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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DeclObjC.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/ExprObjC.h"
21 #include "clang/AST/RecursiveASTVisitor.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/Lookup.h"
25 #include "clang/Sema/Scope.h"
26 #include "clang/Sema/ScopeInfo.h"
27 #include "clang/Sema/SemaInternal.h"
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseSet.h"
31 using namespace clang;
33 /// Check whether the given method, which must be in the 'init'
34 /// family, is a valid member of that family.
36 /// \param receiverTypeIfCall - if null, check this as if declaring it;
37 /// if non-null, check this as if making a call to it with the given
40 /// \return true to indicate that there was an error and appropriate
41 /// actions were taken
42 bool Sema::checkInitMethod(ObjCMethodDecl *method,
43 QualType receiverTypeIfCall) {
44 if (method->isInvalidDecl()) return true;
46 // This castAs is safe: methods that don't return an object
47 // pointer won't be inferred as inits and will reject an explicit
48 // objc_method_family(init).
50 // We ignore protocols here. Should we? What about Class?
52 const ObjCObjectType *result =
53 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
55 if (result->isObjCId()) {
57 } else if (result->isObjCClass()) {
58 // fall through: always an error
60 ObjCInterfaceDecl *resultClass = result->getInterface();
61 assert(resultClass && "unexpected object type!");
63 // It's okay for the result type to still be a forward declaration
64 // if we're checking an interface declaration.
65 if (!resultClass->hasDefinition()) {
66 if (receiverTypeIfCall.isNull() &&
67 !isa<ObjCImplementationDecl>(method->getDeclContext()))
70 // Otherwise, we try to compare class types.
72 // If this method was declared in a protocol, we can't check
73 // anything unless we have a receiver type that's an interface.
74 const ObjCInterfaceDecl *receiverClass = nullptr;
75 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76 if (receiverTypeIfCall.isNull())
79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
82 // This can be null for calls to e.g. id<Foo>.
83 if (!receiverClass) return false;
85 receiverClass = method->getClassInterface();
86 assert(receiverClass && "method not associated with a class!");
89 // If either class is a subclass of the other, it's fine.
90 if (receiverClass->isSuperClassOf(resultClass) ||
91 resultClass->isSuperClassOf(receiverClass))
96 SourceLocation loc = method->getLocation();
98 // If we're in a system header, and this is not a call, just make
99 // the method unusable.
100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
101 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
112 /// Issue a warning if the parameter of the overridden method is non-escaping
113 /// but the parameter of the overriding method is not.
114 static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
116 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
117 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
118 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
125 /// Produce additional diagnostics if a category conforms to a protocol that
126 /// defines a method taking a non-escaping parameter.
127 static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
128 const ObjCCategoryDecl *CD,
129 const ObjCProtocolDecl *PD, Sema &S) {
130 if (!diagnoseNoescape(NewD, OldD, S))
131 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
132 << CD->IsClassExtension() << PD
133 << cast<ObjCMethodDecl>(NewD->getDeclContext());
136 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
137 const ObjCMethodDecl *Overridden) {
138 if (Overridden->hasRelatedResultType() &&
139 !NewMethod->hasRelatedResultType()) {
140 // This can only happen when the method follows a naming convention that
141 // implies a related result type, and the original (overridden) method has
142 // a suitable return type, but the new (overriding) method does not have
143 // a suitable return type.
144 QualType ResultType = NewMethod->getReturnType();
145 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
147 // Figure out which class this method is part of, if any.
148 ObjCInterfaceDecl *CurrentClass
149 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
151 DeclContext *DC = NewMethod->getDeclContext();
152 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
153 CurrentClass = Cat->getClassInterface();
154 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
155 CurrentClass = Impl->getClassInterface();
156 else if (ObjCCategoryImplDecl *CatImpl
157 = dyn_cast<ObjCCategoryImplDecl>(DC))
158 CurrentClass = CatImpl->getClassInterface();
162 Diag(NewMethod->getLocation(),
163 diag::warn_related_result_type_compatibility_class)
164 << Context.getObjCInterfaceType(CurrentClass)
168 Diag(NewMethod->getLocation(),
169 diag::warn_related_result_type_compatibility_protocol)
174 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
175 Diag(Overridden->getLocation(),
176 diag::note_related_result_type_family)
177 << /*overridden method*/ 0
180 Diag(Overridden->getLocation(),
181 diag::note_related_result_type_overridden);
184 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
185 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
186 Diag(NewMethod->getLocation(),
187 getLangOpts().ObjCAutoRefCount
188 ? diag::err_nsreturns_retained_attribute_mismatch
189 : diag::warn_nsreturns_retained_attribute_mismatch)
191 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
193 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
194 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
195 Diag(NewMethod->getLocation(),
196 getLangOpts().ObjCAutoRefCount
197 ? diag::err_nsreturns_retained_attribute_mismatch
198 : diag::warn_nsreturns_retained_attribute_mismatch)
200 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
203 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
204 oe = Overridden->param_end();
205 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
206 ne = NewMethod->param_end();
207 ni != ne && oi != oe; ++ni, ++oi) {
208 const ParmVarDecl *oldDecl = (*oi);
209 ParmVarDecl *newDecl = (*ni);
210 if (newDecl->hasAttr<NSConsumedAttr>() !=
211 oldDecl->hasAttr<NSConsumedAttr>()) {
212 Diag(newDecl->getLocation(),
213 getLangOpts().ObjCAutoRefCount
214 ? diag::err_nsconsumed_attribute_mismatch
215 : diag::warn_nsconsumed_attribute_mismatch);
216 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
219 diagnoseNoescape(newDecl, oldDecl, *this);
223 /// Check a method declaration for compatibility with the Objective-C
225 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
226 ObjCMethodFamily family = method->getMethodFamily();
232 case OMF_autorelease:
233 case OMF_retainCount:
236 case OMF_performSelector:
240 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
241 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
242 if (ResultTypeRange.isInvalid())
243 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
244 << method->getReturnType()
245 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
247 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
248 << method->getReturnType()
249 << FixItHint::CreateReplacement(ResultTypeRange, "void");
255 // If the method doesn't obey the init rules, don't bother annotating it.
256 if (checkInitMethod(method, QualType()))
259 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
261 // Don't add a second copy of this attribute, but otherwise don't
262 // let it be suppressed.
263 if (method->hasAttr<NSReturnsRetainedAttr>())
269 case OMF_mutableCopy:
271 if (method->hasAttr<NSReturnsRetainedAttr>() ||
272 method->hasAttr<NSReturnsNotRetainedAttr>() ||
273 method->hasAttr<NSReturnsAutoreleasedAttr>())
278 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
282 static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
283 SourceLocation ImplLoc) {
286 bool IsCategory = false;
287 StringRef RealizedPlatform;
288 AvailabilityResult Availability = ND->getAvailability(
289 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
291 if (Availability != AR_Deprecated) {
292 if (isa<ObjCMethodDecl>(ND)) {
293 if (Availability != AR_Unavailable)
295 if (RealizedPlatform.empty())
296 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
297 // Warn about implementing unavailable methods, unless the unavailable
298 // is for an app extension.
299 if (RealizedPlatform.endswith("_app_extension"))
301 S.Diag(ImplLoc, diag::warn_unavailable_def);
302 S.Diag(ND->getLocation(), diag::note_method_declared_at)
303 << ND->getDeclName();
306 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
307 if (!CD->getClassInterface()->isDeprecated())
309 ND = CD->getClassInterface();
314 S.Diag(ImplLoc, diag::warn_deprecated_def)
315 << (isa<ObjCMethodDecl>(ND)
317 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
319 if (isa<ObjCMethodDecl>(ND))
320 S.Diag(ND->getLocation(), diag::note_method_declared_at)
321 << ND->getDeclName();
323 S.Diag(ND->getLocation(), diag::note_previous_decl)
324 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
327 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
329 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
330 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
332 // If we don't have a valid method decl, simply return.
335 if (MDecl->isInstanceMethod())
336 AddInstanceMethodToGlobalPool(MDecl, true);
338 AddFactoryMethodToGlobalPool(MDecl, true);
341 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
342 /// has explicit ownership attribute; false otherwise.
344 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
345 QualType T = Param->getType();
347 if (const PointerType *PT = T->getAs<PointerType>()) {
348 T = PT->getPointeeType();
349 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
350 T = RT->getPointeeType();
355 // If we have a lifetime qualifier, but it's local, we must have
356 // inferred it. So, it is implicit.
357 return !T.getLocalQualifiers().hasObjCLifetime();
360 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
361 /// and user declared, in the method definition's AST.
362 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
363 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
364 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
366 PushExpressionEvaluationContext(ExprEvalContexts.back().Context);
368 // If we don't have a valid method decl, simply return.
372 QualType ResultType = MDecl->getReturnType();
373 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
374 !MDecl->isInvalidDecl() &&
375 RequireCompleteType(MDecl->getLocation(), ResultType,
376 diag::err_func_def_incomplete_result))
377 MDecl->setInvalidDecl();
379 // Allow all of Sema to see that we are entering a method definition.
380 PushDeclContext(FnBodyScope, MDecl);
383 // Create Decl objects for each parameter, entrring them in the scope for
384 // binding to their use.
386 // Insert the invisible arguments, self and _cmd!
387 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
389 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
390 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
392 // The ObjC parser requires parameter names so there's no need to check.
393 CheckParmsForFunctionDef(MDecl->parameters(),
394 /*CheckParameterNames=*/false);
396 // Introduce all of the other parameters into this scope.
397 for (auto *Param : MDecl->parameters()) {
398 if (!Param->isInvalidDecl() &&
399 getLangOpts().ObjCAutoRefCount &&
400 !HasExplicitOwnershipAttr(*this, Param))
401 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
404 if (Param->getIdentifier())
405 PushOnScopeChains(Param, FnBodyScope);
408 // In ARC, disallow definition of retain/release/autorelease/retainCount
409 if (getLangOpts().ObjCAutoRefCount) {
410 switch (MDecl->getMethodFamily()) {
412 case OMF_retainCount:
414 case OMF_autorelease:
415 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
416 << 0 << MDecl->getSelector();
424 case OMF_mutableCopy:
429 case OMF_performSelector:
434 // Warn on deprecated methods under -Wdeprecated-implementations,
435 // and prepare for warning on missing super calls.
436 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
437 ObjCMethodDecl *IMD =
438 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
441 ObjCImplDecl *ImplDeclOfMethodDef =
442 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
443 ObjCContainerDecl *ContDeclOfMethodDecl =
444 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
445 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
446 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
447 ImplDeclOfMethodDecl = OID->getImplementation();
448 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
449 if (CD->IsClassExtension()) {
450 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
451 ImplDeclOfMethodDecl = OID->getImplementation();
453 ImplDeclOfMethodDecl = CD->getImplementation();
455 // No need to issue deprecated warning if deprecated mehod in class/category
456 // is being implemented in its own implementation (no overriding is involved).
457 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
458 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
461 if (MDecl->getMethodFamily() == OMF_init) {
462 if (MDecl->isDesignatedInitializerForTheInterface()) {
463 getCurFunction()->ObjCIsDesignatedInit = true;
464 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
465 IC->getSuperClass() != nullptr;
466 } else if (IC->hasDesignatedInitializers()) {
467 getCurFunction()->ObjCIsSecondaryInit = true;
468 getCurFunction()->ObjCWarnForNoInitDelegation = true;
472 // If this is "dealloc" or "finalize", set some bit here.
473 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
474 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
475 // Only do this if the current class actually has a superclass.
476 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
477 ObjCMethodFamily Family = MDecl->getMethodFamily();
478 if (Family == OMF_dealloc) {
479 if (!(getLangOpts().ObjCAutoRefCount ||
480 getLangOpts().getGC() == LangOptions::GCOnly))
481 getCurFunction()->ObjCShouldCallSuper = true;
483 } else if (Family == OMF_finalize) {
484 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
485 getCurFunction()->ObjCShouldCallSuper = true;
488 const ObjCMethodDecl *SuperMethod =
489 SuperClass->lookupMethod(MDecl->getSelector(),
490 MDecl->isInstanceMethod());
491 getCurFunction()->ObjCShouldCallSuper =
492 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
500 // Callback to only accept typo corrections that are Objective-C classes.
501 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
502 // function will reject corrections to that class.
503 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
505 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
506 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
507 : CurrentIDecl(IDecl) {}
509 bool ValidateCandidate(const TypoCorrection &candidate) override {
510 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
511 return ID && !declaresSameEntity(ID, CurrentIDecl);
515 ObjCInterfaceDecl *CurrentIDecl;
518 } // end anonymous namespace
520 static void diagnoseUseOfProtocols(Sema &TheSema,
521 ObjCContainerDecl *CD,
522 ObjCProtocolDecl *const *ProtoRefs,
523 unsigned NumProtoRefs,
524 const SourceLocation *ProtoLocs) {
526 // Diagnose availability in the context of the ObjC container.
527 Sema::ContextRAII SavedContext(TheSema, CD);
528 for (unsigned i = 0; i < NumProtoRefs; ++i) {
529 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
530 /*UnknownObjCClass=*/nullptr,
531 /*ObjCPropertyAccess=*/false,
532 /*AvoidPartialAvailabilityChecks=*/true);
537 ActOnSuperClassOfClassInterface(Scope *S,
538 SourceLocation AtInterfaceLoc,
539 ObjCInterfaceDecl *IDecl,
540 IdentifierInfo *ClassName,
541 SourceLocation ClassLoc,
542 IdentifierInfo *SuperName,
543 SourceLocation SuperLoc,
544 ArrayRef<ParsedType> SuperTypeArgs,
545 SourceRange SuperTypeArgsRange) {
546 // Check if a different kind of symbol declared in this scope.
547 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
551 // Try to correct for a typo in the superclass name without correcting
552 // to the class we're defining.
553 if (TypoCorrection Corrected = CorrectTypo(
554 DeclarationNameInfo(SuperName, SuperLoc),
555 LookupOrdinaryName, TUScope,
556 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
557 CTK_ErrorRecovery)) {
558 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
559 << SuperName << ClassName);
560 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
564 if (declaresSameEntity(PrevDecl, IDecl)) {
565 Diag(SuperLoc, diag::err_recursive_superclass)
566 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
567 IDecl->setEndOfDefinitionLoc(ClassLoc);
569 ObjCInterfaceDecl *SuperClassDecl =
570 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
571 QualType SuperClassType;
573 // Diagnose classes that inherit from deprecated classes.
574 if (SuperClassDecl) {
575 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
576 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
579 if (PrevDecl && !SuperClassDecl) {
580 // The previous declaration was not a class decl. Check if we have a
581 // typedef. If we do, get the underlying class type.
582 if (const TypedefNameDecl *TDecl =
583 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
584 QualType T = TDecl->getUnderlyingType();
585 if (T->isObjCObjectType()) {
586 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
587 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
588 SuperClassType = Context.getTypeDeclType(TDecl);
590 // This handles the following case:
591 // @interface NewI @end
592 // typedef NewI DeprI __attribute__((deprecated("blah")))
593 // @interface SI : DeprI /* warn here */ @end
594 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
599 // This handles the following case:
601 // typedef int SuperClass;
602 // @interface MyClass : SuperClass {} @end
604 if (!SuperClassDecl) {
605 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
606 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
610 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
612 Diag(SuperLoc, diag::err_undef_superclass)
613 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
614 else if (RequireCompleteType(SuperLoc,
616 diag::err_forward_superclass,
617 SuperClassDecl->getDeclName(),
619 SourceRange(AtInterfaceLoc, ClassLoc))) {
620 SuperClassDecl = nullptr;
621 SuperClassType = QualType();
625 if (SuperClassType.isNull()) {
626 assert(!SuperClassDecl && "Failed to set SuperClassType?");
630 // Handle type arguments on the superclass.
631 TypeSourceInfo *SuperClassTInfo = nullptr;
632 if (!SuperTypeArgs.empty()) {
633 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
636 CreateParsedType(SuperClassType,
638 SuperTypeArgsRange.getBegin(),
640 SuperTypeArgsRange.getEnd(),
645 if (!fullSuperClassType.isUsable())
648 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
652 if (!SuperClassTInfo) {
653 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
657 IDecl->setSuperClass(SuperClassTInfo);
658 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getEndLoc());
662 DeclResult Sema::actOnObjCTypeParam(Scope *S,
663 ObjCTypeParamVariance variance,
664 SourceLocation varianceLoc,
666 IdentifierInfo *paramName,
667 SourceLocation paramLoc,
668 SourceLocation colonLoc,
669 ParsedType parsedTypeBound) {
670 // If there was an explicitly-provided type bound, check it.
671 TypeSourceInfo *typeBoundInfo = nullptr;
672 if (parsedTypeBound) {
673 // The type bound can be any Objective-C pointer type.
674 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
675 if (typeBound->isObjCObjectPointerType()) {
677 } else if (typeBound->isObjCObjectType()) {
678 // The user forgot the * on an Objective-C pointer type, e.g.,
680 SourceLocation starLoc = getLocForEndOfToken(
681 typeBoundInfo->getTypeLoc().getEndLoc());
682 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
683 diag::err_objc_type_param_bound_missing_pointer)
684 << typeBound << paramName
685 << FixItHint::CreateInsertion(starLoc, " *");
687 // Create a new type location builder so we can update the type
688 // location information we have.
689 TypeLocBuilder builder;
690 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
692 // Create the Objective-C pointer type.
693 typeBound = Context.getObjCObjectPointerType(typeBound);
694 ObjCObjectPointerTypeLoc newT
695 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
696 newT.setStarLoc(starLoc);
698 // Form the new type source information.
699 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
701 // Not a valid type bound.
702 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
703 diag::err_objc_type_param_bound_nonobject)
704 << typeBound << paramName;
706 // Forget the bound; we'll default to id later.
707 typeBoundInfo = nullptr;
710 // Type bounds cannot have qualifiers (even indirectly) or explicit
713 QualType typeBound = typeBoundInfo->getType();
714 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
715 if (qual || typeBound.hasQualifiers()) {
716 bool diagnosed = false;
717 SourceRange rangeToRemove;
719 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
720 rangeToRemove = attr.getLocalSourceRange();
721 if (attr.getTypePtr()->getImmediateNullability()) {
722 Diag(attr.getBeginLoc(),
723 diag::err_objc_type_param_bound_explicit_nullability)
724 << paramName << typeBound
725 << FixItHint::CreateRemoval(rangeToRemove);
732 Diag(qual ? qual.getBeginLoc()
733 : typeBoundInfo->getTypeLoc().getBeginLoc(),
734 diag::err_objc_type_param_bound_qualified)
735 << paramName << typeBound
736 << typeBound.getQualifiers().getAsString()
737 << FixItHint::CreateRemoval(rangeToRemove);
740 // If the type bound has qualifiers other than CVR, we need to strip
741 // them or we'll probably assert later when trying to apply new
743 Qualifiers quals = typeBound.getQualifiers();
744 quals.removeCVRQualifiers();
745 if (!quals.empty()) {
747 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
753 // If there was no explicit type bound (or we removed it due to an error),
755 if (!typeBoundInfo) {
756 colonLoc = SourceLocation();
757 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
760 // Create the type parameter.
761 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
762 index, paramLoc, paramName, colonLoc,
766 ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
767 SourceLocation lAngleLoc,
768 ArrayRef<Decl *> typeParamsIn,
769 SourceLocation rAngleLoc) {
770 // We know that the array only contains Objective-C type parameters.
771 ArrayRef<ObjCTypeParamDecl *>
773 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
774 typeParamsIn.size());
776 // Diagnose redeclarations of type parameters.
777 // We do this now because Objective-C type parameters aren't pushed into
778 // scope until later (after the instance variable block), but we want the
779 // diagnostics to occur right after we parse the type parameter list.
780 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
781 for (auto typeParam : typeParams) {
782 auto known = knownParams.find(typeParam->getIdentifier());
783 if (known != knownParams.end()) {
784 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
785 << typeParam->getIdentifier()
786 << SourceRange(known->second->getLocation());
788 typeParam->setInvalidDecl();
790 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
792 // Push the type parameter into scope.
793 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
797 // Create the parameter list.
798 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
801 void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
802 for (auto typeParam : *typeParamList) {
803 if (!typeParam->isInvalidDecl()) {
804 S->RemoveDecl(typeParam);
805 IdResolver.RemoveDecl(typeParam);
811 /// The context in which an Objective-C type parameter list occurs, for use
813 enum class TypeParamListContext {
819 } // end anonymous namespace
821 /// Check consistency between two Objective-C type parameter lists, e.g.,
822 /// between a category/extension and an \@interface or between an \@class and an
824 static bool checkTypeParamListConsistency(Sema &S,
825 ObjCTypeParamList *prevTypeParams,
826 ObjCTypeParamList *newTypeParams,
827 TypeParamListContext newContext) {
828 // If the sizes don't match, complain about that.
829 if (prevTypeParams->size() != newTypeParams->size()) {
830 SourceLocation diagLoc;
831 if (newTypeParams->size() > prevTypeParams->size()) {
832 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
834 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getEndLoc());
837 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
838 << static_cast<unsigned>(newContext)
839 << (newTypeParams->size() > prevTypeParams->size())
840 << prevTypeParams->size()
841 << newTypeParams->size();
846 // Match up the type parameters.
847 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
848 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
849 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
851 // Check for consistency of the variance.
852 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
853 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
854 newContext != TypeParamListContext::Definition) {
855 // When the new type parameter is invariant and is not part
856 // of the definition, just propagate the variance.
857 newTypeParam->setVariance(prevTypeParam->getVariance());
858 } else if (prevTypeParam->getVariance()
859 == ObjCTypeParamVariance::Invariant &&
860 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
861 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
862 ->getDefinition() == prevTypeParam->getDeclContext())) {
863 // When the old parameter is invariant and was not part of the
864 // definition, just ignore the difference because it doesn't
868 // Diagnose the conflict and update the second declaration.
869 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
870 if (diagLoc.isInvalid())
871 diagLoc = newTypeParam->getBeginLoc();
873 auto diag = S.Diag(diagLoc,
874 diag::err_objc_type_param_variance_conflict)
875 << static_cast<unsigned>(newTypeParam->getVariance())
876 << newTypeParam->getDeclName()
877 << static_cast<unsigned>(prevTypeParam->getVariance())
878 << prevTypeParam->getDeclName();
879 switch (prevTypeParam->getVariance()) {
880 case ObjCTypeParamVariance::Invariant:
881 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
884 case ObjCTypeParamVariance::Covariant:
885 case ObjCTypeParamVariance::Contravariant: {
886 StringRef newVarianceStr
887 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
890 if (newTypeParam->getVariance()
891 == ObjCTypeParamVariance::Invariant) {
892 diag << FixItHint::CreateInsertion(newTypeParam->getBeginLoc(),
893 (newVarianceStr + " ").str());
895 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
902 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
903 << prevTypeParam->getDeclName();
905 // Override the variance.
906 newTypeParam->setVariance(prevTypeParam->getVariance());
910 // If the bound types match, there's nothing to do.
911 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
912 newTypeParam->getUnderlyingType()))
915 // If the new type parameter's bound was explicit, complain about it being
916 // different from the original.
917 if (newTypeParam->hasExplicitBound()) {
918 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
919 ->getTypeLoc().getSourceRange();
920 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
921 << newTypeParam->getUnderlyingType()
922 << newTypeParam->getDeclName()
923 << prevTypeParam->hasExplicitBound()
924 << prevTypeParam->getUnderlyingType()
925 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
926 << prevTypeParam->getDeclName()
927 << FixItHint::CreateReplacement(
929 prevTypeParam->getUnderlyingType().getAsString(
930 S.Context.getPrintingPolicy()));
932 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
933 << prevTypeParam->getDeclName();
935 // Override the new type parameter's bound type with the previous type,
936 // so that it's consistent.
937 newTypeParam->setTypeSourceInfo(
938 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
942 // The new type parameter got the implicit bound of 'id'. That's okay for
943 // categories and extensions (overwrite it later), but not for forward
944 // declarations and @interfaces, because those must be standalone.
945 if (newContext == TypeParamListContext::ForwardDeclaration ||
946 newContext == TypeParamListContext::Definition) {
947 // Diagnose this problem for forward declarations and definitions.
948 SourceLocation insertionLoc
949 = S.getLocForEndOfToken(newTypeParam->getLocation());
951 = " : " + prevTypeParam->getUnderlyingType().getAsString(
952 S.Context.getPrintingPolicy());
953 S.Diag(newTypeParam->getLocation(),
954 diag::err_objc_type_param_bound_missing)
955 << prevTypeParam->getUnderlyingType()
956 << newTypeParam->getDeclName()
957 << (newContext == TypeParamListContext::ForwardDeclaration)
958 << FixItHint::CreateInsertion(insertionLoc, newCode);
960 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
961 << prevTypeParam->getDeclName();
964 // Update the new type parameter's bound to match the previous one.
965 newTypeParam->setTypeSourceInfo(
966 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
972 Decl *Sema::ActOnStartClassInterface(
973 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
974 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
975 IdentifierInfo *SuperName, SourceLocation SuperLoc,
976 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
977 Decl *const *ProtoRefs, unsigned NumProtoRefs,
978 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
979 const ParsedAttributesView &AttrList) {
980 assert(ClassName && "Missing class identifier");
982 // Check for another declaration kind with the same name.
983 NamedDecl *PrevDecl =
984 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
985 forRedeclarationInCurContext());
987 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
988 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
989 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
992 // Create a declaration to describe this @interface.
993 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
995 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
996 // A previous decl with a different name is because of
997 // @compatibility_alias, for example:
1000 // @compatibility_alias OldImage NewImage;
1002 // A lookup for 'OldImage' will return the 'NewImage' decl.
1004 // In such a case use the real declaration name, instead of the alias one,
1005 // otherwise we will break IdentifierResolver and redecls-chain invariants.
1006 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1007 // has been aliased.
1008 ClassName = PrevIDecl->getIdentifier();
1011 // If there was a forward declaration with type parameters, check
1014 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1015 if (typeParamList) {
1016 // Both have type parameter lists; check for consistency.
1017 if (checkTypeParamListConsistency(*this, prevTypeParamList,
1019 TypeParamListContext::Definition)) {
1020 typeParamList = nullptr;
1023 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1025 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1028 // Clone the type parameter list.
1029 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1030 for (auto typeParam : *prevTypeParamList) {
1031 clonedTypeParams.push_back(
1032 ObjCTypeParamDecl::Create(
1035 typeParam->getVariance(),
1037 typeParam->getIndex(),
1039 typeParam->getIdentifier(),
1041 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1044 typeParamList = ObjCTypeParamList::create(Context,
1052 ObjCInterfaceDecl *IDecl
1053 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
1054 typeParamList, PrevIDecl, ClassLoc);
1056 // Class already seen. Was it a definition?
1057 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1058 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1059 << PrevIDecl->getDeclName();
1060 Diag(Def->getLocation(), diag::note_previous_definition);
1061 IDecl->setInvalidDecl();
1065 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
1066 AddPragmaAttributes(TUScope, IDecl);
1067 PushOnScopeChains(IDecl, TUScope);
1069 // Start the definition of this class. If we're in a redefinition case, there
1070 // may already be a definition, so we'll end up adding to it.
1071 if (!IDecl->hasDefinition())
1072 IDecl->startDefinition();
1075 // Diagnose availability in the context of the @interface.
1076 ContextRAII SavedContext(*this, IDecl);
1078 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1079 ClassName, ClassLoc,
1080 SuperName, SuperLoc, SuperTypeArgs,
1081 SuperTypeArgsRange);
1082 } else { // we have a root class.
1083 IDecl->setEndOfDefinitionLoc(ClassLoc);
1086 // Check then save referenced protocols.
1088 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1089 NumProtoRefs, ProtoLocs);
1090 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1091 ProtoLocs, Context);
1092 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1095 CheckObjCDeclScope(IDecl);
1096 return ActOnObjCContainerStartDefinition(IDecl);
1099 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
1100 /// typedef'ed use for a qualified super class and adds them to the list
1101 /// of the protocols.
1102 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1103 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1104 IdentifierInfo *SuperName,
1105 SourceLocation SuperLoc) {
1108 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1109 LookupOrdinaryName);
1113 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1114 QualType T = TDecl->getUnderlyingType();
1115 if (T->isObjCObjectType())
1116 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1117 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1118 // FIXME: Consider whether this should be an invalid loc since the loc
1119 // is not actually pointing to a protocol name reference but to the
1120 // typedef reference. Note that the base class name loc is also pointing
1122 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1127 /// ActOnCompatibilityAlias - this action is called after complete parsing of
1128 /// a \@compatibility_alias declaration. It sets up the alias relationships.
1129 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1130 IdentifierInfo *AliasName,
1131 SourceLocation AliasLocation,
1132 IdentifierInfo *ClassName,
1133 SourceLocation ClassLocation) {
1134 // Look for previous declaration of alias name
1136 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1137 forRedeclarationInCurContext());
1139 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1140 Diag(ADecl->getLocation(), diag::note_previous_declaration);
1143 // Check for class declaration
1145 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1146 forRedeclarationInCurContext());
1147 if (const TypedefNameDecl *TDecl =
1148 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1149 QualType T = TDecl->getUnderlyingType();
1150 if (T->isObjCObjectType()) {
1151 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
1152 ClassName = IDecl->getIdentifier();
1153 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1155 forRedeclarationInCurContext());
1159 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1161 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1163 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1167 // Everything checked out, instantiate a new alias declaration AST.
1168 ObjCCompatibleAliasDecl *AliasDecl =
1169 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
1171 if (!CheckObjCDeclScope(AliasDecl))
1172 PushOnScopeChains(AliasDecl, TUScope);
1177 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
1178 IdentifierInfo *PName,
1179 SourceLocation &Ploc, SourceLocation PrevLoc,
1180 const ObjCList<ObjCProtocolDecl> &PList) {
1183 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1184 E = PList.end(); I != E; ++I) {
1185 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1187 if (PDecl->getIdentifier() == PName) {
1188 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1189 Diag(PrevLoc, diag::note_previous_definition);
1193 if (!PDecl->hasDefinition())
1196 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1197 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1204 Decl *Sema::ActOnStartProtocolInterface(
1205 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1206 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1207 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1208 const ParsedAttributesView &AttrList) {
1210 // FIXME: Deal with AttrList.
1211 assert(ProtocolName && "Missing protocol identifier");
1212 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1213 forRedeclarationInCurContext());
1214 ObjCProtocolDecl *PDecl = nullptr;
1215 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1216 // If we already have a definition, complain.
1217 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1218 Diag(Def->getLocation(), diag::note_previous_definition);
1220 // Create a new protocol that is completely distinct from previous
1221 // declarations, and do not make this protocol available for name lookup.
1222 // That way, we'll end up completely ignoring the duplicate.
1223 // FIXME: Can we turn this into an error?
1224 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1225 ProtocolLoc, AtProtoInterfaceLoc,
1226 /*PrevDecl=*/nullptr);
1228 // If we are using modules, add the decl to the context in order to
1229 // serialize something meaningful.
1230 if (getLangOpts().Modules)
1231 PushOnScopeChains(PDecl, TUScope);
1232 PDecl->startDefinition();
1235 // Check for circular dependencies among protocol declarations. This can
1236 // only happen if this protocol was forward-declared.
1237 ObjCList<ObjCProtocolDecl> PList;
1238 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1239 err = CheckForwardProtocolDeclarationForCircularDependency(
1240 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1243 // Create the new declaration.
1244 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1245 ProtocolLoc, AtProtoInterfaceLoc,
1246 /*PrevDecl=*/PrevDecl);
1248 PushOnScopeChains(PDecl, TUScope);
1249 PDecl->startDefinition();
1252 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
1253 AddPragmaAttributes(TUScope, PDecl);
1255 // Merge attributes from previous declarations.
1257 mergeDeclAttributes(PDecl, PrevDecl);
1259 if (!err && NumProtoRefs ) {
1260 /// Check then save referenced protocols.
1261 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1262 NumProtoRefs, ProtoLocs);
1263 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1264 ProtoLocs, Context);
1267 CheckObjCDeclScope(PDecl);
1268 return ActOnObjCContainerStartDefinition(PDecl);
1271 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1272 ObjCProtocolDecl *&UndefinedProtocol) {
1273 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1274 UndefinedProtocol = PDecl;
1278 for (auto *PI : PDecl->protocols())
1279 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1280 UndefinedProtocol = PI;
1286 /// FindProtocolDeclaration - This routine looks up protocols and
1287 /// issues an error if they are not declared. It returns list of
1288 /// protocol declarations in its 'Protocols' argument.
1290 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
1291 ArrayRef<IdentifierLocPair> ProtocolId,
1292 SmallVectorImpl<Decl *> &Protocols) {
1293 for (const IdentifierLocPair &Pair : ProtocolId) {
1294 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1296 TypoCorrection Corrected = CorrectTypo(
1297 DeclarationNameInfo(Pair.first, Pair.second),
1298 LookupObjCProtocolName, TUScope, nullptr,
1299 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
1301 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1302 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1307 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1310 // If this is a forward protocol declaration, get its definition.
1311 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1312 PDecl = PDecl->getDefinition();
1314 // For an objc container, delay protocol reference checking until after we
1315 // can set the objc decl as the availability context, otherwise check now.
1316 if (!ForObjCContainer) {
1317 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
1320 // If this is a forward declaration and we are supposed to warn in this
1322 // FIXME: Recover nicely in the hidden case.
1323 ObjCProtocolDecl *UndefinedProtocol;
1325 if (WarnOnDeclarations &&
1326 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1327 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1328 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1329 << UndefinedProtocol;
1331 Protocols.push_back(PDecl);
1336 // Callback to only accept typo corrections that are either
1337 // Objective-C protocols or valid Objective-C type arguments.
1338 class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1339 ASTContext &Context;
1340 Sema::LookupNameKind LookupKind;
1342 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1343 Sema::LookupNameKind lookupKind)
1344 : Context(context), LookupKind(lookupKind) { }
1346 bool ValidateCandidate(const TypoCorrection &candidate) override {
1347 // If we're allowed to find protocols and we have a protocol, accept it.
1348 if (LookupKind != Sema::LookupOrdinaryName) {
1349 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1353 // If we're allowed to find type names and we have one, accept it.
1354 if (LookupKind != Sema::LookupObjCProtocolName) {
1355 // If we have a type declaration, we might accept this result.
1356 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1357 // If we found a tag declaration outside of C++, skip it. This
1358 // can happy because we look for any name when there is no
1359 // bias to protocol or type names.
1360 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1363 // Make sure the type is something we would accept as a type
1365 auto type = Context.getTypeDeclType(typeDecl);
1366 if (type->isObjCObjectPointerType() ||
1367 type->isBlockPointerType() ||
1368 type->isDependentType() ||
1369 type->isObjCObjectType())
1375 // If we have an Objective-C class type, accept it; there will
1376 // be another fix to add the '*'.
1377 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1386 } // end anonymous namespace
1388 void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1389 SourceLocation ProtocolLoc,
1390 IdentifierInfo *TypeArgId,
1391 SourceLocation TypeArgLoc,
1392 bool SelectProtocolFirst) {
1393 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1394 << SelectProtocolFirst << TypeArgId << ProtocolId
1395 << SourceRange(ProtocolLoc);
1398 void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1400 ParsedType baseType,
1401 SourceLocation lAngleLoc,
1402 ArrayRef<IdentifierInfo *> identifiers,
1403 ArrayRef<SourceLocation> identifierLocs,
1404 SourceLocation rAngleLoc,
1405 SourceLocation &typeArgsLAngleLoc,
1406 SmallVectorImpl<ParsedType> &typeArgs,
1407 SourceLocation &typeArgsRAngleLoc,
1408 SourceLocation &protocolLAngleLoc,
1409 SmallVectorImpl<Decl *> &protocols,
1410 SourceLocation &protocolRAngleLoc,
1411 bool warnOnIncompleteProtocols) {
1412 // Local function that updates the declaration specifiers with
1413 // protocol information.
1414 unsigned numProtocolsResolved = 0;
1415 auto resolvedAsProtocols = [&] {
1416 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1418 // Determine whether the base type is a parameterized class, in
1419 // which case we want to warn about typos such as
1420 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1421 ObjCInterfaceDecl *baseClass = nullptr;
1422 QualType base = GetTypeFromParser(baseType, nullptr);
1423 bool allAreTypeNames = false;
1424 SourceLocation firstClassNameLoc;
1425 if (!base.isNull()) {
1426 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1427 baseClass = objcObjectType->getInterface();
1429 if (auto typeParams = baseClass->getTypeParamList()) {
1430 if (typeParams->size() == numProtocolsResolved) {
1431 // Note that we should be looking for type names, too.
1432 allAreTypeNames = true;
1439 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1440 ObjCProtocolDecl *&proto
1441 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1442 // For an objc container, delay protocol reference checking until after we
1443 // can set the objc decl as the availability context, otherwise check now.
1444 if (!warnOnIncompleteProtocols) {
1445 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1448 // If this is a forward protocol declaration, get its definition.
1449 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1450 proto = proto->getDefinition();
1452 // If this is a forward declaration and we are supposed to warn in this
1454 // FIXME: Recover nicely in the hidden case.
1455 ObjCProtocolDecl *forwardDecl = nullptr;
1456 if (warnOnIncompleteProtocols &&
1457 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1458 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1459 << proto->getDeclName();
1460 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1464 // If everything this far has been a type name (and we care
1465 // about such things), check whether this name refers to a type
1467 if (allAreTypeNames) {
1468 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1469 LookupOrdinaryName)) {
1470 if (isa<ObjCInterfaceDecl>(decl)) {
1471 if (firstClassNameLoc.isInvalid())
1472 firstClassNameLoc = identifierLocs[i];
1473 } else if (!isa<TypeDecl>(decl)) {
1475 allAreTypeNames = false;
1478 allAreTypeNames = false;
1483 // All of the protocols listed also have type names, and at least
1484 // one is an Objective-C class name. Check whether all of the
1485 // protocol conformances are declared by the base class itself, in
1486 // which case we warn.
1487 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1488 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1489 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1490 bool allProtocolsDeclared = true;
1491 for (auto proto : protocols) {
1492 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1493 allProtocolsDeclared = false;
1498 if (allProtocolsDeclared) {
1499 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1500 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1501 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1506 protocolLAngleLoc = lAngleLoc;
1507 protocolRAngleLoc = rAngleLoc;
1508 assert(protocols.size() == identifierLocs.size());
1511 // Attempt to resolve all of the identifiers as protocols.
1512 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1513 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1514 protocols.push_back(proto);
1516 ++numProtocolsResolved;
1519 // If all of the names were protocols, these were protocol qualifiers.
1520 if (numProtocolsResolved == identifiers.size())
1521 return resolvedAsProtocols();
1523 // Attempt to resolve all of the identifiers as type names or
1524 // Objective-C class names. The latter is technically ill-formed,
1525 // but is probably something like \c NSArray<NSView *> missing the
1527 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1528 SmallVector<TypeOrClassDecl, 4> typeDecls;
1529 unsigned numTypeDeclsResolved = 0;
1530 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1531 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1532 LookupOrdinaryName);
1534 typeDecls.push_back(TypeOrClassDecl());
1538 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1539 typeDecls.push_back(typeDecl);
1540 ++numTypeDeclsResolved;
1544 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1545 typeDecls.push_back(objcClass);
1546 ++numTypeDeclsResolved;
1550 typeDecls.push_back(TypeOrClassDecl());
1553 AttributeFactory attrFactory;
1555 // Local function that forms a reference to the given type or
1556 // Objective-C class declaration.
1557 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1559 // Form declaration specifiers. They simply refer to the type.
1560 DeclSpec DS(attrFactory);
1561 const char* prevSpec; // unused
1562 unsigned diagID; // unused
1564 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1565 type = Context.getTypeDeclType(actualTypeDecl);
1567 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1568 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1569 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1570 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1571 parsedType, Context.getPrintingPolicy());
1572 // Use the identifier location for the type source range.
1573 DS.SetRangeStart(loc);
1574 DS.SetRangeEnd(loc);
1576 // Form the declarator.
1577 Declarator D(DS, DeclaratorContext::TypeNameContext);
1579 // If we have a typedef of an Objective-C class type that is missing a '*',
1581 if (type->getAs<ObjCInterfaceType>()) {
1582 SourceLocation starLoc = getLocForEndOfToken(loc);
1583 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1591 // Diagnose the missing '*'.
1592 Diag(loc, diag::err_objc_type_arg_missing_star)
1594 << FixItHint::CreateInsertion(starLoc, " *");
1597 // Convert this to a type.
1598 return ActOnTypeName(S, D);
1601 // Local function that updates the declaration specifiers with
1602 // type argument information.
1603 auto resolvedAsTypeDecls = [&] {
1604 // We did not resolve these as protocols.
1607 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1608 // Map type declarations to type arguments.
1609 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1610 // Map type reference to a type.
1611 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1612 if (!type.isUsable()) {
1617 typeArgs.push_back(type.get());
1620 typeArgsLAngleLoc = lAngleLoc;
1621 typeArgsRAngleLoc = rAngleLoc;
1624 // If all of the identifiers can be resolved as type names or
1625 // Objective-C class names, we have type arguments.
1626 if (numTypeDeclsResolved == identifiers.size())
1627 return resolvedAsTypeDecls();
1629 // Error recovery: some names weren't found, or we have a mix of
1630 // type and protocol names. Go resolve all of the unresolved names
1631 // and complain if we can't find a consistent answer.
1632 LookupNameKind lookupKind = LookupAnyName;
1633 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1634 // If we already have a protocol or type. Check whether it is the
1636 if (protocols[i] || typeDecls[i]) {
1637 // If we haven't figured out whether we want types or protocols
1638 // yet, try to figure it out from this name.
1639 if (lookupKind == LookupAnyName) {
1640 // If this name refers to both a protocol and a type (e.g., \c
1641 // NSObject), don't conclude anything yet.
1642 if (protocols[i] && typeDecls[i])
1645 // Otherwise, let this name decide whether we'll be correcting
1646 // toward types or protocols.
1647 lookupKind = protocols[i] ? LookupObjCProtocolName
1648 : LookupOrdinaryName;
1652 // If we want protocols and we have a protocol, there's nothing
1654 if (lookupKind == LookupObjCProtocolName && protocols[i])
1657 // If we want types and we have a type declaration, there's
1658 // nothing more to do.
1659 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1662 // We have a conflict: some names refer to protocols and others
1664 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1665 identifiers[i], identifierLocs[i],
1666 protocols[i] != nullptr);
1673 // Perform typo correction on the name.
1674 TypoCorrection corrected = CorrectTypo(
1675 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1677 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1681 // Did we find a protocol?
1682 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1683 diagnoseTypo(corrected,
1684 PDiag(diag::err_undeclared_protocol_suggest)
1686 lookupKind = LookupObjCProtocolName;
1687 protocols[i] = proto;
1688 ++numProtocolsResolved;
1692 // Did we find a type?
1693 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1694 diagnoseTypo(corrected,
1695 PDiag(diag::err_unknown_typename_suggest)
1697 lookupKind = LookupOrdinaryName;
1698 typeDecls[i] = typeDecl;
1699 ++numTypeDeclsResolved;
1703 // Did we find an Objective-C class?
1704 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1705 diagnoseTypo(corrected,
1706 PDiag(diag::err_unknown_type_or_class_name_suggest)
1707 << identifiers[i] << true);
1708 lookupKind = LookupOrdinaryName;
1709 typeDecls[i] = objcClass;
1710 ++numTypeDeclsResolved;
1715 // We couldn't find anything.
1716 Diag(identifierLocs[i],
1717 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1718 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1719 : diag::err_unknown_typename))
1726 // If all of the names were (corrected to) protocols, these were
1727 // protocol qualifiers.
1728 if (numProtocolsResolved == identifiers.size())
1729 return resolvedAsProtocols();
1731 // Otherwise, all of the names were (corrected to) types.
1732 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1733 return resolvedAsTypeDecls();
1736 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1737 /// a class method in its extension.
1739 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
1740 ObjCInterfaceDecl *ID) {
1742 return; // Possibly due to previous error
1744 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1745 for (auto *MD : ID->methods())
1746 MethodMap[MD->getSelector()] = MD;
1748 if (MethodMap.empty())
1750 for (const auto *Method : CAT->methods()) {
1751 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1753 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1754 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1755 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1756 << Method->getDeclName();
1757 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1762 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1763 Sema::DeclGroupPtrTy
1764 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
1765 ArrayRef<IdentifierLocPair> IdentList,
1766 const ParsedAttributesView &attrList) {
1767 SmallVector<Decl *, 8> DeclsInGroup;
1768 for (const IdentifierLocPair &IdentPair : IdentList) {
1769 IdentifierInfo *Ident = IdentPair.first;
1770 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
1771 forRedeclarationInCurContext());
1772 ObjCProtocolDecl *PDecl
1773 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1774 IdentPair.second, AtProtocolLoc,
1777 PushOnScopeChains(PDecl, TUScope);
1778 CheckObjCDeclScope(PDecl);
1780 ProcessDeclAttributeList(TUScope, PDecl, attrList);
1781 AddPragmaAttributes(TUScope, PDecl);
1784 mergeDeclAttributes(PDecl, PrevDecl);
1786 DeclsInGroup.push_back(PDecl);
1789 return BuildDeclaratorGroup(DeclsInGroup);
1792 Decl *Sema::ActOnStartCategoryInterface(
1793 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1794 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1795 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1796 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1797 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1798 const ParsedAttributesView &AttrList) {
1799 ObjCCategoryDecl *CDecl;
1800 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1802 /// Check that class of this category is already completely declared.
1805 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1806 diag::err_category_forward_interface,
1807 CategoryName == nullptr)) {
1808 // Create an invalid ObjCCategoryDecl to serve as context for
1809 // the enclosing method declarations. We mark the decl invalid
1810 // to make it clear that this isn't a valid AST.
1811 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1812 ClassLoc, CategoryLoc, CategoryName,
1813 IDecl, typeParamList);
1814 CDecl->setInvalidDecl();
1815 CurContext->addDecl(CDecl);
1818 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1819 return ActOnObjCContainerStartDefinition(CDecl);
1822 if (!CategoryName && IDecl->getImplementation()) {
1823 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1824 Diag(IDecl->getImplementation()->getLocation(),
1825 diag::note_implementation_declared);
1829 /// Check for duplicate interface declaration for this category
1830 if (ObjCCategoryDecl *Previous
1831 = IDecl->FindCategoryDeclaration(CategoryName)) {
1832 // Class extensions can be declared multiple times, categories cannot.
1833 Diag(CategoryLoc, diag::warn_dup_category_def)
1834 << ClassName << CategoryName;
1835 Diag(Previous->getLocation(), diag::note_previous_definition);
1839 // If we have a type parameter list, check it.
1840 if (typeParamList) {
1841 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1842 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1844 ? TypeParamListContext::Category
1845 : TypeParamListContext::Extension))
1846 typeParamList = nullptr;
1848 Diag(typeParamList->getLAngleLoc(),
1849 diag::err_objc_parameterized_category_nonclass)
1850 << (CategoryName != nullptr)
1852 << typeParamList->getSourceRange();
1854 typeParamList = nullptr;
1858 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1859 ClassLoc, CategoryLoc, CategoryName, IDecl,
1861 // FIXME: PushOnScopeChains?
1862 CurContext->addDecl(CDecl);
1864 // Process the attributes before looking at protocols to ensure that the
1865 // availability attribute is attached to the category to provide availability
1866 // checking for protocol uses.
1867 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1868 AddPragmaAttributes(TUScope, CDecl);
1871 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1872 NumProtoRefs, ProtoLocs);
1873 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1874 ProtoLocs, Context);
1875 // Protocols in the class extension belong to the class.
1876 if (CDecl->IsClassExtension())
1877 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1878 NumProtoRefs, Context);
1881 CheckObjCDeclScope(CDecl);
1882 return ActOnObjCContainerStartDefinition(CDecl);
1885 /// ActOnStartCategoryImplementation - Perform semantic checks on the
1886 /// category implementation declaration and build an ObjCCategoryImplDecl
1888 Decl *Sema::ActOnStartCategoryImplementation(
1889 SourceLocation AtCatImplLoc,
1890 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1891 IdentifierInfo *CatName, SourceLocation CatLoc) {
1892 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1893 ObjCCategoryDecl *CatIDecl = nullptr;
1894 if (IDecl && IDecl->hasDefinition()) {
1895 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1897 // Category @implementation with no corresponding @interface.
1898 // Create and install one.
1899 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1902 /*typeParamList=*/nullptr);
1903 CatIDecl->setImplicit();
1907 ObjCCategoryImplDecl *CDecl =
1908 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
1909 ClassLoc, AtCatImplLoc, CatLoc);
1910 /// Check that class of this category is already completely declared.
1912 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1913 CDecl->setInvalidDecl();
1914 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1915 diag::err_undef_interface)) {
1916 CDecl->setInvalidDecl();
1919 // FIXME: PushOnScopeChains?
1920 CurContext->addDecl(CDecl);
1922 // If the interface has the objc_runtime_visible attribute, we
1923 // cannot implement a category for it.
1924 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1925 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1926 << IDecl->getDeclName();
1929 /// Check that CatName, category name, is not used in another implementation.
1931 if (CatIDecl->getImplementation()) {
1932 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1934 Diag(CatIDecl->getImplementation()->getLocation(),
1935 diag::note_previous_definition);
1936 CDecl->setInvalidDecl();
1938 CatIDecl->setImplementation(CDecl);
1939 // Warn on implementating category of deprecated class under
1940 // -Wdeprecated-implementations flag.
1941 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1942 CDecl->getLocation());
1946 CheckObjCDeclScope(CDecl);
1947 return ActOnObjCContainerStartDefinition(CDecl);
1950 Decl *Sema::ActOnStartClassImplementation(
1951 SourceLocation AtClassImplLoc,
1952 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1953 IdentifierInfo *SuperClassname,
1954 SourceLocation SuperClassLoc) {
1955 ObjCInterfaceDecl *IDecl = nullptr;
1956 // Check for another declaration kind with the same name.
1958 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1959 forRedeclarationInCurContext());
1960 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1961 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1962 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1963 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1964 // FIXME: This will produce an error if the definition of the interface has
1965 // been imported from a module but is not visible.
1966 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1967 diag::warn_undef_interface);
1969 // We did not find anything with the name ClassName; try to correct for
1970 // typos in the class name.
1971 TypoCorrection Corrected = CorrectTypo(
1972 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1973 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
1974 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1975 // Suggest the (potentially) correct interface name. Don't provide a
1976 // code-modification hint or use the typo name for recovery, because
1977 // this is just a warning. The program may actually be correct.
1978 diagnoseTypo(Corrected,
1979 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1980 /*ErrorRecovery*/false);
1982 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1986 // Check that super class name is valid class name
1987 ObjCInterfaceDecl *SDecl = nullptr;
1988 if (SuperClassname) {
1989 // Check if a different kind of symbol declared in this scope.
1990 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1991 LookupOrdinaryName);
1992 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1993 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1995 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1997 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1998 if (SDecl && !SDecl->hasDefinition())
2001 Diag(SuperClassLoc, diag::err_undef_superclass)
2002 << SuperClassname << ClassName;
2003 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
2004 // This implementation and its interface do not have the same
2006 Diag(SuperClassLoc, diag::err_conflicting_super_class)
2007 << SDecl->getDeclName();
2008 Diag(SDecl->getLocation(), diag::note_previous_definition);
2014 // Legacy case of @implementation with no corresponding @interface.
2015 // Build, chain & install the interface decl into the identifier.
2017 // FIXME: Do we support attributes on the @implementation? If so we should
2019 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
2020 ClassName, /*typeParamList=*/nullptr,
2021 /*PrevDecl=*/nullptr, ClassLoc,
2023 AddPragmaAttributes(TUScope, IDecl);
2024 IDecl->startDefinition();
2026 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2027 Context.getObjCInterfaceType(SDecl),
2029 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2031 IDecl->setEndOfDefinitionLoc(ClassLoc);
2034 PushOnScopeChains(IDecl, TUScope);
2036 // Mark the interface as being completed, even if it was just as
2038 // declaration; the user cannot reopen it.
2039 if (!IDecl->hasDefinition())
2040 IDecl->startDefinition();
2043 ObjCImplementationDecl* IMPDecl =
2044 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
2045 ClassLoc, AtClassImplLoc, SuperClassLoc);
2047 if (CheckObjCDeclScope(IMPDecl))
2048 return ActOnObjCContainerStartDefinition(IMPDecl);
2050 // Check that there is no duplicate implementation of this class.
2051 if (IDecl->getImplementation()) {
2052 // FIXME: Don't leak everything!
2053 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2054 Diag(IDecl->getImplementation()->getLocation(),
2055 diag::note_previous_definition);
2056 IMPDecl->setInvalidDecl();
2057 } else { // add it to the list.
2058 IDecl->setImplementation(IMPDecl);
2059 PushOnScopeChains(IMPDecl, TUScope);
2060 // Warn on implementating deprecated class under
2061 // -Wdeprecated-implementations flag.
2062 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
2065 // If the superclass has the objc_runtime_visible attribute, we
2066 // cannot implement a subclass of it.
2067 if (IDecl->getSuperClass() &&
2068 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2069 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2070 << IDecl->getDeclName()
2071 << IDecl->getSuperClass()->getDeclName();
2074 return ActOnObjCContainerStartDefinition(IMPDecl);
2077 Sema::DeclGroupPtrTy
2078 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2079 SmallVector<Decl *, 64> DeclsInGroup;
2080 DeclsInGroup.reserve(Decls.size() + 1);
2082 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2083 Decl *Dcl = Decls[i];
2086 if (Dcl->getDeclContext()->isFileContext())
2087 Dcl->setTopLevelDeclInObjCContainer();
2088 DeclsInGroup.push_back(Dcl);
2091 DeclsInGroup.push_back(ObjCImpDecl);
2093 return BuildDeclaratorGroup(DeclsInGroup);
2096 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2097 ObjCIvarDecl **ivars, unsigned numIvars,
2098 SourceLocation RBrace) {
2099 assert(ImpDecl && "missing implementation decl");
2100 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2103 /// Check case of non-existing \@interface decl.
2104 /// (legacy objective-c \@implementation decl without an \@interface decl).
2105 /// Add implementations's ivar to the synthesize class's ivar list.
2106 if (IDecl->isImplicitInterfaceDecl()) {
2107 IDecl->setEndOfDefinitionLoc(RBrace);
2108 // Add ivar's to class's DeclContext.
2109 for (unsigned i = 0, e = numIvars; i != e; ++i) {
2110 ivars[i]->setLexicalDeclContext(ImpDecl);
2111 IDecl->makeDeclVisibleInContext(ivars[i]);
2112 ImpDecl->addDecl(ivars[i]);
2117 // If implementation has empty ivar list, just return.
2121 assert(ivars && "missing @implementation ivars");
2122 if (LangOpts.ObjCRuntime.isNonFragile()) {
2123 if (ImpDecl->getSuperClass())
2124 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2125 for (unsigned i = 0; i < numIvars; i++) {
2126 ObjCIvarDecl* ImplIvar = ivars[i];
2127 if (const ObjCIvarDecl *ClsIvar =
2128 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2129 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2130 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2133 // Check class extensions (unnamed categories) for duplicate ivars.
2134 for (const auto *CDecl : IDecl->visible_extensions()) {
2135 if (const ObjCIvarDecl *ClsExtIvar =
2136 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2137 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2138 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2142 // Instance ivar to Implementation's DeclContext.
2143 ImplIvar->setLexicalDeclContext(ImpDecl);
2144 IDecl->makeDeclVisibleInContext(ImplIvar);
2145 ImpDecl->addDecl(ImplIvar);
2149 // Check interface's Ivar list against those in the implementation.
2150 // names and types must match.
2153 ObjCInterfaceDecl::ivar_iterator
2154 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2155 for (; numIvars > 0 && IVI != IVE; ++IVI) {
2156 ObjCIvarDecl* ImplIvar = ivars[j++];
2157 ObjCIvarDecl* ClsIvar = *IVI;
2158 assert (ImplIvar && "missing implementation ivar");
2159 assert (ClsIvar && "missing class ivar");
2161 // First, make sure the types match.
2162 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2163 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2164 << ImplIvar->getIdentifier()
2165 << ImplIvar->getType() << ClsIvar->getType();
2166 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2167 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2168 ImplIvar->getBitWidthValue(Context) !=
2169 ClsIvar->getBitWidthValue(Context)) {
2170 Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2171 diag::err_conflicting_ivar_bitwidth)
2172 << ImplIvar->getIdentifier();
2173 Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2174 diag::note_previous_definition);
2176 // Make sure the names are identical.
2177 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2178 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2179 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2180 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2186 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2187 else if (IVI != IVE)
2188 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2191 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2192 ObjCMethodDecl *method,
2193 bool &IncompleteImpl,
2195 NamedDecl *NeededFor = nullptr) {
2196 // No point warning no definition of method which is 'unavailable'.
2197 if (method->getAvailability() == AR_Unavailable)
2200 // FIXME: For now ignore 'IncompleteImpl'.
2201 // Previously we grouped all unimplemented methods under a single
2202 // warning, but some users strongly voiced that they would prefer
2203 // separate warnings. We will give that approach a try, as that
2204 // matches what we do with protocols.
2206 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2212 // Issue a note to the original declaration.
2213 SourceLocation MethodLoc = method->getBeginLoc();
2214 if (MethodLoc.isValid())
2215 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2218 /// Determines if type B can be substituted for type A. Returns true if we can
2219 /// guarantee that anything that the user will do to an object of type A can
2220 /// also be done to an object of type B. This is trivially true if the two
2221 /// types are the same, or if B is a subclass of A. It becomes more complex
2222 /// in cases where protocols are involved.
2224 /// Object types in Objective-C describe the minimum requirements for an
2225 /// object, rather than providing a complete description of a type. For
2226 /// example, if A is a subclass of B, then B* may refer to an instance of A.
2227 /// The principle of substitutability means that we may use an instance of A
2228 /// anywhere that we may use an instance of B - it will implement all of the
2229 /// ivars of B and all of the methods of B.
2231 /// This substitutability is important when type checking methods, because
2232 /// the implementation may have stricter type definitions than the interface.
2233 /// The interface specifies minimum requirements, but the implementation may
2234 /// have more accurate ones. For example, a method may privately accept
2235 /// instances of B, but only publish that it accepts instances of A. Any
2236 /// object passed to it will be type checked against B, and so will implicitly
2237 /// by a valid A*. Similarly, a method may return a subclass of the class that
2238 /// it is declared as returning.
2240 /// This is most important when considering subclassing. A method in a
2241 /// subclass must accept any object as an argument that its superclass's
2242 /// implementation accepts. It may, however, accept a more general type
2243 /// without breaking substitutability (i.e. you can still use the subclass
2244 /// anywhere that you can use the superclass, but not vice versa). The
2245 /// converse requirement applies to return types: the return type for a
2246 /// subclass method must be a valid object of the kind that the superclass
2247 /// advertises, but it may be specified more accurately. This avoids the need
2248 /// for explicit down-casting by callers.
2250 /// Note: This is a stricter requirement than for assignment.
2251 static bool isObjCTypeSubstitutable(ASTContext &Context,
2252 const ObjCObjectPointerType *A,
2253 const ObjCObjectPointerType *B,
2255 // Reject a protocol-unqualified id.
2256 if (rejectId && B->isObjCIdType()) return false;
2258 // If B is a qualified id, then A must also be a qualified id and it must
2259 // implement all of the protocols in B. It may not be a qualified class.
2260 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2261 // stricter definition so it is not substitutable for id<A>.
2262 if (B->isObjCQualifiedIdType()) {
2263 return A->isObjCQualifiedIdType() &&
2264 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2270 // id is a special type that bypasses type checking completely. We want a
2271 // warning when it is used in one place but not another.
2272 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2275 // If B is a qualified id, then A must also be a qualified id (which it isn't
2276 // if we've got this far)
2277 if (B->isObjCQualifiedIdType()) return false;
2280 // Now we know that A and B are (potentially-qualified) class types. The
2281 // normal rules for assignment apply.
2282 return Context.canAssignObjCInterfaces(A, B);
2285 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2286 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2289 /// Determine whether two set of Objective-C declaration qualifiers conflict.
2290 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2291 Decl::ObjCDeclQualifier y) {
2292 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2293 (y & ~Decl::OBJC_TQ_CSNullability);
2296 static bool CheckMethodOverrideReturn(Sema &S,
2297 ObjCMethodDecl *MethodImpl,
2298 ObjCMethodDecl *MethodDecl,
2299 bool IsProtocolMethodDecl,
2300 bool IsOverridingMode,
2302 if (IsProtocolMethodDecl &&
2303 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2304 MethodImpl->getObjCDeclQualifier())) {
2306 S.Diag(MethodImpl->getLocation(),
2308 ? diag::warn_conflicting_overriding_ret_type_modifiers
2309 : diag::warn_conflicting_ret_type_modifiers))
2310 << MethodImpl->getDeclName()
2311 << MethodImpl->getReturnTypeSourceRange();
2312 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2313 << MethodDecl->getReturnTypeSourceRange();
2318 if (Warn && IsOverridingMode &&
2319 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2320 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2321 MethodDecl->getReturnType(),
2323 auto nullabilityMethodImpl =
2324 *MethodImpl->getReturnType()->getNullability(S.Context);
2325 auto nullabilityMethodDecl =
2326 *MethodDecl->getReturnType()->getNullability(S.Context);
2327 S.Diag(MethodImpl->getLocation(),
2328 diag::warn_conflicting_nullability_attr_overriding_ret_types)
2329 << DiagNullabilityKind(
2330 nullabilityMethodImpl,
2331 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2333 << DiagNullabilityKind(
2334 nullabilityMethodDecl,
2335 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2337 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2340 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2341 MethodDecl->getReturnType()))
2347 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2348 : diag::warn_conflicting_ret_types;
2350 // Mismatches between ObjC pointers go into a different warning
2351 // category, and sometimes they're even completely whitelisted.
2352 if (const ObjCObjectPointerType *ImplPtrTy =
2353 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2354 if (const ObjCObjectPointerType *IfacePtrTy =
2355 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2356 // Allow non-matching return types as long as they don't violate
2357 // the principle of substitutability. Specifically, we permit
2358 // return types that are subclasses of the declared return type,
2359 // or that are more-qualified versions of the declared type.
2360 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2364 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2365 : diag::warn_non_covariant_ret_types;
2369 S.Diag(MethodImpl->getLocation(), DiagID)
2370 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2371 << MethodImpl->getReturnType()
2372 << MethodImpl->getReturnTypeSourceRange();
2373 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2374 ? diag::note_previous_declaration
2375 : diag::note_previous_definition)
2376 << MethodDecl->getReturnTypeSourceRange();
2380 static bool CheckMethodOverrideParam(Sema &S,
2381 ObjCMethodDecl *MethodImpl,
2382 ObjCMethodDecl *MethodDecl,
2383 ParmVarDecl *ImplVar,
2384 ParmVarDecl *IfaceVar,
2385 bool IsProtocolMethodDecl,
2386 bool IsOverridingMode,
2388 if (IsProtocolMethodDecl &&
2389 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2390 IfaceVar->getObjCDeclQualifier())) {
2392 if (IsOverridingMode)
2393 S.Diag(ImplVar->getLocation(),
2394 diag::warn_conflicting_overriding_param_modifiers)
2395 << getTypeRange(ImplVar->getTypeSourceInfo())
2396 << MethodImpl->getDeclName();
2397 else S.Diag(ImplVar->getLocation(),
2398 diag::warn_conflicting_param_modifiers)
2399 << getTypeRange(ImplVar->getTypeSourceInfo())
2400 << MethodImpl->getDeclName();
2401 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2402 << getTypeRange(IfaceVar->getTypeSourceInfo());
2408 QualType ImplTy = ImplVar->getType();
2409 QualType IfaceTy = IfaceVar->getType();
2410 if (Warn && IsOverridingMode &&
2411 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2412 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2413 S.Diag(ImplVar->getLocation(),
2414 diag::warn_conflicting_nullability_attr_overriding_param_types)
2415 << DiagNullabilityKind(
2416 *ImplTy->getNullability(S.Context),
2417 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2419 << DiagNullabilityKind(
2420 *IfaceTy->getNullability(S.Context),
2421 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2423 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2425 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2431 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2432 : diag::warn_conflicting_param_types;
2434 // Mismatches between ObjC pointers go into a different warning
2435 // category, and sometimes they're even completely whitelisted.
2436 if (const ObjCObjectPointerType *ImplPtrTy =
2437 ImplTy->getAs<ObjCObjectPointerType>()) {
2438 if (const ObjCObjectPointerType *IfacePtrTy =
2439 IfaceTy->getAs<ObjCObjectPointerType>()) {
2440 // Allow non-matching argument types as long as they don't
2441 // violate the principle of substitutability. Specifically, the
2442 // implementation must accept any objects that the superclass
2443 // accepts, however it may also accept others.
2444 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2448 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2449 : diag::warn_non_contravariant_param_types;
2453 S.Diag(ImplVar->getLocation(), DiagID)
2454 << getTypeRange(ImplVar->getTypeSourceInfo())
2455 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2456 S.Diag(IfaceVar->getLocation(),
2457 (IsOverridingMode ? diag::note_previous_declaration
2458 : diag::note_previous_definition))
2459 << getTypeRange(IfaceVar->getTypeSourceInfo());
2463 /// In ARC, check whether the conventional meanings of the two methods
2464 /// match. If they don't, it's a hard error.
2465 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2466 ObjCMethodDecl *decl) {
2467 ObjCMethodFamily implFamily = impl->getMethodFamily();
2468 ObjCMethodFamily declFamily = decl->getMethodFamily();
2469 if (implFamily == declFamily) return false;
2471 // Since conventions are sorted by selector, the only possibility is
2472 // that the types differ enough to cause one selector or the other
2473 // to fall out of the family.
2474 assert(implFamily == OMF_None || declFamily == OMF_None);
2476 // No further diagnostics required on invalid declarations.
2477 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2479 const ObjCMethodDecl *unmatched = impl;
2480 ObjCMethodFamily family = declFamily;
2481 unsigned errorID = diag::err_arc_lost_method_convention;
2482 unsigned noteID = diag::note_arc_lost_method_convention;
2483 if (declFamily == OMF_None) {
2485 family = implFamily;
2486 errorID = diag::err_arc_gained_method_convention;
2487 noteID = diag::note_arc_gained_method_convention;
2490 // Indexes into a %select clause in the diagnostic.
2491 enum FamilySelector {
2492 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2494 FamilySelector familySelector = FamilySelector();
2497 case OMF_None: llvm_unreachable("logic error, no method convention");
2500 case OMF_autorelease:
2503 case OMF_retainCount:
2505 case OMF_initialize:
2506 case OMF_performSelector:
2507 // Mismatches for these methods don't change ownership
2508 // conventions, so we don't care.
2511 case OMF_init: familySelector = F_init; break;
2512 case OMF_alloc: familySelector = F_alloc; break;
2513 case OMF_copy: familySelector = F_copy; break;
2514 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2515 case OMF_new: familySelector = F_new; break;
2518 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2519 ReasonSelector reasonSelector;
2521 // The only reason these methods don't fall within their families is
2522 // due to unusual result types.
2523 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2524 reasonSelector = R_UnrelatedReturn;
2526 reasonSelector = R_NonObjectReturn;
2529 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2530 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2535 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2536 ObjCMethodDecl *MethodDecl,
2537 bool IsProtocolMethodDecl) {
2538 if (getLangOpts().ObjCAutoRefCount &&
2539 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2542 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2543 IsProtocolMethodDecl, false,
2546 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2547 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2548 EF = MethodDecl->param_end();
2549 IM != EM && IF != EF; ++IM, ++IF) {
2550 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2551 IsProtocolMethodDecl, false, true);
2554 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2555 Diag(ImpMethodDecl->getLocation(),
2556 diag::warn_conflicting_variadic);
2557 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2561 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2562 ObjCMethodDecl *Overridden,
2563 bool IsProtocolMethodDecl) {
2565 CheckMethodOverrideReturn(*this, Method, Overridden,
2566 IsProtocolMethodDecl, true,
2569 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2570 IF = Overridden->param_begin(), EM = Method->param_end(),
2571 EF = Overridden->param_end();
2572 IM != EM && IF != EF; ++IM, ++IF) {
2573 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2574 IsProtocolMethodDecl, true, true);
2577 if (Method->isVariadic() != Overridden->isVariadic()) {
2578 Diag(Method->getLocation(),
2579 diag::warn_conflicting_overriding_variadic);
2580 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2584 /// WarnExactTypedMethods - This routine issues a warning if method
2585 /// implementation declaration matches exactly that of its declaration.
2586 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2587 ObjCMethodDecl *MethodDecl,
2588 bool IsProtocolMethodDecl) {
2589 // don't issue warning when protocol method is optional because primary
2590 // class is not required to implement it and it is safe for protocol
2592 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2594 // don't issue warning when primary class's method is
2595 // depecated/unavailable.
2596 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2597 MethodDecl->hasAttr<DeprecatedAttr>())
2600 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2601 IsProtocolMethodDecl, false, false);
2603 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2604 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2605 EF = MethodDecl->param_end();
2606 IM != EM && IF != EF; ++IM, ++IF) {
2607 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2609 IsProtocolMethodDecl, false, false);
2614 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2616 match = !(MethodDecl->isClassMethod() &&
2617 MethodDecl->getSelector() == GetNullarySelector("load", Context));
2620 Diag(ImpMethodDecl->getLocation(),
2621 diag::warn_category_method_impl_match);
2622 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2623 << MethodDecl->getDeclName();
2627 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2628 /// improve the efficiency of selector lookups and type checking by associating
2629 /// with each protocol / interface / category the flattened instance tables. If
2630 /// we used an immutable set to keep the table then it wouldn't add significant
2631 /// memory cost and it would be handy for lookups.
2633 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2634 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2636 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2637 ProtocolNameSet &PNS) {
2638 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2639 PNS.insert(PDecl->getIdentifier());
2640 for (const auto *PI : PDecl->protocols())
2641 findProtocolsWithExplicitImpls(PI, PNS);
2644 /// Recursively populates a set with all conformed protocols in a class
2645 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2647 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2648 ProtocolNameSet &PNS) {
2652 for (const auto *I : Super->all_referenced_protocols())
2653 findProtocolsWithExplicitImpls(I, PNS);
2655 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2658 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
2659 /// Declared in protocol, and those referenced by it.
2660 static void CheckProtocolMethodDefs(Sema &S,
2661 SourceLocation ImpLoc,
2662 ObjCProtocolDecl *PDecl,
2663 bool& IncompleteImpl,
2664 const Sema::SelectorSet &InsMap,
2665 const Sema::SelectorSet &ClsMap,
2666 ObjCContainerDecl *CDecl,
2667 LazyProtocolNameSet &ProtocolsExplictImpl) {
2668 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2669 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2670 : dyn_cast<ObjCInterfaceDecl>(CDecl);
2671 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2673 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2674 ObjCInterfaceDecl *NSIDecl = nullptr;
2676 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2677 // then we should check if any class in the super class hierarchy also
2678 // conforms to this protocol, either directly or via protocol inheritance.
2679 // If so, we can skip checking this protocol completely because we
2680 // know that a parent class already satisfies this protocol.
2682 // Note: we could generalize this logic for all protocols, and merely
2683 // add the limit on looking at the super class chain for just
2684 // specially marked protocols. This may be a good optimization. This
2685 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2686 // protocols for now for controlled evaluation.
2687 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2688 if (!ProtocolsExplictImpl) {
2689 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2690 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2692 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2693 ProtocolsExplictImpl->end())
2696 // If no super class conforms to the protocol, we should not search
2697 // for methods in the super class to implicitly satisfy the protocol.
2701 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2702 // check to see if class implements forwardInvocation method and objects
2703 // of this class are derived from 'NSProxy' so that to forward requests
2704 // from one object to another.
2705 // Under such conditions, which means that every method possible is
2706 // implemented in the class, we should not issue "Method definition not
2708 // FIXME: Use a general GetUnarySelector method for this.
2709 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2710 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2711 if (InsMap.count(fISelector))
2712 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2713 // need be implemented in the implementation.
2714 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2717 // If this is a forward protocol declaration, get its definition.
2718 if (!PDecl->isThisDeclarationADefinition() &&
2719 PDecl->getDefinition())
2720 PDecl = PDecl->getDefinition();
2722 // If a method lookup fails locally we still need to look and see if
2723 // the method was implemented by a base class or an inherited
2724 // protocol. This lookup is slow, but occurs rarely in correct code
2725 // and otherwise would terminate in a warning.
2727 // check unimplemented instance methods.
2729 for (auto *method : PDecl->instance_methods()) {
2730 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2731 !method->isPropertyAccessor() &&
2732 !InsMap.count(method->getSelector()) &&
2733 (!Super || !Super->lookupMethod(method->getSelector(),
2734 true /* instance */,
2735 false /* shallowCategory */,
2736 true /* followsSuper */,
2737 nullptr /* category */))) {
2738 // If a method is not implemented in the category implementation but
2739 // has been declared in its primary class, superclass,
2740 // or in one of their protocols, no need to issue the warning.
2741 // This is because method will be implemented in the primary class
2742 // or one of its super class implementation.
2744 // Ugly, but necessary. Method declared in protocol might have
2745 // have been synthesized due to a property declared in the class which
2746 // uses the protocol.
2747 if (ObjCMethodDecl *MethodInClass =
2748 IDecl->lookupMethod(method->getSelector(),
2749 true /* instance */,
2750 true /* shallowCategoryLookup */,
2751 false /* followSuper */))
2752 if (C || MethodInClass->isPropertyAccessor())
2754 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2755 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2756 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
2761 // check unimplemented class methods
2762 for (auto *method : PDecl->class_methods()) {
2763 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2764 !ClsMap.count(method->getSelector()) &&
2765 (!Super || !Super->lookupMethod(method->getSelector(),
2766 false /* class method */,
2767 false /* shallowCategoryLookup */,
2768 true /* followSuper */,
2769 nullptr /* category */))) {
2770 // See above comment for instance method lookups.
2771 if (C && IDecl->lookupMethod(method->getSelector(),
2773 true /* shallowCategoryLookup */,
2774 false /* followSuper */))
2777 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2778 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2779 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
2783 // Check on this protocols's referenced protocols, recursively.
2784 for (auto *PI : PDecl->protocols())
2785 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
2786 CDecl, ProtocolsExplictImpl);
2789 /// MatchAllMethodDeclarations - Check methods declared in interface
2790 /// or protocol against those declared in their implementations.
2792 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2793 const SelectorSet &ClsMap,
2794 SelectorSet &InsMapSeen,
2795 SelectorSet &ClsMapSeen,
2796 ObjCImplDecl* IMPDecl,
2797 ObjCContainerDecl* CDecl,
2798 bool &IncompleteImpl,
2799 bool ImmediateClass,
2800 bool WarnCategoryMethodImpl) {
2801 // Check and see if instance methods in class interface have been
2802 // implemented in the implementation class. If so, their types match.
2803 for (auto *I : CDecl->instance_methods()) {
2804 if (!InsMapSeen.insert(I->getSelector()).second)
2806 if (!I->isPropertyAccessor() &&
2807 !InsMap.count(I->getSelector())) {
2809 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2810 diag::warn_undef_method_impl);
2813 ObjCMethodDecl *ImpMethodDecl =
2814 IMPDecl->getInstanceMethod(I->getSelector());
2815 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2816 "Expected to find the method through lookup as well");
2817 // ImpMethodDecl may be null as in a @dynamic property.
2818 if (ImpMethodDecl) {
2819 if (!WarnCategoryMethodImpl)
2820 WarnConflictingTypedMethods(ImpMethodDecl, I,
2821 isa<ObjCProtocolDecl>(CDecl));
2822 else if (!I->isPropertyAccessor())
2823 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2828 // Check and see if class methods in class interface have been
2829 // implemented in the implementation class. If so, their types match.
2830 for (auto *I : CDecl->class_methods()) {
2831 if (!ClsMapSeen.insert(I->getSelector()).second)
2833 if (!I->isPropertyAccessor() &&
2834 !ClsMap.count(I->getSelector())) {
2836 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2837 diag::warn_undef_method_impl);
2839 ObjCMethodDecl *ImpMethodDecl =
2840 IMPDecl->getClassMethod(I->getSelector());
2841 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2842 "Expected to find the method through lookup as well");
2843 // ImpMethodDecl may be null as in a @dynamic property.
2844 if (ImpMethodDecl) {
2845 if (!WarnCategoryMethodImpl)
2846 WarnConflictingTypedMethods(ImpMethodDecl, I,
2847 isa<ObjCProtocolDecl>(CDecl));
2848 else if (!I->isPropertyAccessor())
2849 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2854 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2855 // Also, check for methods declared in protocols inherited by
2857 for (auto *PI : PD->protocols())
2858 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2859 IMPDecl, PI, IncompleteImpl, false,
2860 WarnCategoryMethodImpl);
2863 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2864 // when checking that methods in implementation match their declaration,
2865 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2866 // extension; as well as those in categories.
2867 if (!WarnCategoryMethodImpl) {
2868 for (auto *Cat : I->visible_categories())
2869 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2870 IMPDecl, Cat, IncompleteImpl,
2871 ImmediateClass && Cat->IsClassExtension(),
2872 WarnCategoryMethodImpl);
2874 // Also methods in class extensions need be looked at next.
2875 for (auto *Ext : I->visible_extensions())
2876 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2877 IMPDecl, Ext, IncompleteImpl, false,
2878 WarnCategoryMethodImpl);
2881 // Check for any implementation of a methods declared in protocol.
2882 for (auto *PI : I->all_referenced_protocols())
2883 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2884 IMPDecl, PI, IncompleteImpl, false,
2885 WarnCategoryMethodImpl);
2887 // FIXME. For now, we are not checking for exact match of methods
2888 // in category implementation and its primary class's super class.
2889 if (!WarnCategoryMethodImpl && I->getSuperClass())
2890 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2892 I->getSuperClass(), IncompleteImpl, false);
2896 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2897 /// category matches with those implemented in its primary class and
2898 /// warns each time an exact match is found.
2899 void Sema::CheckCategoryVsClassMethodMatches(
2900 ObjCCategoryImplDecl *CatIMPDecl) {
2901 // Get category's primary class.
2902 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2905 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2908 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2909 SelectorSet InsMap, ClsMap;
2911 for (const auto *I : CatIMPDecl->instance_methods()) {
2912 Selector Sel = I->getSelector();
2913 // When checking for methods implemented in the category, skip over
2914 // those declared in category class's super class. This is because
2915 // the super class must implement the method.
2916 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2921 for (const auto *I : CatIMPDecl->class_methods()) {
2922 Selector Sel = I->getSelector();
2923 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2927 if (InsMap.empty() && ClsMap.empty())
2930 SelectorSet InsMapSeen, ClsMapSeen;
2931 bool IncompleteImpl = false;
2932 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2934 IncompleteImpl, false,
2935 true /*WarnCategoryMethodImpl*/);
2938 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2939 ObjCContainerDecl* CDecl,
2940 bool IncompleteImpl) {
2942 // Check and see if instance methods in class interface have been
2943 // implemented in the implementation class.
2944 for (const auto *I : IMPDecl->instance_methods())
2945 InsMap.insert(I->getSelector());
2947 // Add the selectors for getters/setters of @dynamic properties.
2948 for (const auto *PImpl : IMPDecl->property_impls()) {
2949 // We only care about @dynamic implementations.
2950 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2953 const auto *P = PImpl->getPropertyDecl();
2956 InsMap.insert(P->getGetterName());
2957 if (!P->getSetterName().isNull())
2958 InsMap.insert(P->getSetterName());
2961 // Check and see if properties declared in the interface have either 1)
2962 // an implementation or 2) there is a @synthesize/@dynamic implementation
2963 // of the property in the @implementation.
2964 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2965 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2966 LangOpts.ObjCRuntime.isNonFragile() &&
2967 !IDecl->isObjCRequiresPropertyDefs();
2968 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2971 // Diagnose null-resettable synthesized setters.
2972 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2975 for (const auto *I : IMPDecl->class_methods())
2976 ClsMap.insert(I->getSelector());
2978 // Check for type conflict of methods declared in a class/protocol and
2979 // its implementation; if any.
2980 SelectorSet InsMapSeen, ClsMapSeen;
2981 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2983 IncompleteImpl, true);
2985 // check all methods implemented in category against those declared
2986 // in its primary class.
2987 if (ObjCCategoryImplDecl *CatDecl =
2988 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2989 CheckCategoryVsClassMethodMatches(CatDecl);
2991 // Check the protocol list for unimplemented methods in the @implementation
2993 // Check and see if class methods in class interface have been
2994 // implemented in the implementation class.
2996 LazyProtocolNameSet ExplicitImplProtocols;
2998 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2999 for (auto *PI : I->all_referenced_protocols())
3000 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
3001 InsMap, ClsMap, I, ExplicitImplProtocols);
3002 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3003 // For extended class, unimplemented methods in its protocols will
3004 // be reported in the primary class.
3005 if (!C->IsClassExtension()) {
3006 for (auto *P : C->protocols())
3007 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
3008 IncompleteImpl, InsMap, ClsMap, CDecl,
3009 ExplicitImplProtocols);
3010 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3011 /*SynthesizeProperties=*/false);
3014 llvm_unreachable("invalid ObjCContainerDecl type.");
3017 Sema::DeclGroupPtrTy
3018 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
3019 IdentifierInfo **IdentList,
3020 SourceLocation *IdentLocs,
3021 ArrayRef<ObjCTypeParamList *> TypeParamLists,
3023 SmallVector<Decl *, 8> DeclsInGroup;
3024 for (unsigned i = 0; i != NumElts; ++i) {
3025 // Check for another declaration kind with the same name.
3027 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
3028 LookupOrdinaryName, forRedeclarationInCurContext());
3029 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3030 // GCC apparently allows the following idiom:
3032 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3033 // @class XCElementToggler;
3035 // Here we have chosen to ignore the forward class declaration
3036 // with a warning. Since this is the implied behavior.
3037 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3038 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3039 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3040 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3042 // a forward class declaration matching a typedef name of a class refers
3043 // to the underlying class. Just ignore the forward class with a warning
3044 // as this will force the intended behavior which is to lookup the
3046 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3047 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3049 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3055 // Create a declaration to describe this forward declaration.
3056 ObjCInterfaceDecl *PrevIDecl
3057 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3059 IdentifierInfo *ClassName = IdentList[i];
3060 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3061 // A previous decl with a different name is because of
3062 // @compatibility_alias, for example:
3065 // @compatibility_alias OldImage NewImage;
3067 // A lookup for 'OldImage' will return the 'NewImage' decl.
3069 // In such a case use the real declaration name, instead of the alias one,
3070 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3071 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3072 // has been aliased.
3073 ClassName = PrevIDecl->getIdentifier();
3076 // If this forward declaration has type parameters, compare them with the
3077 // type parameters of the previous declaration.
3078 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3079 if (PrevIDecl && TypeParams) {
3080 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3081 // Check for consistency with the previous declaration.
3082 if (checkTypeParamListConsistency(
3083 *this, PrevTypeParams, TypeParams,
3084 TypeParamListContext::ForwardDeclaration)) {
3085 TypeParams = nullptr;
3087 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3088 // The @interface does not have type parameters. Complain.
3089 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3091 << TypeParams->getSourceRange();
3092 Diag(Def->getLocation(), diag::note_defined_here)
3095 TypeParams = nullptr;
3099 ObjCInterfaceDecl *IDecl
3100 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
3101 ClassName, TypeParams, PrevIDecl,
3103 IDecl->setAtEndRange(IdentLocs[i]);
3105 PushOnScopeChains(IDecl, TUScope);
3106 CheckObjCDeclScope(IDecl);
3107 DeclsInGroup.push_back(IDecl);
3110 return BuildDeclaratorGroup(DeclsInGroup);
3113 static bool tryMatchRecordTypes(ASTContext &Context,
3114 Sema::MethodMatchStrategy strategy,
3115 const Type *left, const Type *right);
3117 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3118 QualType leftQT, QualType rightQT) {
3120 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3122 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3124 if (left == right) return true;
3126 // If we're doing a strict match, the types have to match exactly.
3127 if (strategy == Sema::MMS_strict) return false;
3129 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3131 // Otherwise, use this absurdly complicated algorithm to try to
3132 // validate the basic, low-level compatibility of the two types.
3134 // As a minimum, require the sizes and alignments to match.
3135 TypeInfo LeftTI = Context.getTypeInfo(left);
3136 TypeInfo RightTI = Context.getTypeInfo(right);
3137 if (LeftTI.Width != RightTI.Width)
3140 if (LeftTI.Align != RightTI.Align)
3143 // Consider all the kinds of non-dependent canonical types:
3144 // - functions and arrays aren't possible as return and parameter types
3146 // - vector types of equal size can be arbitrarily mixed
3147 if (isa<VectorType>(left)) return isa<VectorType>(right);
3148 if (isa<VectorType>(right)) return false;
3150 // - references should only match references of identical type
3151 // - structs, unions, and Objective-C objects must match more-or-less
3153 // - everything else should be a scalar
3154 if (!left->isScalarType() || !right->isScalarType())
3155 return tryMatchRecordTypes(Context, strategy, left, right);
3157 // Make scalars agree in kind, except count bools as chars, and group
3158 // all non-member pointers together.
3159 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3160 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3161 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3162 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3163 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3164 leftSK = Type::STK_ObjCObjectPointer;
3165 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3166 rightSK = Type::STK_ObjCObjectPointer;
3168 // Note that data member pointers and function member pointers don't
3169 // intermix because of the size differences.
3171 return (leftSK == rightSK);
3174 static bool tryMatchRecordTypes(ASTContext &Context,
3175 Sema::MethodMatchStrategy strategy,
3176 const Type *lt, const Type *rt) {
3177 assert(lt && rt && lt != rt);
3179 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3180 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3181 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3183 // Require union-hood to match.
3184 if (left->isUnion() != right->isUnion()) return false;
3186 // Require an exact match if either is non-POD.
3187 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3188 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3191 // Require size and alignment to match.
3192 TypeInfo LeftTI = Context.getTypeInfo(lt);
3193 TypeInfo RightTI = Context.getTypeInfo(rt);
3194 if (LeftTI.Width != RightTI.Width)
3197 if (LeftTI.Align != RightTI.Align)
3200 // Require fields to match.
3201 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3202 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3203 for (; li != le && ri != re; ++li, ++ri) {
3204 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3207 return (li == le && ri == re);
3210 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3211 /// returns true, or false, accordingly.
3212 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3213 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3214 const ObjCMethodDecl *right,
3215 MethodMatchStrategy strategy) {
3216 if (!matchTypes(Context, strategy, left->getReturnType(),
3217 right->getReturnType()))
3220 // If either is hidden, it is not considered to match.
3221 if (left->isHidden() || right->isHidden())
3224 if (getLangOpts().ObjCAutoRefCount &&
3225 (left->hasAttr<NSReturnsRetainedAttr>()
3226 != right->hasAttr<NSReturnsRetainedAttr>() ||
3227 left->hasAttr<NSConsumesSelfAttr>()
3228 != right->hasAttr<NSConsumesSelfAttr>()))
3231 ObjCMethodDecl::param_const_iterator
3232 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3233 re = right->param_end();
3235 for (; li != le && ri != re; ++li, ++ri) {
3236 assert(ri != right->param_end() && "Param mismatch");
3237 const ParmVarDecl *lparm = *li, *rparm = *ri;
3239 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3242 if (getLangOpts().ObjCAutoRefCount &&
3243 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3249 static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3250 ObjCMethodDecl *MethodInList) {
3251 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3252 auto *MethodInListProtocol =
3253 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3254 // If this method belongs to a protocol but the method in list does not, or
3255 // vice versa, we say the context is not the same.
3256 if ((MethodProtocol && !MethodInListProtocol) ||
3257 (!MethodProtocol && MethodInListProtocol))
3260 if (MethodProtocol && MethodInListProtocol)
3263 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3264 ObjCInterfaceDecl *MethodInListInterface =
3265 MethodInList->getClassInterface();
3266 return MethodInterface == MethodInListInterface;
3269 void Sema::addMethodToGlobalList(ObjCMethodList *List,
3270 ObjCMethodDecl *Method) {
3271 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3272 // inside categories.
3273 if (ObjCCategoryDecl *CD =
3274 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3275 if (!CD->IsClassExtension() && List->getBits() < 2)
3276 List->setBits(List->getBits() + 1);
3278 // If the list is empty, make it a singleton list.
3279 if (List->getMethod() == nullptr) {
3280 List->setMethod(Method);
3281 List->setNext(nullptr);
3285 // We've seen a method with this name, see if we have already seen this type
3287 ObjCMethodList *Previous = List;
3288 ObjCMethodList *ListWithSameDeclaration = nullptr;
3289 for (; List; Previous = List, List = List->getNext()) {
3290 // If we are building a module, keep all of the methods.
3291 if (getLangOpts().isCompilingModule())
3294 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3296 // Looking for method with a type bound requires the correct context exists.
3297 // We need to insert a method into the list if the context is different.
3298 // If the method's declaration matches the list
3299 // a> the method belongs to a different context: we need to insert it, in
3300 // order to emit the availability message, we need to prioritize over
3301 // availability among the methods with the same declaration.
3302 // b> the method belongs to the same context: there is no need to insert a
3304 // If the method's declaration does not match the list, we insert it to the
3306 if (!SameDeclaration ||
3307 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3308 // Even if two method types do not match, we would like to say
3309 // there is more than one declaration so unavailability/deprecated
3310 // warning is not too noisy.
3311 if (!Method->isDefined())
3312 List->setHasMoreThanOneDecl(true);
3314 // For methods with the same declaration, the one that is deprecated
3315 // should be put in the front for better diagnostics.
3316 if (Method->isDeprecated() && SameDeclaration &&
3317 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3318 ListWithSameDeclaration = List;
3320 if (Method->isUnavailable() && SameDeclaration &&
3321 !ListWithSameDeclaration &&
3322 List->getMethod()->getAvailability() < AR_Deprecated)
3323 ListWithSameDeclaration = List;
3327 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3329 // Propagate the 'defined' bit.
3330 if (Method->isDefined())
3331 PrevObjCMethod->setDefined(true);
3333 // Objective-C doesn't allow an @interface for a class after its
3334 // @implementation. So if Method is not defined and there already is
3335 // an entry for this type signature, Method has to be for a different
3336 // class than PrevObjCMethod.
3337 List->setHasMoreThanOneDecl(true);
3340 // If a method is deprecated, push it in the global pool.
3341 // This is used for better diagnostics.
3342 if (Method->isDeprecated()) {
3343 if (!PrevObjCMethod->isDeprecated())
3344 List->setMethod(Method);
3346 // If the new method is unavailable, push it into global pool
3347 // unless previous one is deprecated.
3348 if (Method->isUnavailable()) {
3349 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3350 List->setMethod(Method);
3356 // We have a new signature for an existing method - add it.
3357 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3358 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3360 // We insert it right before ListWithSameDeclaration.
3361 if (ListWithSameDeclaration) {
3362 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3363 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3364 ListWithSameDeclaration->setMethod(Method);
3365 ListWithSameDeclaration->setNext(List);
3369 Previous->setNext(new (Mem) ObjCMethodList(Method));
3372 /// Read the contents of the method pool for a given selector from
3373 /// external storage.
3374 void Sema::ReadMethodPool(Selector Sel) {
3375 assert(ExternalSource && "We need an external AST source");
3376 ExternalSource->ReadMethodPool(Sel);
3379 void Sema::updateOutOfDateSelector(Selector Sel) {
3380 if (!ExternalSource)
3382 ExternalSource->updateOutOfDateSelector(Sel);
3385 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3387 // Ignore methods of invalid containers.
3388 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3392 ReadMethodPool(Method->getSelector());
3394 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
3395 if (Pos == MethodPool.end())
3396 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3397 GlobalMethods())).first;
3399 Method->setDefined(impl);
3401 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3402 addMethodToGlobalList(&Entry, Method);
3405 /// Determines if this is an "acceptable" loose mismatch in the global
3406 /// method pool. This exists mostly as a hack to get around certain
3407 /// global mismatches which we can't afford to make warnings / errors.
3408 /// Really, what we want is a way to take a method out of the global
3410 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3411 ObjCMethodDecl *other) {
3412 if (!chosen->isInstanceMethod())
3415 Selector sel = chosen->getSelector();
3416 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3419 // Don't complain about mismatches for -length if the method we
3420 // chose has an integral result type.
3421 return (chosen->getReturnType()->isIntegerType());
3424 /// Return true if the given method is wthin the type bound.
3425 static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3426 const ObjCObjectType *TypeBound) {
3430 if (TypeBound->isObjCId())
3431 // FIXME: should we handle the case of bounding to id<A, B> differently?
3434 auto *BoundInterface = TypeBound->getInterface();
3435 assert(BoundInterface && "unexpected object type!");
3437 // Check if the Method belongs to a protocol. We should allow any method
3438 // defined in any protocol, because any subclass could adopt the protocol.
3439 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3440 if (MethodProtocol) {
3444 // If the Method belongs to a class, check if it belongs to the class
3445 // hierarchy of the class bound.
3446 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3447 // We allow methods declared within classes that are part of the hierarchy
3448 // of the class bound (superclass of, subclass of, or the same as the class
3450 return MethodInterface == BoundInterface ||
3451 MethodInterface->isSuperClassOf(BoundInterface) ||
3452 BoundInterface->isSuperClassOf(MethodInterface);
3454 llvm_unreachable("unknown method context");
3457 /// We first select the type of the method: Instance or Factory, then collect
3458 /// all methods with that type.
3459 bool Sema::CollectMultipleMethodsInGlobalPool(
3460 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3461 bool InstanceFirst, bool CheckTheOther,
3462 const ObjCObjectType *TypeBound) {
3464 ReadMethodPool(Sel);
3466 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3467 if (Pos == MethodPool.end())
3470 // Gather the non-hidden methods.
3471 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3473 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3474 if (M->getMethod() && !M->getMethod()->isHidden()) {
3475 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3476 Methods.push_back(M->getMethod());
3479 // Return if we find any method with the desired kind.
3480 if (!Methods.empty())
3481 return Methods.size() > 1;
3486 // Gather the other kind.
3487 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3489 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3490 if (M->getMethod() && !M->getMethod()->isHidden()) {
3491 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3492 Methods.push_back(M->getMethod());
3495 return Methods.size() > 1;
3498 bool Sema::AreMultipleMethodsInGlobalPool(
3499 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3500 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3501 // Diagnose finding more than one method in global pool.
3502 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3503 FilteredMethods.push_back(BestMethod);
3505 for (auto *M : Methods)
3506 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3507 FilteredMethods.push_back(M);
3509 if (FilteredMethods.size() > 1)
3510 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3513 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3514 // Test for no method in the pool which should not trigger any warning by
3516 if (Pos == MethodPool.end())
3518 ObjCMethodList &MethList =
3519 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3520 return MethList.hasMoreThanOneDecl();
3523 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3524 bool receiverIdOrClass,
3527 ReadMethodPool(Sel);
3529 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3530 if (Pos == MethodPool.end())
3533 // Gather the non-hidden methods.
3534 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3535 SmallVector<ObjCMethodDecl *, 4> Methods;
3536 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3537 if (M->getMethod() && !M->getMethod()->isHidden())
3538 return M->getMethod();
3543 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3544 Selector Sel, SourceRange R,
3545 bool receiverIdOrClass) {
3546 // We found multiple methods, so we may have to complain.
3547 bool issueDiagnostic = false, issueError = false;
3549 // We support a warning which complains about *any* difference in
3550 // method signature.
3551 bool strictSelectorMatch =
3552 receiverIdOrClass &&
3553 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3554 if (strictSelectorMatch) {
3555 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3556 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3557 issueDiagnostic = true;
3563 // If we didn't see any strict differences, we won't see any loose
3564 // differences. In ARC, however, we also need to check for loose
3565 // mismatches, because most of them are errors.
3566 if (!strictSelectorMatch ||
3567 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3568 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3569 // This checks if the methods differ in type mismatch.
3570 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3571 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3572 issueDiagnostic = true;
3573 if (getLangOpts().ObjCAutoRefCount)
3579 if (issueDiagnostic) {
3581 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3582 else if (strictSelectorMatch)
3583 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3585 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3587 Diag(Methods[0]->getBeginLoc(),
3588 issueError ? diag::note_possibility : diag::note_using)
3589 << Methods[0]->getSourceRange();
3590 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3591 Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3592 << Methods[I]->getSourceRange();
3597 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
3598 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3599 if (Pos == MethodPool.end())
3602 GlobalMethods &Methods = Pos->second;
3603 for (const ObjCMethodList *Method = &Methods.first; Method;
3604 Method = Method->getNext())
3605 if (Method->getMethod() &&
3606 (Method->getMethod()->isDefined() ||
3607 Method->getMethod()->isPropertyAccessor()))
3608 return Method->getMethod();
3610 for (const ObjCMethodList *Method = &Methods.second; Method;
3611 Method = Method->getNext())
3612 if (Method->getMethod() &&
3613 (Method->getMethod()->isDefined() ||
3614 Method->getMethod()->isPropertyAccessor()))
3615 return Method->getMethod();
3620 HelperSelectorsForTypoCorrection(
3621 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3622 StringRef Typo, const ObjCMethodDecl * Method) {
3623 const unsigned MaxEditDistance = 1;
3624 unsigned BestEditDistance = MaxEditDistance + 1;
3625 std::string MethodName = Method->getSelector().getAsString();
3627 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3628 if (MinPossibleEditDistance > 0 &&
3629 Typo.size() / MinPossibleEditDistance < 1)
3631 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3632 if (EditDistance > MaxEditDistance)
3634 if (EditDistance == BestEditDistance)
3635 BestMethod.push_back(Method);
3636 else if (EditDistance < BestEditDistance) {
3638 BestMethod.push_back(Method);
3642 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3643 QualType ObjectType) {
3644 if (ObjectType.isNull())
3646 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3648 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3652 const ObjCMethodDecl *
3653 Sema::SelectorsForTypoCorrection(Selector Sel,
3654 QualType ObjectType) {
3655 unsigned NumArgs = Sel.getNumArgs();
3656 SmallVector<const ObjCMethodDecl *, 8> Methods;
3657 bool ObjectIsId = true, ObjectIsClass = true;
3658 if (ObjectType.isNull())
3659 ObjectIsId = ObjectIsClass = false;
3660 else if (!ObjectType->isObjCObjectPointerType())
3662 else if (const ObjCObjectPointerType *ObjCPtr =
3663 ObjectType->getAsObjCInterfacePointerType()) {
3664 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3665 ObjectIsId = ObjectIsClass = false;
3667 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3668 ObjectIsClass = false;
3669 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3674 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3675 e = MethodPool.end(); b != e; b++) {
3677 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3678 if (M->getMethod() &&
3679 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3680 (M->getMethod()->getSelector() != Sel)) {
3682 Methods.push_back(M->getMethod());
3683 else if (!ObjectIsClass &&
3684 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3686 Methods.push_back(M->getMethod());
3689 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3690 if (M->getMethod() &&
3691 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3692 (M->getMethod()->getSelector() != Sel)) {
3694 Methods.push_back(M->getMethod());
3695 else if (!ObjectIsId &&
3696 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3698 Methods.push_back(M->getMethod());
3702 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3703 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3704 HelperSelectorsForTypoCorrection(SelectedMethods,
3705 Sel.getAsString(), Methods[i]);
3707 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3710 /// DiagnoseDuplicateIvars -
3711 /// Check for duplicate ivars in the entire class at the start of
3712 /// \@implementation. This becomes necesssary because class extension can
3713 /// add ivars to a class in random order which will not be known until
3714 /// class's \@implementation is seen.
3715 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3716 ObjCInterfaceDecl *SID) {
3717 for (auto *Ivar : ID->ivars()) {
3718 if (Ivar->isInvalidDecl())
3720 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3721 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3723 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3724 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3725 Ivar->setInvalidDecl();
3731 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3732 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3733 if (S.getLangOpts().ObjCWeak) return;
3735 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3736 ivar; ivar = ivar->getNextIvar()) {
3737 if (ivar->isInvalidDecl()) continue;
3738 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3739 if (S.getLangOpts().ObjCWeakRuntime) {
3740 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3742 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3748 /// Diagnose attempts to use flexible array member with retainable object type.
3749 static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3750 ObjCInterfaceDecl *ID) {
3751 if (!S.getLangOpts().ObjCAutoRefCount)
3754 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3755 ivar = ivar->getNextIvar()) {
3756 if (ivar->isInvalidDecl())
3758 QualType IvarTy = ivar->getType();
3759 if (IvarTy->isIncompleteArrayType() &&
3760 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3761 IvarTy->isObjCLifetimeType()) {
3762 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3763 ivar->setInvalidDecl();
3768 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3769 switch (CurContext->getDeclKind()) {
3770 case Decl::ObjCInterface:
3771 return Sema::OCK_Interface;
3772 case Decl::ObjCProtocol:
3773 return Sema::OCK_Protocol;
3774 case Decl::ObjCCategory:
3775 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3776 return Sema::OCK_ClassExtension;
3777 return Sema::OCK_Category;
3778 case Decl::ObjCImplementation:
3779 return Sema::OCK_Implementation;
3780 case Decl::ObjCCategoryImpl:
3781 return Sema::OCK_CategoryImplementation;
3784 return Sema::OCK_None;
3788 static bool IsVariableSizedType(QualType T) {
3789 if (T->isIncompleteArrayType())
3791 const auto *RecordTy = T->getAs<RecordType>();
3792 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3795 static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3796 ObjCInterfaceDecl *IntfDecl = nullptr;
3797 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3798 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3799 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3800 Ivars = IntfDecl->ivars();
3801 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3802 IntfDecl = ImplDecl->getClassInterface();
3803 Ivars = ImplDecl->ivars();
3804 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3805 if (CategoryDecl->IsClassExtension()) {
3806 IntfDecl = CategoryDecl->getClassInterface();
3807 Ivars = CategoryDecl->ivars();
3811 // Check if variable sized ivar is in interface and visible to subclasses.
3812 if (!isa<ObjCInterfaceDecl>(OCD)) {
3813 for (auto ivar : Ivars) {
3814 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3815 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3816 << ivar->getDeclName() << ivar->getType();
3821 // Subsequent checks require interface decl.
3825 // Check if variable sized ivar is followed by another ivar.
3826 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3827 ivar = ivar->getNextIvar()) {
3828 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3830 QualType IvarTy = ivar->getType();
3831 bool IsInvalidIvar = false;
3832 if (IvarTy->isIncompleteArrayType()) {
3833 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3834 << ivar->getDeclName() << IvarTy
3835 << TTK_Class; // Use "class" for Obj-C.
3836 IsInvalidIvar = true;
3837 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3838 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3839 S.Diag(ivar->getLocation(),
3840 diag::err_objc_variable_sized_type_not_at_end)
3841 << ivar->getDeclName() << IvarTy;
3842 IsInvalidIvar = true;
3845 if (IsInvalidIvar) {
3846 S.Diag(ivar->getNextIvar()->getLocation(),
3847 diag::note_next_ivar_declaration)
3848 << ivar->getNextIvar()->getSynthesize();
3849 ivar->setInvalidDecl();
3853 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3854 // Perform the check only if OCD is the first container to declare ivars to
3855 // avoid multiple warnings for the same ivar.
3856 ObjCIvarDecl *FirstIvar =
3857 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3858 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3859 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3860 while (SuperClass && SuperClass->ivar_empty())
3861 SuperClass = SuperClass->getSuperClass();
3863 auto IvarIter = SuperClass->ivar_begin();
3864 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3865 const ObjCIvarDecl *LastIvar = *IvarIter;
3866 if (IsVariableSizedType(LastIvar->getType())) {
3867 S.Diag(FirstIvar->getLocation(),
3868 diag::warn_superclass_variable_sized_type_not_at_end)
3869 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3870 << LastIvar->getType() << SuperClass->getDeclName();
3871 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3872 << LastIvar->getDeclName();
3878 // Note: For class/category implementations, allMethods is always null.
3879 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
3880 ArrayRef<DeclGroupPtrTy> allTUVars) {
3881 if (getObjCContainerKind() == Sema::OCK_None)
3884 assert(AtEnd.isValid() && "Invalid location for '@end'");
3886 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3887 Decl *ClassDecl = OCD;
3889 bool isInterfaceDeclKind =
3890 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3891 || isa<ObjCProtocolDecl>(ClassDecl);
3892 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3894 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3895 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3896 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3898 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
3899 ObjCMethodDecl *Method =
3900 cast_or_null<ObjCMethodDecl>(allMethods[i]);
3902 if (!Method) continue; // Already issued a diagnostic.
3903 if (Method->isInstanceMethod()) {
3904 /// Check for instance method of the same name with incompatible types
3905 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
3906 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
3908 if ((isInterfaceDeclKind && PrevMethod && !match)
3909 || (checkIdenticalMethods && match)) {
3910 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
3911 << Method->getDeclName();
3912 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3913 Method->setInvalidDecl();
3916 Method->setAsRedeclaration(PrevMethod);
3917 if (!Context.getSourceManager().isInSystemHeader(
3918 Method->getLocation()))
3919 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3920 << Method->getDeclName();
3921 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3923 InsMap[Method->getSelector()] = Method;
3924 /// The following allows us to typecheck messages to "id".
3925 AddInstanceMethodToGlobalPool(Method);
3928 /// Check for class method of the same name with incompatible types
3929 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
3930 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
3932 if ((isInterfaceDeclKind && PrevMethod && !match)
3933 || (checkIdenticalMethods && match)) {
3934 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
3935 << Method->getDeclName();
3936 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3937 Method->setInvalidDecl();
3940 Method->setAsRedeclaration(PrevMethod);
3941 if (!Context.getSourceManager().isInSystemHeader(
3942 Method->getLocation()))
3943 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3944 << Method->getDeclName();
3945 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3947 ClsMap[Method->getSelector()] = Method;
3948 AddFactoryMethodToGlobalPool(Method);
3952 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3953 // Nothing to do here.
3954 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
3955 // Categories are used to extend the class by declaring new methods.
3956 // By the same token, they are also used to add new properties. No
3957 // need to compare the added property to those in the class.
3959 if (C->IsClassExtension()) {
3960 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3961 DiagnoseClassExtensionDupMethods(C, CCPrimary);
3964 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
3965 if (CDecl->getIdentifier())
3966 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3967 // user-defined setter/getter. It also synthesizes setter/getter methods
3968 // and adds them to the DeclContext and global method pools.
3969 for (auto *I : CDecl->properties())
3970 ProcessPropertyDecl(I);
3971 CDecl->setAtEndRange(AtEnd);
3973 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
3974 IC->setAtEndRange(AtEnd);
3975 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
3976 // Any property declared in a class extension might have user
3977 // declared setter or getter in current class extension or one
3978 // of the other class extensions. Mark them as synthesized as
3979 // property will be synthesized when property with same name is
3980 // seen in the @implementation.
3981 for (const auto *Ext : IDecl->visible_extensions()) {
3982 for (const auto *Property : Ext->instance_properties()) {
3983 // Skip over properties declared @dynamic
3984 if (const ObjCPropertyImplDecl *PIDecl
3985 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3986 Property->getQueryKind()))
3987 if (PIDecl->getPropertyImplementation()
3988 == ObjCPropertyImplDecl::Dynamic)
3991 for (const auto *Ext : IDecl->visible_extensions()) {
3992 if (ObjCMethodDecl *GetterMethod
3993 = Ext->getInstanceMethod(Property->getGetterName()))
3994 GetterMethod->setPropertyAccessor(true);
3995 if (!Property->isReadOnly())
3996 if (ObjCMethodDecl *SetterMethod
3997 = Ext->getInstanceMethod(Property->getSetterName()))
3998 SetterMethod->setPropertyAccessor(true);
4002 ImplMethodsVsClassMethods(S, IC, IDecl);
4003 AtomicPropertySetterGetterRules(IC, IDecl);
4004 DiagnoseOwningPropertyGetterSynthesis(IC);
4005 DiagnoseUnusedBackingIvarInAccessor(S, IC);
4006 if (IDecl->hasDesignatedInitializers())
4007 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
4008 DiagnoseWeakIvars(*this, IC);
4009 DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
4011 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
4012 if (IDecl->getSuperClass() == nullptr) {
4013 // This class has no superclass, so check that it has been marked with
4014 // __attribute((objc_root_class)).
4015 if (!HasRootClassAttr) {
4016 SourceLocation DeclLoc(IDecl->getLocation());
4017 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
4018 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4019 << IDecl->getIdentifier();
4020 // See if NSObject is in the current scope, and if it is, suggest
4021 // adding " : NSObject " to the class declaration.
4022 NamedDecl *IF = LookupSingleName(TUScope,
4023 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4024 DeclLoc, LookupOrdinaryName);
4025 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4026 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4027 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4028 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4030 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4033 } else if (HasRootClassAttr) {
4034 // Complain that only root classes may have this attribute.
4035 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4038 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4039 // An interface can subclass another interface with a
4040 // objc_subclassing_restricted attribute when it has that attribute as
4041 // well (because of interfaces imported from Swift). Therefore we have
4042 // to check if we can subclass in the implementation as well.
4043 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4044 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4045 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4046 Diag(Super->getLocation(), diag::note_class_declared);
4050 if (LangOpts.ObjCRuntime.isNonFragile()) {
4051 while (IDecl->getSuperClass()) {
4052 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4053 IDecl = IDecl->getSuperClass();
4057 SetIvarInitializers(IC);
4058 } else if (ObjCCategoryImplDecl* CatImplClass =
4059 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
4060 CatImplClass->setAtEndRange(AtEnd);
4062 // Find category interface decl and then check that all methods declared
4063 // in this interface are implemented in the category @implementation.
4064 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
4065 if (ObjCCategoryDecl *Cat
4066 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4067 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
4070 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4071 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4072 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4073 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4074 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4075 Diag(Super->getLocation(), diag::note_class_declared);
4079 DiagnoseVariableSizedIvars(*this, OCD);
4080 if (isInterfaceDeclKind) {
4081 // Reject invalid vardecls.
4082 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4083 DeclGroupRef DG = allTUVars[i].get();
4084 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4085 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
4086 if (!VDecl->hasExternalStorage())
4087 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
4091 ActOnObjCContainerFinishDefinition();
4093 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
4094 DeclGroupRef DG = allTUVars[i].get();
4095 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4096 (*I)->setTopLevelDeclInObjCContainer();
4097 Consumer.HandleTopLevelDeclInObjCContainer(DG);
4100 ActOnDocumentableDecl(ClassDecl);
4104 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4105 /// objective-c's type qualifier from the parser version of the same info.
4106 static Decl::ObjCDeclQualifier
4107 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
4108 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
4111 /// Check whether the declared result type of the given Objective-C
4112 /// method declaration is compatible with the method's class.
4114 static Sema::ResultTypeCompatibilityKind
4115 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4116 ObjCInterfaceDecl *CurrentClass) {
4117 QualType ResultType = Method->getReturnType();
4119 // If an Objective-C method inherits its related result type, then its
4120 // declared result type must be compatible with its own class type. The
4121 // declared result type is compatible if:
4122 if (const ObjCObjectPointerType *ResultObjectType
4123 = ResultType->getAs<ObjCObjectPointerType>()) {
4124 // - it is id or qualified id, or
4125 if (ResultObjectType->isObjCIdType() ||
4126 ResultObjectType->isObjCQualifiedIdType())
4127 return Sema::RTC_Compatible;
4130 if (ObjCInterfaceDecl *ResultClass
4131 = ResultObjectType->getInterfaceDecl()) {
4132 // - it is the same as the method's class type, or
4133 if (declaresSameEntity(CurrentClass, ResultClass))
4134 return Sema::RTC_Compatible;
4136 // - it is a superclass of the method's class type
4137 if (ResultClass->isSuperClassOf(CurrentClass))
4138 return Sema::RTC_Compatible;
4141 // Any Objective-C pointer type might be acceptable for a protocol
4142 // method; we just don't know.
4143 return Sema::RTC_Unknown;
4147 return Sema::RTC_Incompatible;
4151 /// A helper class for searching for methods which a particular method
4153 class OverrideSearch {
4156 ObjCMethodDecl *Method;
4157 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
4161 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
4162 Selector selector = method->getSelector();
4164 // Bypass this search if we've never seen an instance/class method
4165 // with this selector before.
4166 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4167 if (it == S.MethodPool.end()) {
4168 if (!S.getExternalSource()) return;
4169 S.ReadMethodPool(selector);
4171 it = S.MethodPool.find(selector);
4172 if (it == S.MethodPool.end())
4175 ObjCMethodList &list =
4176 method->isInstanceMethod() ? it->second.first : it->second.second;
4177 if (!list.getMethod()) return;
4179 ObjCContainerDecl *container
4180 = cast<ObjCContainerDecl>(method->getDeclContext());
4182 // Prevent the search from reaching this container again. This is
4183 // important with categories, which override methods from the
4184 // interface and each other.
4185 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4186 searchFromContainer(container);
4187 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4188 searchFromContainer(Interface);
4190 searchFromContainer(container);
4194 typedef decltype(Overridden)::iterator iterator;
4195 iterator begin() const { return Overridden.begin(); }
4196 iterator end() const { return Overridden.end(); }
4199 void searchFromContainer(ObjCContainerDecl *container) {
4200 if (container->isInvalidDecl()) return;
4202 switch (container->getDeclKind()) {
4203 #define OBJCCONTAINER(type, base) \
4205 searchFrom(cast<type##Decl>(container)); \
4207 #define ABSTRACT_DECL(expansion)
4208 #define DECL(type, base) \
4210 #include "clang/AST/DeclNodes.inc"
4211 llvm_unreachable("not an ObjC container!");
4215 void searchFrom(ObjCProtocolDecl *protocol) {
4216 if (!protocol->hasDefinition())
4219 // A method in a protocol declaration overrides declarations from
4220 // referenced ("parent") protocols.
4221 search(protocol->getReferencedProtocols());
4224 void searchFrom(ObjCCategoryDecl *category) {
4225 // A method in a category declaration overrides declarations from
4226 // the main class and from protocols the category references.
4227 // The main class is handled in the constructor.
4228 search(category->getReferencedProtocols());
4231 void searchFrom(ObjCCategoryImplDecl *impl) {
4232 // A method in a category definition that has a category
4233 // declaration overrides declarations from the category
4235 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4237 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4240 // Otherwise it overrides declarations from the class.
4241 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4246 void searchFrom(ObjCInterfaceDecl *iface) {
4247 // A method in a class declaration overrides declarations from
4248 if (!iface->hasDefinition())
4252 for (auto *Cat : iface->known_categories())
4255 // - the super class, and
4256 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4259 // - any referenced protocols.
4260 search(iface->getReferencedProtocols());
4263 void searchFrom(ObjCImplementationDecl *impl) {
4264 // A method in a class implementation overrides declarations from
4265 // the class interface.
4266 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4270 void search(const ObjCProtocolList &protocols) {
4271 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4276 void search(ObjCContainerDecl *container) {
4277 // Check for a method in this container which matches this selector.
4278 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4279 Method->isInstanceMethod(),
4280 /*AllowHidden=*/true);
4282 // If we find one, record it and bail out.
4284 Overridden.insert(meth);
4288 // Otherwise, search for methods that a hypothetical method here
4289 // would have overridden.
4291 // Note that we're now in a recursive case.
4294 searchFromContainer(container);
4297 } // end anonymous namespace
4299 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4300 ObjCInterfaceDecl *CurrentClass,
4301 ResultTypeCompatibilityKind RTC) {
4302 // Search for overridden methods and merge information down from them.
4303 OverrideSearch overrides(*this, ObjCMethod);
4304 // Keep track if the method overrides any method in the class's base classes,
4305 // its protocols, or its categories' protocols; we will keep that info
4306 // in the ObjCMethodDecl.
4307 // For this info, a method in an implementation is not considered as
4308 // overriding the same method in the interface or its categories.
4309 bool hasOverriddenMethodsInBaseOrProtocol = false;
4310 for (OverrideSearch::iterator
4311 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4312 ObjCMethodDecl *overridden = *i;
4314 if (!hasOverriddenMethodsInBaseOrProtocol) {
4315 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4316 CurrentClass != overridden->getClassInterface() ||
4317 overridden->isOverriding()) {
4318 hasOverriddenMethodsInBaseOrProtocol = true;
4320 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4321 // OverrideSearch will return as "overridden" the same method in the
4322 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4323 // check whether a category of a base class introduced a method with the
4324 // same selector, after the interface method declaration.
4325 // To avoid unnecessary lookups in the majority of cases, we use the
4326 // extra info bits in GlobalMethodPool to check whether there were any
4327 // category methods with this selector.
4328 GlobalMethodPool::iterator It =
4329 MethodPool.find(ObjCMethod->getSelector());
4330 if (It != MethodPool.end()) {
4331 ObjCMethodList &List =
4332 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4333 unsigned CategCount = List.getBits();
4334 if (CategCount > 0) {
4335 // If the method is in a category we'll do lookup if there were at
4336 // least 2 category methods recorded, otherwise only one will do.
4337 if (CategCount > 1 ||
4338 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4339 OverrideSearch overrides(*this, overridden);
4340 for (OverrideSearch::iterator
4341 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4342 ObjCMethodDecl *SuperOverridden = *OI;
4343 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4344 CurrentClass != SuperOverridden->getClassInterface()) {
4345 hasOverriddenMethodsInBaseOrProtocol = true;
4346 overridden->setOverriding(true);
4356 // Propagate down the 'related result type' bit from overridden methods.
4357 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4358 ObjCMethod->setRelatedResultType();
4360 // Then merge the declarations.
4361 mergeObjCMethodDecls(ObjCMethod, overridden);
4363 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4364 continue; // Conflicting properties are detected elsewhere.
4366 // Check for overriding methods
4367 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4368 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4369 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4370 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4372 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4373 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4374 !overridden->isImplicit() /* not meant for properties */) {
4375 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4376 E = ObjCMethod->param_end();
4377 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4378 PrevE = overridden->param_end();
4379 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4380 assert(PrevI != overridden->param_end() && "Param mismatch");
4381 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4382 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4383 // If type of argument of method in this class does not match its
4384 // respective argument type in the super class method, issue warning;
4385 if (!Context.typesAreCompatible(T1, T2)) {
4386 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4388 Diag(overridden->getLocation(), diag::note_previous_declaration);
4395 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4398 /// Merge type nullability from for a redeclaration of the same entity,
4399 /// producing the updated type of the redeclared entity.
4400 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4403 SourceLocation prevLoc,
4405 bool prevUsesCSKeyword) {
4406 // Determine the nullability of both types.
4407 auto nullability = type->getNullability(S.Context);
4408 auto prevNullability = prevType->getNullability(S.Context);
4410 // Easy case: both have nullability.
4411 if (nullability.hasValue() == prevNullability.hasValue()) {
4412 // Neither has nullability; continue.
4416 // The nullabilities are equivalent; do nothing.
4417 if (*nullability == *prevNullability)
4420 // Complain about mismatched nullability.
4421 S.Diag(loc, diag::err_nullability_conflicting)
4422 << DiagNullabilityKind(*nullability, usesCSKeyword)
4423 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4427 // If it's the redeclaration that has nullability, don't change anything.
4431 // Otherwise, provide the result with the same nullability.
4432 return S.Context.getAttributedType(
4433 AttributedType::getNullabilityAttrKind(*prevNullability),
4437 /// Merge information from the declaration of a method in the \@interface
4438 /// (or a category/extension) into the corresponding method in the
4439 /// @implementation (for a class or category).
4440 static void mergeInterfaceMethodToImpl(Sema &S,
4441 ObjCMethodDecl *method,
4442 ObjCMethodDecl *prevMethod) {
4443 // Merge the objc_requires_super attribute.
4444 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4445 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4446 // merge the attribute into implementation.
4448 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4449 method->getLocation()));
4452 // Merge nullability of the result type.
4453 QualType newReturnType
4454 = mergeTypeNullabilityForRedecl(
4455 S, method->getReturnTypeSourceRange().getBegin(),
4456 method->getReturnType(),
4457 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4458 prevMethod->getReturnTypeSourceRange().getBegin(),
4459 prevMethod->getReturnType(),
4460 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4461 method->setReturnType(newReturnType);
4463 // Handle each of the parameters.
4464 unsigned numParams = method->param_size();
4465 unsigned numPrevParams = prevMethod->param_size();
4466 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4467 ParmVarDecl *param = method->param_begin()[i];
4468 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4470 // Merge nullability.
4471 QualType newParamType
4472 = mergeTypeNullabilityForRedecl(
4473 S, param->getLocation(), param->getType(),
4474 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4475 prevParam->getLocation(), prevParam->getType(),
4476 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4477 param->setType(newParamType);
4481 /// Verify that the method parameters/return value have types that are supported
4482 /// by the x86 target.
4483 static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4484 const ObjCMethodDecl *Method) {
4485 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4486 llvm::Triple::x86 &&
4487 "x86-specific check invoked for a different target");
4490 for (const ParmVarDecl *P : Method->parameters()) {
4491 if (P->getType()->isVectorType()) {
4492 Loc = P->getBeginLoc();
4497 if (Loc.isInvalid()) {
4498 if (Method->getReturnType()->isVectorType()) {
4499 Loc = Method->getReturnTypeSourceRange().getBegin();
4500 T = Method->getReturnType();
4505 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4506 // iOS < 9 and macOS < 10.11.
4507 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4508 VersionTuple AcceptedInVersion;
4509 if (Triple.getOS() == llvm::Triple::IOS)
4510 AcceptedInVersion = VersionTuple(/*Major=*/9);
4511 else if (Triple.isMacOSX())
4512 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4515 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
4518 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4519 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4521 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4524 Decl *Sema::ActOnMethodDeclaration(
4525 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4526 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4527 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4528 // optional arguments. The number of types/arguments is obtained
4529 // from the Sel.getNumArgs().
4530 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4531 unsigned CNumArgs, // c-style args
4532 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4533 bool isVariadic, bool MethodDefinition) {
4534 // Make sure we can establish a context for the method.
4535 if (!CurContext->isObjCContainer()) {
4536 Diag(MethodLoc, diag::err_missing_method_context);
4539 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
4540 QualType resultDeclType;
4542 bool HasRelatedResultType = false;
4543 TypeSourceInfo *ReturnTInfo = nullptr;
4545 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4547 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4550 QualType bareResultType = resultDeclType;
4551 (void)AttributedType::stripOuterNullability(bareResultType);
4552 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4553 } else { // get the type for "id".
4554 resultDeclType = Context.getObjCIdType();
4555 Diag(MethodLoc, diag::warn_missing_method_return_type)
4556 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4559 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4560 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4561 MethodType == tok::minus, isVariadic,
4562 /*isPropertyAccessor=*/false,
4563 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4564 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4565 : ObjCMethodDecl::Required,
4566 HasRelatedResultType);
4568 SmallVector<ParmVarDecl*, 16> Params;
4570 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4574 if (!ArgInfo[i].Type) {
4575 ArgType = Context.getObjCIdType();
4578 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4581 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4582 LookupOrdinaryName, forRedeclarationInCurContext());
4584 if (R.isSingleResult()) {
4585 NamedDecl *PrevDecl = R.getFoundDecl();
4586 if (S->isDeclScope(PrevDecl)) {
4587 Diag(ArgInfo[i].NameLoc,
4588 (MethodDefinition ? diag::warn_method_param_redefinition
4589 : diag::warn_method_param_declaration))
4591 Diag(PrevDecl->getLocation(),
4592 diag::note_previous_declaration);
4596 SourceLocation StartLoc = DI
4597 ? DI->getTypeLoc().getBeginLoc()
4598 : ArgInfo[i].NameLoc;
4600 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4601 ArgInfo[i].NameLoc, ArgInfo[i].Name,
4602 ArgType, DI, SC_None);
4604 Param->setObjCMethodScopeInfo(i);
4606 Param->setObjCDeclQualifier(
4607 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4609 // Apply the attributes to the parameter.
4610 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4611 AddPragmaAttributes(TUScope, Param);
4613 if (Param->hasAttr<BlocksAttr>()) {
4614 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4615 Param->setInvalidDecl();
4618 IdResolver.AddDecl(Param);
4620 Params.push_back(Param);
4623 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4624 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4625 QualType ArgType = Param->getType();
4626 if (ArgType.isNull())
4627 ArgType = Context.getObjCIdType();
4629 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4630 ArgType = Context.getAdjustedParameterType(ArgType);
4632 Param->setDeclContext(ObjCMethod);
4633 Params.push_back(Param);
4636 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4637 ObjCMethod->setObjCDeclQualifier(
4638 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4640 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4641 AddPragmaAttributes(TUScope, ObjCMethod);
4643 // Add the method now.
4644 const ObjCMethodDecl *PrevMethod = nullptr;
4645 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4646 if (MethodType == tok::minus) {
4647 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4648 ImpDecl->addInstanceMethod(ObjCMethod);
4650 PrevMethod = ImpDecl->getClassMethod(Sel);
4651 ImpDecl->addClassMethod(ObjCMethod);
4654 // Merge information from the @interface declaration into the
4656 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4657 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4658 ObjCMethod->isInstanceMethod())) {
4659 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4661 // Warn about defining -dealloc in a category.
4662 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4663 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4664 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4665 << ObjCMethod->getDeclName();
4669 // Warn if a method declared in a protocol to which a category or
4670 // extension conforms is non-escaping and the implementation's method is
4672 for (auto *C : IDecl->visible_categories())
4673 for (auto &P : C->protocols())
4674 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4675 ObjCMethod->isInstanceMethod())) {
4676 assert(ObjCMethod->parameters().size() ==
4677 IMD->parameters().size() &&
4678 "Methods have different number of parameters");
4679 auto OI = IMD->param_begin(), OE = IMD->param_end();
4680 auto NI = ObjCMethod->param_begin();
4681 for (; OI != OE; ++OI, ++NI)
4682 diagnoseNoescape(*NI, *OI, C, P, *this);
4686 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4690 // You can never have two method definitions with the same name.
4691 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
4692 << ObjCMethod->getDeclName();
4693 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4694 ObjCMethod->setInvalidDecl();
4698 // If this Objective-C method does not have a related result type, but we
4699 // are allowed to infer related result types, try to do so based on the
4701 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4702 if (!CurrentClass) {
4703 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4704 CurrentClass = Cat->getClassInterface();
4705 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4706 CurrentClass = Impl->getClassInterface();
4707 else if (ObjCCategoryImplDecl *CatImpl
4708 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4709 CurrentClass = CatImpl->getClassInterface();
4712 ResultTypeCompatibilityKind RTC
4713 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
4715 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
4717 bool ARCError = false;
4718 if (getLangOpts().ObjCAutoRefCount)
4719 ARCError = CheckARCMethodDecl(ObjCMethod);
4721 // Infer the related result type when possible.
4722 if (!ARCError && RTC == Sema::RTC_Compatible &&
4723 !ObjCMethod->hasRelatedResultType() &&
4724 LangOpts.ObjCInferRelatedResultType) {
4725 bool InferRelatedResultType = false;
4726 switch (ObjCMethod->getMethodFamily()) {
4731 case OMF_mutableCopy:
4733 case OMF_retainCount:
4734 case OMF_initialize:
4735 case OMF_performSelector:
4740 InferRelatedResultType = ObjCMethod->isClassMethod();
4744 case OMF_autorelease:
4747 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4751 if (InferRelatedResultType &&
4752 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
4753 ObjCMethod->setRelatedResultType();
4756 if (MethodDefinition &&
4757 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4758 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4760 // + load method cannot have availability attributes. It get called on
4761 // startup, so it has to have the availability of the deployment target.
4762 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
4763 if (ObjCMethod->isClassMethod() &&
4764 ObjCMethod->getSelector().getAsString() == "load") {
4765 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
4767 ObjCMethod->dropAttr<AvailabilityAttr>();
4771 ActOnDocumentableDecl(ObjCMethod);
4776 bool Sema::CheckObjCDeclScope(Decl *D) {
4777 // Following is also an error. But it is caused by a missing @end
4778 // and diagnostic is issued elsewhere.
4779 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
4782 // If we switched context to translation unit while we are still lexically in
4783 // an objc container, it means the parser missed emitting an error.
4784 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4787 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4788 D->setInvalidDecl();
4793 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
4794 /// instance variables of ClassName into Decls.
4795 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
4796 IdentifierInfo *ClassName,
4797 SmallVectorImpl<Decl*> &Decls) {
4798 // Check that ClassName is a valid class
4799 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
4801 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4804 if (LangOpts.ObjCRuntime.isNonFragile()) {
4805 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4809 // Collect the instance variables
4810 SmallVector<const ObjCIvarDecl*, 32> Ivars;
4811 Context.DeepCollectObjCIvars(Class, true, Ivars);
4812 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
4813 for (unsigned i = 0; i < Ivars.size(); i++) {
4814 const FieldDecl* ID = Ivars[i];
4815 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
4816 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4817 /*FIXME: StartL=*/ID->getLocation(),
4819 ID->getIdentifier(), ID->getType(),
4821 Decls.push_back(FD);
4824 // Introduce all of these fields into the appropriate scope.
4825 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
4826 D != Decls.end(); ++D) {
4827 FieldDecl *FD = cast<FieldDecl>(*D);
4828 if (getLangOpts().CPlusPlus)
4829 PushOnScopeChains(FD, S);
4830 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
4831 Record->addDecl(FD);
4835 /// Build a type-check a new Objective-C exception variable declaration.
4836 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4837 SourceLocation StartLoc,
4838 SourceLocation IdLoc,
4841 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4842 // duration shall not be qualified by an address-space qualifier."
4843 // Since all parameters have automatic store duration, they can not have
4844 // an address space.
4845 if (T.getAddressSpace() != LangAS::Default) {
4846 Diag(IdLoc, diag::err_arg_with_address_space);
4850 // An @catch parameter must be an unqualified object pointer type;
4851 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4853 // Don't do any further checking.
4854 } else if (T->isDependentType()) {
4855 // Okay: we don't know what this type will instantiate to.
4856 } else if (T->isObjCQualifiedIdType()) {
4858 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
4859 } else if (T->isObjCIdType()) {
4860 // Okay: we don't know what this type will instantiate to.
4861 } else if (!T->isObjCObjectPointerType()) {
4863 Diag(IdLoc, diag::err_catch_param_not_objc_type);
4864 } else if (!T->getAs<ObjCObjectPointerType>()->getInterfaceType()) {
4866 Diag(IdLoc, diag::err_catch_param_not_objc_type);
4869 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
4871 New->setExceptionVariable(true);
4873 // In ARC, infer 'retaining' for variables of retainable type.
4874 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
4878 New->setInvalidDecl();
4882 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
4883 const DeclSpec &DS = D.getDeclSpec();
4885 // We allow the "register" storage class on exception variables because
4886 // GCC did, but we drop it completely. Any other storage class is an error.
4887 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4888 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4889 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
4890 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4891 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
4892 << DeclSpec::getSpecifierName(SCS);
4894 if (DS.isInlineSpecified())
4895 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4896 << getLangOpts().CPlusPlus17;
4897 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4898 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4899 diag::err_invalid_thread)
4900 << DeclSpec::getSpecifierName(TSCS);
4901 D.getMutableDeclSpec().ClearStorageClassSpecs();
4903 DiagnoseFunctionSpecifiers(D.getDeclSpec());
4905 // Check that there are no default arguments inside the type of this
4906 // exception object (C++ only).
4907 if (getLangOpts().CPlusPlus)
4908 CheckExtraCXXDefaultArguments(D);
4910 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4911 QualType ExceptionType = TInfo->getType();
4913 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4914 D.getSourceRange().getBegin(),
4915 D.getIdentifierLoc(),
4919 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4920 if (D.getCXXScopeSpec().isSet()) {
4921 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4922 << D.getCXXScopeSpec().getRange();
4923 New->setInvalidDecl();
4926 // Add the parameter declaration into this scope.
4928 if (D.getIdentifier())
4929 IdResolver.AddDecl(New);
4931 ProcessDeclAttributes(S, New, D);
4933 if (New->hasAttr<BlocksAttr>())
4934 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4938 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4940 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4941 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
4942 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4943 Iv= Iv->getNextIvar()) {
4944 QualType QT = Context.getBaseElementType(Iv->getType());
4945 if (QT->isRecordType())
4946 Ivars.push_back(Iv);
4950 void Sema::DiagnoseUseOfUnimplementedSelectors() {
4951 // Load referenced selectors from the external source.
4952 if (ExternalSource) {
4953 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4954 ExternalSource->ReadReferencedSelectors(Sels);
4955 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4956 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4959 // Warning will be issued only when selector table is
4960 // generated (which means there is at lease one implementation
4961 // in the TU). This is to match gcc's behavior.
4962 if (ReferencedSelectors.empty() ||
4963 !Context.AnyObjCImplementation())
4965 for (auto &SelectorAndLocation : ReferencedSelectors) {
4966 Selector Sel = SelectorAndLocation.first;
4967 SourceLocation Loc = SelectorAndLocation.second;
4968 if (!LookupImplementedMethodInGlobalPool(Sel))
4969 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
4974 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4975 const ObjCPropertyDecl *&PDecl) const {
4976 if (Method->isClassMethod())
4978 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4981 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4982 /*shallowCategoryLookup=*/false,
4983 /*followSuper=*/false);
4984 if (!Method || !Method->isPropertyAccessor())
4986 if ((PDecl = Method->findPropertyDecl()))
4987 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4988 // property backing ivar must belong to property's class
4989 // or be a private ivar in class's implementation.
4990 // FIXME. fix the const-ness issue.
4991 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4992 IV->getIdentifier());
4999 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
5000 /// accessor references the backing ivar.
5001 class UnusedBackingIvarChecker :
5002 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
5005 const ObjCMethodDecl *Method;
5006 const ObjCIvarDecl *IvarD;
5008 bool InvokedSelfMethod;
5010 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5011 const ObjCIvarDecl *IvarD)
5012 : S(S), Method(Method), IvarD(IvarD),
5013 AccessedIvar(false), InvokedSelfMethod(false) {
5017 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5018 if (E->getDecl() == IvarD) {
5019 AccessedIvar = true;
5025 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5026 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5027 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5028 InvokedSelfMethod = true;
5033 } // end anonymous namespace
5035 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5036 const ObjCImplementationDecl *ImplD) {
5037 if (S->hasUnrecoverableErrorOccurred())
5040 for (const auto *CurMethod : ImplD->instance_methods()) {
5041 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5042 SourceLocation Loc = CurMethod->getLocation();
5043 if (Diags.isIgnored(DIAG, Loc))
5046 const ObjCPropertyDecl *PDecl;
5047 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5051 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5052 Checker.TraverseStmt(CurMethod->getBody());
5053 if (Checker.AccessedIvar)
5056 // Do not issue this warning if backing ivar is used somewhere and accessor
5057 // implementation makes a self call. This is to prevent false positive in
5058 // cases where the ivar is accessed by another method that the accessor
5060 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
5061 Diag(Loc, DIAG) << IV;
5062 Diag(PDecl->getLocation(), diag::note_property_declare);