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 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
113 const ObjCMethodDecl *Overridden) {
114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
120 QualType ResultType = NewMethod->getReturnType();
121 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
123 // Figure out which class this method is part of, if any.
124 ObjCInterfaceDecl *CurrentClass
125 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
127 DeclContext *DC = NewMethod->getDeclContext();
128 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
129 CurrentClass = Cat->getClassInterface();
130 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
131 CurrentClass = Impl->getClassInterface();
132 else if (ObjCCategoryImplDecl *CatImpl
133 = dyn_cast<ObjCCategoryImplDecl>(DC))
134 CurrentClass = CatImpl->getClassInterface();
138 Diag(NewMethod->getLocation(),
139 diag::warn_related_result_type_compatibility_class)
140 << Context.getObjCInterfaceType(CurrentClass)
144 Diag(NewMethod->getLocation(),
145 diag::warn_related_result_type_compatibility_protocol)
150 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
151 Diag(Overridden->getLocation(),
152 diag::note_related_result_type_family)
153 << /*overridden method*/ 0
156 Diag(Overridden->getLocation(),
157 diag::note_related_result_type_overridden);
159 if (getLangOpts().ObjCAutoRefCount) {
160 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162 Diag(NewMethod->getLocation(),
163 diag::err_nsreturns_retained_attribute_mismatch) << 1;
164 Diag(Overridden->getLocation(), diag::note_previous_decl)
167 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
168 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
169 Diag(NewMethod->getLocation(),
170 diag::err_nsreturns_retained_attribute_mismatch) << 0;
171 Diag(Overridden->getLocation(), diag::note_previous_decl)
174 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
175 oe = Overridden->param_end();
176 for (ObjCMethodDecl::param_iterator
177 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
178 ni != ne && oi != oe; ++ni, ++oi) {
179 const ParmVarDecl *oldDecl = (*oi);
180 ParmVarDecl *newDecl = (*ni);
181 if (newDecl->hasAttr<NSConsumedAttr>() !=
182 oldDecl->hasAttr<NSConsumedAttr>()) {
183 Diag(newDecl->getLocation(),
184 diag::err_nsconsumed_attribute_mismatch);
185 Diag(oldDecl->getLocation(), diag::note_previous_decl)
192 /// \brief Check a method declaration for compatibility with the Objective-C
194 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
195 ObjCMethodFamily family = method->getMethodFamily();
201 case OMF_autorelease:
202 case OMF_retainCount:
205 case OMF_performSelector:
209 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
210 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
211 if (ResultTypeRange.isInvalid())
212 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
213 << method->getReturnType()
214 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
216 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
217 << method->getReturnType()
218 << FixItHint::CreateReplacement(ResultTypeRange, "void");
224 // If the method doesn't obey the init rules, don't bother annotating it.
225 if (checkInitMethod(method, QualType()))
228 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
230 // Don't add a second copy of this attribute, but otherwise don't
231 // let it be suppressed.
232 if (method->hasAttr<NSReturnsRetainedAttr>())
238 case OMF_mutableCopy:
240 if (method->hasAttr<NSReturnsRetainedAttr>() ||
241 method->hasAttr<NSReturnsNotRetainedAttr>() ||
242 method->hasAttr<NSReturnsAutoreleasedAttr>())
247 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
251 static void DiagnoseObjCImplementedDeprecations(Sema &S,
253 SourceLocation ImplLoc,
255 if (ND && ND->isDeprecated()) {
256 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
258 S.Diag(ND->getLocation(), diag::note_method_declared_at)
259 << ND->getDeclName();
261 S.Diag(ND->getLocation(), diag::note_previous_decl)
262 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
266 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
268 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
269 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
271 // If we don't have a valid method decl, simply return.
274 if (MDecl->isInstanceMethod())
275 AddInstanceMethodToGlobalPool(MDecl, true);
277 AddFactoryMethodToGlobalPool(MDecl, true);
280 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
281 /// has explicit ownership attribute; false otherwise.
283 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
284 QualType T = Param->getType();
286 if (const PointerType *PT = T->getAs<PointerType>()) {
287 T = PT->getPointeeType();
288 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
289 T = RT->getPointeeType();
294 // If we have a lifetime qualifier, but it's local, we must have
295 // inferred it. So, it is implicit.
296 return !T.getLocalQualifiers().hasObjCLifetime();
299 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
300 /// and user declared, in the method definition's AST.
301 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
302 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
303 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
305 // If we don't have a valid method decl, simply return.
309 // Allow all of Sema to see that we are entering a method definition.
310 PushDeclContext(FnBodyScope, MDecl);
313 // Create Decl objects for each parameter, entrring them in the scope for
314 // binding to their use.
316 // Insert the invisible arguments, self and _cmd!
317 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
319 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
320 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
322 // The ObjC parser requires parameter names so there's no need to check.
323 CheckParmsForFunctionDef(MDecl->parameters(),
324 /*CheckParameterNames=*/false);
326 // Introduce all of the other parameters into this scope.
327 for (auto *Param : MDecl->parameters()) {
328 if (!Param->isInvalidDecl() &&
329 getLangOpts().ObjCAutoRefCount &&
330 !HasExplicitOwnershipAttr(*this, Param))
331 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
334 if (Param->getIdentifier())
335 PushOnScopeChains(Param, FnBodyScope);
338 // In ARC, disallow definition of retain/release/autorelease/retainCount
339 if (getLangOpts().ObjCAutoRefCount) {
340 switch (MDecl->getMethodFamily()) {
342 case OMF_retainCount:
344 case OMF_autorelease:
345 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
346 << 0 << MDecl->getSelector();
354 case OMF_mutableCopy:
359 case OMF_performSelector:
364 // Warn on deprecated methods under -Wdeprecated-implementations,
365 // and prepare for warning on missing super calls.
366 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
367 ObjCMethodDecl *IMD =
368 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
371 ObjCImplDecl *ImplDeclOfMethodDef =
372 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
373 ObjCContainerDecl *ContDeclOfMethodDecl =
374 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
375 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
376 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
377 ImplDeclOfMethodDecl = OID->getImplementation();
378 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
379 if (CD->IsClassExtension()) {
380 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
381 ImplDeclOfMethodDecl = OID->getImplementation();
383 ImplDeclOfMethodDecl = CD->getImplementation();
385 // No need to issue deprecated warning if deprecated mehod in class/category
386 // is being implemented in its own implementation (no overriding is involved).
387 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
388 DiagnoseObjCImplementedDeprecations(*this,
389 dyn_cast<NamedDecl>(IMD),
390 MDecl->getLocation(), 0);
393 if (MDecl->getMethodFamily() == OMF_init) {
394 if (MDecl->isDesignatedInitializerForTheInterface()) {
395 getCurFunction()->ObjCIsDesignatedInit = true;
396 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
397 IC->getSuperClass() != nullptr;
398 } else if (IC->hasDesignatedInitializers()) {
399 getCurFunction()->ObjCIsSecondaryInit = true;
400 getCurFunction()->ObjCWarnForNoInitDelegation = true;
404 // If this is "dealloc" or "finalize", set some bit here.
405 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
406 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
407 // Only do this if the current class actually has a superclass.
408 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
409 ObjCMethodFamily Family = MDecl->getMethodFamily();
410 if (Family == OMF_dealloc) {
411 if (!(getLangOpts().ObjCAutoRefCount ||
412 getLangOpts().getGC() == LangOptions::GCOnly))
413 getCurFunction()->ObjCShouldCallSuper = true;
415 } else if (Family == OMF_finalize) {
416 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
417 getCurFunction()->ObjCShouldCallSuper = true;
420 const ObjCMethodDecl *SuperMethod =
421 SuperClass->lookupMethod(MDecl->getSelector(),
422 MDecl->isInstanceMethod());
423 getCurFunction()->ObjCShouldCallSuper =
424 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
432 // Callback to only accept typo corrections that are Objective-C classes.
433 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
434 // function will reject corrections to that class.
435 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
437 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
438 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
439 : CurrentIDecl(IDecl) {}
441 bool ValidateCandidate(const TypoCorrection &candidate) override {
442 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
443 return ID && !declaresSameEntity(ID, CurrentIDecl);
447 ObjCInterfaceDecl *CurrentIDecl;
450 } // end anonymous namespace
452 static void diagnoseUseOfProtocols(Sema &TheSema,
453 ObjCContainerDecl *CD,
454 ObjCProtocolDecl *const *ProtoRefs,
455 unsigned NumProtoRefs,
456 const SourceLocation *ProtoLocs) {
458 // Diagnose availability in the context of the ObjC container.
459 Sema::ContextRAII SavedContext(TheSema, CD);
460 for (unsigned i = 0; i < NumProtoRefs; ++i) {
461 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i]);
466 ActOnSuperClassOfClassInterface(Scope *S,
467 SourceLocation AtInterfaceLoc,
468 ObjCInterfaceDecl *IDecl,
469 IdentifierInfo *ClassName,
470 SourceLocation ClassLoc,
471 IdentifierInfo *SuperName,
472 SourceLocation SuperLoc,
473 ArrayRef<ParsedType> SuperTypeArgs,
474 SourceRange SuperTypeArgsRange) {
475 // Check if a different kind of symbol declared in this scope.
476 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
480 // Try to correct for a typo in the superclass name without correcting
481 // to the class we're defining.
482 if (TypoCorrection Corrected = CorrectTypo(
483 DeclarationNameInfo(SuperName, SuperLoc),
484 LookupOrdinaryName, TUScope,
485 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
486 CTK_ErrorRecovery)) {
487 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
488 << SuperName << ClassName);
489 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
493 if (declaresSameEntity(PrevDecl, IDecl)) {
494 Diag(SuperLoc, diag::err_recursive_superclass)
495 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
496 IDecl->setEndOfDefinitionLoc(ClassLoc);
498 ObjCInterfaceDecl *SuperClassDecl =
499 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
500 QualType SuperClassType;
502 // Diagnose classes that inherit from deprecated classes.
503 if (SuperClassDecl) {
504 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
505 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
508 if (PrevDecl && !SuperClassDecl) {
509 // The previous declaration was not a class decl. Check if we have a
510 // typedef. If we do, get the underlying class type.
511 if (const TypedefNameDecl *TDecl =
512 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
513 QualType T = TDecl->getUnderlyingType();
514 if (T->isObjCObjectType()) {
515 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
516 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
517 SuperClassType = Context.getTypeDeclType(TDecl);
519 // This handles the following case:
520 // @interface NewI @end
521 // typedef NewI DeprI __attribute__((deprecated("blah")))
522 // @interface SI : DeprI /* warn here */ @end
523 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
528 // This handles the following case:
530 // typedef int SuperClass;
531 // @interface MyClass : SuperClass {} @end
533 if (!SuperClassDecl) {
534 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
535 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
539 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
541 Diag(SuperLoc, diag::err_undef_superclass)
542 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
543 else if (RequireCompleteType(SuperLoc,
545 diag::err_forward_superclass,
546 SuperClassDecl->getDeclName(),
548 SourceRange(AtInterfaceLoc, ClassLoc))) {
549 SuperClassDecl = nullptr;
550 SuperClassType = QualType();
554 if (SuperClassType.isNull()) {
555 assert(!SuperClassDecl && "Failed to set SuperClassType?");
559 // Handle type arguments on the superclass.
560 TypeSourceInfo *SuperClassTInfo = nullptr;
561 if (!SuperTypeArgs.empty()) {
562 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
565 CreateParsedType(SuperClassType,
567 SuperTypeArgsRange.getBegin(),
569 SuperTypeArgsRange.getEnd(),
574 if (!fullSuperClassType.isUsable())
577 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
581 if (!SuperClassTInfo) {
582 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
586 IDecl->setSuperClass(SuperClassTInfo);
587 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
591 DeclResult Sema::actOnObjCTypeParam(Scope *S,
592 ObjCTypeParamVariance variance,
593 SourceLocation varianceLoc,
595 IdentifierInfo *paramName,
596 SourceLocation paramLoc,
597 SourceLocation colonLoc,
598 ParsedType parsedTypeBound) {
599 // If there was an explicitly-provided type bound, check it.
600 TypeSourceInfo *typeBoundInfo = nullptr;
601 if (parsedTypeBound) {
602 // The type bound can be any Objective-C pointer type.
603 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
604 if (typeBound->isObjCObjectPointerType()) {
606 } else if (typeBound->isObjCObjectType()) {
607 // The user forgot the * on an Objective-C pointer type, e.g.,
609 SourceLocation starLoc = getLocForEndOfToken(
610 typeBoundInfo->getTypeLoc().getEndLoc());
611 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
612 diag::err_objc_type_param_bound_missing_pointer)
613 << typeBound << paramName
614 << FixItHint::CreateInsertion(starLoc, " *");
616 // Create a new type location builder so we can update the type
617 // location information we have.
618 TypeLocBuilder builder;
619 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
621 // Create the Objective-C pointer type.
622 typeBound = Context.getObjCObjectPointerType(typeBound);
623 ObjCObjectPointerTypeLoc newT
624 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
625 newT.setStarLoc(starLoc);
627 // Form the new type source information.
628 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
630 // Not a valid type bound.
631 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
632 diag::err_objc_type_param_bound_nonobject)
633 << typeBound << paramName;
635 // Forget the bound; we'll default to id later.
636 typeBoundInfo = nullptr;
639 // Type bounds cannot have qualifiers (even indirectly) or explicit
642 QualType typeBound = typeBoundInfo->getType();
643 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
644 if (qual || typeBound.hasQualifiers()) {
645 bool diagnosed = false;
646 SourceRange rangeToRemove;
648 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
649 rangeToRemove = attr.getLocalSourceRange();
650 if (attr.getTypePtr()->getImmediateNullability()) {
651 Diag(attr.getLocStart(),
652 diag::err_objc_type_param_bound_explicit_nullability)
653 << paramName << typeBound
654 << FixItHint::CreateRemoval(rangeToRemove);
661 Diag(qual ? qual.getLocStart()
662 : typeBoundInfo->getTypeLoc().getLocStart(),
663 diag::err_objc_type_param_bound_qualified)
664 << paramName << typeBound << typeBound.getQualifiers().getAsString()
665 << FixItHint::CreateRemoval(rangeToRemove);
668 // If the type bound has qualifiers other than CVR, we need to strip
669 // them or we'll probably assert later when trying to apply new
671 Qualifiers quals = typeBound.getQualifiers();
672 quals.removeCVRQualifiers();
673 if (!quals.empty()) {
675 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
681 // If there was no explicit type bound (or we removed it due to an error),
683 if (!typeBoundInfo) {
684 colonLoc = SourceLocation();
685 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
688 // Create the type parameter.
689 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
690 index, paramLoc, paramName, colonLoc,
694 ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
695 SourceLocation lAngleLoc,
696 ArrayRef<Decl *> typeParamsIn,
697 SourceLocation rAngleLoc) {
698 // We know that the array only contains Objective-C type parameters.
699 ArrayRef<ObjCTypeParamDecl *>
701 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
702 typeParamsIn.size());
704 // Diagnose redeclarations of type parameters.
705 // We do this now because Objective-C type parameters aren't pushed into
706 // scope until later (after the instance variable block), but we want the
707 // diagnostics to occur right after we parse the type parameter list.
708 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
709 for (auto typeParam : typeParams) {
710 auto known = knownParams.find(typeParam->getIdentifier());
711 if (known != knownParams.end()) {
712 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
713 << typeParam->getIdentifier()
714 << SourceRange(known->second->getLocation());
716 typeParam->setInvalidDecl();
718 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
720 // Push the type parameter into scope.
721 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
725 // Create the parameter list.
726 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
729 void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
730 for (auto typeParam : *typeParamList) {
731 if (!typeParam->isInvalidDecl()) {
732 S->RemoveDecl(typeParam);
733 IdResolver.RemoveDecl(typeParam);
739 /// The context in which an Objective-C type parameter list occurs, for use
741 enum class TypeParamListContext {
747 } // end anonymous namespace
749 /// Check consistency between two Objective-C type parameter lists, e.g.,
750 /// between a category/extension and an \@interface or between an \@class and an
752 static bool checkTypeParamListConsistency(Sema &S,
753 ObjCTypeParamList *prevTypeParams,
754 ObjCTypeParamList *newTypeParams,
755 TypeParamListContext newContext) {
756 // If the sizes don't match, complain about that.
757 if (prevTypeParams->size() != newTypeParams->size()) {
758 SourceLocation diagLoc;
759 if (newTypeParams->size() > prevTypeParams->size()) {
760 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
762 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
765 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
766 << static_cast<unsigned>(newContext)
767 << (newTypeParams->size() > prevTypeParams->size())
768 << prevTypeParams->size()
769 << newTypeParams->size();
774 // Match up the type parameters.
775 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
776 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
777 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
779 // Check for consistency of the variance.
780 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
781 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
782 newContext != TypeParamListContext::Definition) {
783 // When the new type parameter is invariant and is not part
784 // of the definition, just propagate the variance.
785 newTypeParam->setVariance(prevTypeParam->getVariance());
786 } else if (prevTypeParam->getVariance()
787 == ObjCTypeParamVariance::Invariant &&
788 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
789 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
790 ->getDefinition() == prevTypeParam->getDeclContext())) {
791 // When the old parameter is invariant and was not part of the
792 // definition, just ignore the difference because it doesn't
796 // Diagnose the conflict and update the second declaration.
797 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
798 if (diagLoc.isInvalid())
799 diagLoc = newTypeParam->getLocStart();
801 auto diag = S.Diag(diagLoc,
802 diag::err_objc_type_param_variance_conflict)
803 << static_cast<unsigned>(newTypeParam->getVariance())
804 << newTypeParam->getDeclName()
805 << static_cast<unsigned>(prevTypeParam->getVariance())
806 << prevTypeParam->getDeclName();
807 switch (prevTypeParam->getVariance()) {
808 case ObjCTypeParamVariance::Invariant:
809 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
812 case ObjCTypeParamVariance::Covariant:
813 case ObjCTypeParamVariance::Contravariant: {
814 StringRef newVarianceStr
815 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
818 if (newTypeParam->getVariance()
819 == ObjCTypeParamVariance::Invariant) {
820 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
821 (newVarianceStr + " ").str());
823 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
830 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
831 << prevTypeParam->getDeclName();
833 // Override the variance.
834 newTypeParam->setVariance(prevTypeParam->getVariance());
838 // If the bound types match, there's nothing to do.
839 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
840 newTypeParam->getUnderlyingType()))
843 // If the new type parameter's bound was explicit, complain about it being
844 // different from the original.
845 if (newTypeParam->hasExplicitBound()) {
846 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
847 ->getTypeLoc().getSourceRange();
848 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
849 << newTypeParam->getUnderlyingType()
850 << newTypeParam->getDeclName()
851 << prevTypeParam->hasExplicitBound()
852 << prevTypeParam->getUnderlyingType()
853 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
854 << prevTypeParam->getDeclName()
855 << FixItHint::CreateReplacement(
857 prevTypeParam->getUnderlyingType().getAsString(
858 S.Context.getPrintingPolicy()));
860 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
861 << prevTypeParam->getDeclName();
863 // Override the new type parameter's bound type with the previous type,
864 // so that it's consistent.
865 newTypeParam->setTypeSourceInfo(
866 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
870 // The new type parameter got the implicit bound of 'id'. That's okay for
871 // categories and extensions (overwrite it later), but not for forward
872 // declarations and @interfaces, because those must be standalone.
873 if (newContext == TypeParamListContext::ForwardDeclaration ||
874 newContext == TypeParamListContext::Definition) {
875 // Diagnose this problem for forward declarations and definitions.
876 SourceLocation insertionLoc
877 = S.getLocForEndOfToken(newTypeParam->getLocation());
879 = " : " + prevTypeParam->getUnderlyingType().getAsString(
880 S.Context.getPrintingPolicy());
881 S.Diag(newTypeParam->getLocation(),
882 diag::err_objc_type_param_bound_missing)
883 << prevTypeParam->getUnderlyingType()
884 << newTypeParam->getDeclName()
885 << (newContext == TypeParamListContext::ForwardDeclaration)
886 << FixItHint::CreateInsertion(insertionLoc, newCode);
888 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
889 << prevTypeParam->getDeclName();
892 // Update the new type parameter's bound to match the previous one.
893 newTypeParam->setTypeSourceInfo(
894 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
901 ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
902 IdentifierInfo *ClassName, SourceLocation ClassLoc,
903 ObjCTypeParamList *typeParamList,
904 IdentifierInfo *SuperName, SourceLocation SuperLoc,
905 ArrayRef<ParsedType> SuperTypeArgs,
906 SourceRange SuperTypeArgsRange,
907 Decl * const *ProtoRefs, unsigned NumProtoRefs,
908 const SourceLocation *ProtoLocs,
909 SourceLocation EndProtoLoc, AttributeList *AttrList) {
910 assert(ClassName && "Missing class identifier");
912 // Check for another declaration kind with the same name.
913 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
914 LookupOrdinaryName, ForRedeclaration);
916 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
917 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
918 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
921 // Create a declaration to describe this @interface.
922 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
924 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
925 // A previous decl with a different name is because of
926 // @compatibility_alias, for example:
929 // @compatibility_alias OldImage NewImage;
931 // A lookup for 'OldImage' will return the 'NewImage' decl.
933 // In such a case use the real declaration name, instead of the alias one,
934 // otherwise we will break IdentifierResolver and redecls-chain invariants.
935 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
937 ClassName = PrevIDecl->getIdentifier();
940 // If there was a forward declaration with type parameters, check
943 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
945 // Both have type parameter lists; check for consistency.
946 if (checkTypeParamListConsistency(*this, prevTypeParamList,
948 TypeParamListContext::Definition)) {
949 typeParamList = nullptr;
952 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
954 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
957 // Clone the type parameter list.
958 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
959 for (auto typeParam : *prevTypeParamList) {
960 clonedTypeParams.push_back(
961 ObjCTypeParamDecl::Create(
964 typeParam->getVariance(),
966 typeParam->getIndex(),
968 typeParam->getIdentifier(),
970 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
973 typeParamList = ObjCTypeParamList::create(Context,
981 ObjCInterfaceDecl *IDecl
982 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
983 typeParamList, PrevIDecl, ClassLoc);
985 // Class already seen. Was it a definition?
986 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
987 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
988 << PrevIDecl->getDeclName();
989 Diag(Def->getLocation(), diag::note_previous_definition);
990 IDecl->setInvalidDecl();
995 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
996 PushOnScopeChains(IDecl, TUScope);
998 // Start the definition of this class. If we're in a redefinition case, there
999 // may already be a definition, so we'll end up adding to it.
1000 if (!IDecl->hasDefinition())
1001 IDecl->startDefinition();
1004 // Diagnose availability in the context of the @interface.
1005 ContextRAII SavedContext(*this, IDecl);
1007 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1008 ClassName, ClassLoc,
1009 SuperName, SuperLoc, SuperTypeArgs,
1010 SuperTypeArgsRange);
1011 } else { // we have a root class.
1012 IDecl->setEndOfDefinitionLoc(ClassLoc);
1015 // Check then save referenced protocols.
1017 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1018 NumProtoRefs, ProtoLocs);
1019 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1020 ProtoLocs, Context);
1021 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1024 CheckObjCDeclScope(IDecl);
1025 return ActOnObjCContainerStartDefinition(IDecl);
1028 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
1029 /// typedef'ed use for a qualified super class and adds them to the list
1030 /// of the protocols.
1031 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
1032 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1033 IdentifierInfo *SuperName,
1034 SourceLocation SuperLoc) {
1037 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1038 LookupOrdinaryName);
1042 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1043 QualType T = TDecl->getUnderlyingType();
1044 if (T->isObjCObjectType())
1045 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1046 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1047 // FIXME: Consider whether this should be an invalid loc since the loc
1048 // is not actually pointing to a protocol name reference but to the
1049 // typedef reference. Note that the base class name loc is also pointing
1051 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1056 /// ActOnCompatibilityAlias - this action is called after complete parsing of
1057 /// a \@compatibility_alias declaration. It sets up the alias relationships.
1058 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1059 IdentifierInfo *AliasName,
1060 SourceLocation AliasLocation,
1061 IdentifierInfo *ClassName,
1062 SourceLocation ClassLocation) {
1063 // Look for previous declaration of alias name
1064 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
1065 LookupOrdinaryName, ForRedeclaration);
1067 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1068 Diag(ADecl->getLocation(), diag::note_previous_declaration);
1071 // Check for class declaration
1072 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1073 LookupOrdinaryName, ForRedeclaration);
1074 if (const TypedefNameDecl *TDecl =
1075 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1076 QualType T = TDecl->getUnderlyingType();
1077 if (T->isObjCObjectType()) {
1078 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
1079 ClassName = IDecl->getIdentifier();
1080 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1081 LookupOrdinaryName, ForRedeclaration);
1085 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1087 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1089 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1093 // Everything checked out, instantiate a new alias declaration AST.
1094 ObjCCompatibleAliasDecl *AliasDecl =
1095 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
1097 if (!CheckObjCDeclScope(AliasDecl))
1098 PushOnScopeChains(AliasDecl, TUScope);
1103 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
1104 IdentifierInfo *PName,
1105 SourceLocation &Ploc, SourceLocation PrevLoc,
1106 const ObjCList<ObjCProtocolDecl> &PList) {
1109 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1110 E = PList.end(); I != E; ++I) {
1111 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1113 if (PDecl->getIdentifier() == PName) {
1114 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1115 Diag(PrevLoc, diag::note_previous_definition);
1119 if (!PDecl->hasDefinition())
1122 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1123 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1131 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1132 IdentifierInfo *ProtocolName,
1133 SourceLocation ProtocolLoc,
1134 Decl * const *ProtoRefs,
1135 unsigned NumProtoRefs,
1136 const SourceLocation *ProtoLocs,
1137 SourceLocation EndProtoLoc,
1138 AttributeList *AttrList) {
1140 // FIXME: Deal with AttrList.
1141 assert(ProtocolName && "Missing protocol identifier");
1142 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1144 ObjCProtocolDecl *PDecl = nullptr;
1145 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1146 // If we already have a definition, complain.
1147 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1148 Diag(Def->getLocation(), diag::note_previous_definition);
1150 // Create a new protocol that is completely distinct from previous
1151 // declarations, and do not make this protocol available for name lookup.
1152 // That way, we'll end up completely ignoring the duplicate.
1153 // FIXME: Can we turn this into an error?
1154 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1155 ProtocolLoc, AtProtoInterfaceLoc,
1156 /*PrevDecl=*/nullptr);
1157 PDecl->startDefinition();
1160 // Check for circular dependencies among protocol declarations. This can
1161 // only happen if this protocol was forward-declared.
1162 ObjCList<ObjCProtocolDecl> PList;
1163 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1164 err = CheckForwardProtocolDeclarationForCircularDependency(
1165 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1168 // Create the new declaration.
1169 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1170 ProtocolLoc, AtProtoInterfaceLoc,
1171 /*PrevDecl=*/PrevDecl);
1173 PushOnScopeChains(PDecl, TUScope);
1174 PDecl->startDefinition();
1178 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
1180 // Merge attributes from previous declarations.
1182 mergeDeclAttributes(PDecl, PrevDecl);
1184 if (!err && NumProtoRefs ) {
1185 /// Check then save referenced protocols.
1186 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1187 NumProtoRefs, ProtoLocs);
1188 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1189 ProtoLocs, Context);
1192 CheckObjCDeclScope(PDecl);
1193 return ActOnObjCContainerStartDefinition(PDecl);
1196 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1197 ObjCProtocolDecl *&UndefinedProtocol) {
1198 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1199 UndefinedProtocol = PDecl;
1203 for (auto *PI : PDecl->protocols())
1204 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1205 UndefinedProtocol = PI;
1211 /// FindProtocolDeclaration - This routine looks up protocols and
1212 /// issues an error if they are not declared. It returns list of
1213 /// protocol declarations in its 'Protocols' argument.
1215 Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
1216 ArrayRef<IdentifierLocPair> ProtocolId,
1217 SmallVectorImpl<Decl *> &Protocols) {
1218 for (const IdentifierLocPair &Pair : ProtocolId) {
1219 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1221 TypoCorrection Corrected = CorrectTypo(
1222 DeclarationNameInfo(Pair.first, Pair.second),
1223 LookupObjCProtocolName, TUScope, nullptr,
1224 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
1226 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1227 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1232 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1235 // If this is a forward protocol declaration, get its definition.
1236 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1237 PDecl = PDecl->getDefinition();
1239 // For an objc container, delay protocol reference checking until after we
1240 // can set the objc decl as the availability context, otherwise check now.
1241 if (!ForObjCContainer) {
1242 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
1245 // If this is a forward declaration and we are supposed to warn in this
1247 // FIXME: Recover nicely in the hidden case.
1248 ObjCProtocolDecl *UndefinedProtocol;
1250 if (WarnOnDeclarations &&
1251 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1252 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1253 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1254 << UndefinedProtocol;
1256 Protocols.push_back(PDecl);
1261 // Callback to only accept typo corrections that are either
1262 // Objective-C protocols or valid Objective-C type arguments.
1263 class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1264 ASTContext &Context;
1265 Sema::LookupNameKind LookupKind;
1267 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1268 Sema::LookupNameKind lookupKind)
1269 : Context(context), LookupKind(lookupKind) { }
1271 bool ValidateCandidate(const TypoCorrection &candidate) override {
1272 // If we're allowed to find protocols and we have a protocol, accept it.
1273 if (LookupKind != Sema::LookupOrdinaryName) {
1274 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1278 // If we're allowed to find type names and we have one, accept it.
1279 if (LookupKind != Sema::LookupObjCProtocolName) {
1280 // If we have a type declaration, we might accept this result.
1281 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1282 // If we found a tag declaration outside of C++, skip it. This
1283 // can happy because we look for any name when there is no
1284 // bias to protocol or type names.
1285 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1288 // Make sure the type is something we would accept as a type
1290 auto type = Context.getTypeDeclType(typeDecl);
1291 if (type->isObjCObjectPointerType() ||
1292 type->isBlockPointerType() ||
1293 type->isDependentType() ||
1294 type->isObjCObjectType())
1300 // If we have an Objective-C class type, accept it; there will
1301 // be another fix to add the '*'.
1302 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1311 } // end anonymous namespace
1313 void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1314 SourceLocation ProtocolLoc,
1315 IdentifierInfo *TypeArgId,
1316 SourceLocation TypeArgLoc,
1317 bool SelectProtocolFirst) {
1318 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1319 << SelectProtocolFirst << TypeArgId << ProtocolId
1320 << SourceRange(ProtocolLoc);
1323 void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1325 ParsedType baseType,
1326 SourceLocation lAngleLoc,
1327 ArrayRef<IdentifierInfo *> identifiers,
1328 ArrayRef<SourceLocation> identifierLocs,
1329 SourceLocation rAngleLoc,
1330 SourceLocation &typeArgsLAngleLoc,
1331 SmallVectorImpl<ParsedType> &typeArgs,
1332 SourceLocation &typeArgsRAngleLoc,
1333 SourceLocation &protocolLAngleLoc,
1334 SmallVectorImpl<Decl *> &protocols,
1335 SourceLocation &protocolRAngleLoc,
1336 bool warnOnIncompleteProtocols) {
1337 // Local function that updates the declaration specifiers with
1338 // protocol information.
1339 unsigned numProtocolsResolved = 0;
1340 auto resolvedAsProtocols = [&] {
1341 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1343 // Determine whether the base type is a parameterized class, in
1344 // which case we want to warn about typos such as
1345 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1346 ObjCInterfaceDecl *baseClass = nullptr;
1347 QualType base = GetTypeFromParser(baseType, nullptr);
1348 bool allAreTypeNames = false;
1349 SourceLocation firstClassNameLoc;
1350 if (!base.isNull()) {
1351 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1352 baseClass = objcObjectType->getInterface();
1354 if (auto typeParams = baseClass->getTypeParamList()) {
1355 if (typeParams->size() == numProtocolsResolved) {
1356 // Note that we should be looking for type names, too.
1357 allAreTypeNames = true;
1364 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1365 ObjCProtocolDecl *&proto
1366 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1367 // For an objc container, delay protocol reference checking until after we
1368 // can set the objc decl as the availability context, otherwise check now.
1369 if (!warnOnIncompleteProtocols) {
1370 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1373 // If this is a forward protocol declaration, get its definition.
1374 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1375 proto = proto->getDefinition();
1377 // If this is a forward declaration and we are supposed to warn in this
1379 // FIXME: Recover nicely in the hidden case.
1380 ObjCProtocolDecl *forwardDecl = nullptr;
1381 if (warnOnIncompleteProtocols &&
1382 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1383 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1384 << proto->getDeclName();
1385 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1389 // If everything this far has been a type name (and we care
1390 // about such things), check whether this name refers to a type
1392 if (allAreTypeNames) {
1393 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1394 LookupOrdinaryName)) {
1395 if (isa<ObjCInterfaceDecl>(decl)) {
1396 if (firstClassNameLoc.isInvalid())
1397 firstClassNameLoc = identifierLocs[i];
1398 } else if (!isa<TypeDecl>(decl)) {
1400 allAreTypeNames = false;
1403 allAreTypeNames = false;
1408 // All of the protocols listed also have type names, and at least
1409 // one is an Objective-C class name. Check whether all of the
1410 // protocol conformances are declared by the base class itself, in
1411 // which case we warn.
1412 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1413 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1414 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1415 bool allProtocolsDeclared = true;
1416 for (auto proto : protocols) {
1417 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1418 allProtocolsDeclared = false;
1423 if (allProtocolsDeclared) {
1424 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1425 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1426 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1431 protocolLAngleLoc = lAngleLoc;
1432 protocolRAngleLoc = rAngleLoc;
1433 assert(protocols.size() == identifierLocs.size());
1436 // Attempt to resolve all of the identifiers as protocols.
1437 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1438 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1439 protocols.push_back(proto);
1441 ++numProtocolsResolved;
1444 // If all of the names were protocols, these were protocol qualifiers.
1445 if (numProtocolsResolved == identifiers.size())
1446 return resolvedAsProtocols();
1448 // Attempt to resolve all of the identifiers as type names or
1449 // Objective-C class names. The latter is technically ill-formed,
1450 // but is probably something like \c NSArray<NSView *> missing the
1452 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1453 SmallVector<TypeOrClassDecl, 4> typeDecls;
1454 unsigned numTypeDeclsResolved = 0;
1455 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1456 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1457 LookupOrdinaryName);
1459 typeDecls.push_back(TypeOrClassDecl());
1463 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1464 typeDecls.push_back(typeDecl);
1465 ++numTypeDeclsResolved;
1469 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1470 typeDecls.push_back(objcClass);
1471 ++numTypeDeclsResolved;
1475 typeDecls.push_back(TypeOrClassDecl());
1478 AttributeFactory attrFactory;
1480 // Local function that forms a reference to the given type or
1481 // Objective-C class declaration.
1482 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1484 // Form declaration specifiers. They simply refer to the type.
1485 DeclSpec DS(attrFactory);
1486 const char* prevSpec; // unused
1487 unsigned diagID; // unused
1489 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1490 type = Context.getTypeDeclType(actualTypeDecl);
1492 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1493 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1494 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1495 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1496 parsedType, Context.getPrintingPolicy());
1497 // Use the identifier location for the type source range.
1498 DS.SetRangeStart(loc);
1499 DS.SetRangeEnd(loc);
1501 // Form the declarator.
1502 Declarator D(DS, Declarator::TypeNameContext);
1504 // If we have a typedef of an Objective-C class type that is missing a '*',
1506 if (type->getAs<ObjCInterfaceType>()) {
1507 SourceLocation starLoc = getLocForEndOfToken(loc);
1508 ParsedAttributes parsedAttrs(attrFactory);
1509 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1518 // Diagnose the missing '*'.
1519 Diag(loc, diag::err_objc_type_arg_missing_star)
1521 << FixItHint::CreateInsertion(starLoc, " *");
1524 // Convert this to a type.
1525 return ActOnTypeName(S, D);
1528 // Local function that updates the declaration specifiers with
1529 // type argument information.
1530 auto resolvedAsTypeDecls = [&] {
1531 // We did not resolve these as protocols.
1534 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1535 // Map type declarations to type arguments.
1536 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1537 // Map type reference to a type.
1538 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1539 if (!type.isUsable()) {
1544 typeArgs.push_back(type.get());
1547 typeArgsLAngleLoc = lAngleLoc;
1548 typeArgsRAngleLoc = rAngleLoc;
1551 // If all of the identifiers can be resolved as type names or
1552 // Objective-C class names, we have type arguments.
1553 if (numTypeDeclsResolved == identifiers.size())
1554 return resolvedAsTypeDecls();
1556 // Error recovery: some names weren't found, or we have a mix of
1557 // type and protocol names. Go resolve all of the unresolved names
1558 // and complain if we can't find a consistent answer.
1559 LookupNameKind lookupKind = LookupAnyName;
1560 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1561 // If we already have a protocol or type. Check whether it is the
1563 if (protocols[i] || typeDecls[i]) {
1564 // If we haven't figured out whether we want types or protocols
1565 // yet, try to figure it out from this name.
1566 if (lookupKind == LookupAnyName) {
1567 // If this name refers to both a protocol and a type (e.g., \c
1568 // NSObject), don't conclude anything yet.
1569 if (protocols[i] && typeDecls[i])
1572 // Otherwise, let this name decide whether we'll be correcting
1573 // toward types or protocols.
1574 lookupKind = protocols[i] ? LookupObjCProtocolName
1575 : LookupOrdinaryName;
1579 // If we want protocols and we have a protocol, there's nothing
1581 if (lookupKind == LookupObjCProtocolName && protocols[i])
1584 // If we want types and we have a type declaration, there's
1585 // nothing more to do.
1586 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1589 // We have a conflict: some names refer to protocols and others
1591 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1592 identifiers[i], identifierLocs[i],
1593 protocols[i] != nullptr);
1600 // Perform typo correction on the name.
1601 TypoCorrection corrected = CorrectTypo(
1602 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1604 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1608 // Did we find a protocol?
1609 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1610 diagnoseTypo(corrected,
1611 PDiag(diag::err_undeclared_protocol_suggest)
1613 lookupKind = LookupObjCProtocolName;
1614 protocols[i] = proto;
1615 ++numProtocolsResolved;
1619 // Did we find a type?
1620 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1621 diagnoseTypo(corrected,
1622 PDiag(diag::err_unknown_typename_suggest)
1624 lookupKind = LookupOrdinaryName;
1625 typeDecls[i] = typeDecl;
1626 ++numTypeDeclsResolved;
1630 // Did we find an Objective-C class?
1631 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1632 diagnoseTypo(corrected,
1633 PDiag(diag::err_unknown_type_or_class_name_suggest)
1634 << identifiers[i] << true);
1635 lookupKind = LookupOrdinaryName;
1636 typeDecls[i] = objcClass;
1637 ++numTypeDeclsResolved;
1642 // We couldn't find anything.
1643 Diag(identifierLocs[i],
1644 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1645 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1646 : diag::err_unknown_typename))
1653 // If all of the names were (corrected to) protocols, these were
1654 // protocol qualifiers.
1655 if (numProtocolsResolved == identifiers.size())
1656 return resolvedAsProtocols();
1658 // Otherwise, all of the names were (corrected to) types.
1659 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1660 return resolvedAsTypeDecls();
1663 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1664 /// a class method in its extension.
1666 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
1667 ObjCInterfaceDecl *ID) {
1669 return; // Possibly due to previous error
1671 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1672 for (auto *MD : ID->methods())
1673 MethodMap[MD->getSelector()] = MD;
1675 if (MethodMap.empty())
1677 for (const auto *Method : CAT->methods()) {
1678 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1680 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1681 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1682 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1683 << Method->getDeclName();
1684 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1689 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1690 Sema::DeclGroupPtrTy
1691 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
1692 ArrayRef<IdentifierLocPair> IdentList,
1693 AttributeList *attrList) {
1694 SmallVector<Decl *, 8> DeclsInGroup;
1695 for (const IdentifierLocPair &IdentPair : IdentList) {
1696 IdentifierInfo *Ident = IdentPair.first;
1697 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
1699 ObjCProtocolDecl *PDecl
1700 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
1701 IdentPair.second, AtProtocolLoc,
1704 PushOnScopeChains(PDecl, TUScope);
1705 CheckObjCDeclScope(PDecl);
1708 ProcessDeclAttributeList(TUScope, PDecl, attrList);
1711 mergeDeclAttributes(PDecl, PrevDecl);
1713 DeclsInGroup.push_back(PDecl);
1716 return BuildDeclaratorGroup(DeclsInGroup);
1720 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1721 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1722 ObjCTypeParamList *typeParamList,
1723 IdentifierInfo *CategoryName,
1724 SourceLocation CategoryLoc,
1725 Decl * const *ProtoRefs,
1726 unsigned NumProtoRefs,
1727 const SourceLocation *ProtoLocs,
1728 SourceLocation EndProtoLoc,
1729 AttributeList *AttrList) {
1730 ObjCCategoryDecl *CDecl;
1731 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1733 /// Check that class of this category is already completely declared.
1736 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1737 diag::err_category_forward_interface,
1738 CategoryName == nullptr)) {
1739 // Create an invalid ObjCCategoryDecl to serve as context for
1740 // the enclosing method declarations. We mark the decl invalid
1741 // to make it clear that this isn't a valid AST.
1742 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1743 ClassLoc, CategoryLoc, CategoryName,
1744 IDecl, typeParamList);
1745 CDecl->setInvalidDecl();
1746 CurContext->addDecl(CDecl);
1749 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1750 return ActOnObjCContainerStartDefinition(CDecl);
1753 if (!CategoryName && IDecl->getImplementation()) {
1754 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1755 Diag(IDecl->getImplementation()->getLocation(),
1756 diag::note_implementation_declared);
1760 /// Check for duplicate interface declaration for this category
1761 if (ObjCCategoryDecl *Previous
1762 = IDecl->FindCategoryDeclaration(CategoryName)) {
1763 // Class extensions can be declared multiple times, categories cannot.
1764 Diag(CategoryLoc, diag::warn_dup_category_def)
1765 << ClassName << CategoryName;
1766 Diag(Previous->getLocation(), diag::note_previous_definition);
1770 // If we have a type parameter list, check it.
1771 if (typeParamList) {
1772 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1773 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1775 ? TypeParamListContext::Category
1776 : TypeParamListContext::Extension))
1777 typeParamList = nullptr;
1779 Diag(typeParamList->getLAngleLoc(),
1780 diag::err_objc_parameterized_category_nonclass)
1781 << (CategoryName != nullptr)
1783 << typeParamList->getSourceRange();
1785 typeParamList = nullptr;
1789 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1790 ClassLoc, CategoryLoc, CategoryName, IDecl,
1792 // FIXME: PushOnScopeChains?
1793 CurContext->addDecl(CDecl);
1796 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1797 NumProtoRefs, ProtoLocs);
1798 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1799 ProtoLocs, Context);
1800 // Protocols in the class extension belong to the class.
1801 if (CDecl->IsClassExtension())
1802 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1803 NumProtoRefs, Context);
1807 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1809 CheckObjCDeclScope(CDecl);
1810 return ActOnObjCContainerStartDefinition(CDecl);
1813 /// ActOnStartCategoryImplementation - Perform semantic checks on the
1814 /// category implementation declaration and build an ObjCCategoryImplDecl
1816 Decl *Sema::ActOnStartCategoryImplementation(
1817 SourceLocation AtCatImplLoc,
1818 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1819 IdentifierInfo *CatName, SourceLocation CatLoc) {
1820 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1821 ObjCCategoryDecl *CatIDecl = nullptr;
1822 if (IDecl && IDecl->hasDefinition()) {
1823 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1825 // Category @implementation with no corresponding @interface.
1826 // Create and install one.
1827 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1830 /*typeParamList=*/nullptr);
1831 CatIDecl->setImplicit();
1835 ObjCCategoryImplDecl *CDecl =
1836 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
1837 ClassLoc, AtCatImplLoc, CatLoc);
1838 /// Check that class of this category is already completely declared.
1840 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1841 CDecl->setInvalidDecl();
1842 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1843 diag::err_undef_interface)) {
1844 CDecl->setInvalidDecl();
1847 // FIXME: PushOnScopeChains?
1848 CurContext->addDecl(CDecl);
1850 // If the interface is deprecated/unavailable, warn/error about it.
1852 DiagnoseUseOfDecl(IDecl, ClassLoc);
1854 // If the interface has the objc_runtime_visible attribute, we
1855 // cannot implement a category for it.
1856 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1857 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1858 << IDecl->getDeclName();
1861 /// Check that CatName, category name, is not used in another implementation.
1863 if (CatIDecl->getImplementation()) {
1864 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1866 Diag(CatIDecl->getImplementation()->getLocation(),
1867 diag::note_previous_definition);
1868 CDecl->setInvalidDecl();
1870 CatIDecl->setImplementation(CDecl);
1871 // Warn on implementating category of deprecated class under
1872 // -Wdeprecated-implementations flag.
1873 DiagnoseObjCImplementedDeprecations(
1875 CatIDecl->isDeprecated() ? CatIDecl : dyn_cast<NamedDecl>(IDecl),
1876 CDecl->getLocation(), 2);
1880 CheckObjCDeclScope(CDecl);
1881 return ActOnObjCContainerStartDefinition(CDecl);
1884 Decl *Sema::ActOnStartClassImplementation(
1885 SourceLocation AtClassImplLoc,
1886 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1887 IdentifierInfo *SuperClassname,
1888 SourceLocation SuperClassLoc) {
1889 ObjCInterfaceDecl *IDecl = nullptr;
1890 // Check for another declaration kind with the same name.
1892 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1894 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1895 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1896 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1897 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1898 // FIXME: This will produce an error if the definition of the interface has
1899 // been imported from a module but is not visible.
1900 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1901 diag::warn_undef_interface);
1903 // We did not find anything with the name ClassName; try to correct for
1904 // typos in the class name.
1905 TypoCorrection Corrected = CorrectTypo(
1906 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1907 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
1908 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1909 // Suggest the (potentially) correct interface name. Don't provide a
1910 // code-modification hint or use the typo name for recovery, because
1911 // this is just a warning. The program may actually be correct.
1912 diagnoseTypo(Corrected,
1913 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1914 /*ErrorRecovery*/false);
1916 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1920 // Check that super class name is valid class name
1921 ObjCInterfaceDecl *SDecl = nullptr;
1922 if (SuperClassname) {
1923 // Check if a different kind of symbol declared in this scope.
1924 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1925 LookupOrdinaryName);
1926 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1927 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1929 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1931 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1932 if (SDecl && !SDecl->hasDefinition())
1935 Diag(SuperClassLoc, diag::err_undef_superclass)
1936 << SuperClassname << ClassName;
1937 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1938 // This implementation and its interface do not have the same
1940 Diag(SuperClassLoc, diag::err_conflicting_super_class)
1941 << SDecl->getDeclName();
1942 Diag(SDecl->getLocation(), diag::note_previous_definition);
1948 // Legacy case of @implementation with no corresponding @interface.
1949 // Build, chain & install the interface decl into the identifier.
1951 // FIXME: Do we support attributes on the @implementation? If so we should
1953 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1954 ClassName, /*typeParamList=*/nullptr,
1955 /*PrevDecl=*/nullptr, ClassLoc,
1957 IDecl->startDefinition();
1959 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
1960 Context.getObjCInterfaceType(SDecl),
1962 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1964 IDecl->setEndOfDefinitionLoc(ClassLoc);
1967 PushOnScopeChains(IDecl, TUScope);
1969 // Mark the interface as being completed, even if it was just as
1971 // declaration; the user cannot reopen it.
1972 if (!IDecl->hasDefinition())
1973 IDecl->startDefinition();
1976 ObjCImplementationDecl* IMPDecl =
1977 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1978 ClassLoc, AtClassImplLoc, SuperClassLoc);
1980 if (CheckObjCDeclScope(IMPDecl))
1981 return ActOnObjCContainerStartDefinition(IMPDecl);
1983 // Check that there is no duplicate implementation of this class.
1984 if (IDecl->getImplementation()) {
1985 // FIXME: Don't leak everything!
1986 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1987 Diag(IDecl->getImplementation()->getLocation(),
1988 diag::note_previous_definition);
1989 IMPDecl->setInvalidDecl();
1990 } else { // add it to the list.
1991 IDecl->setImplementation(IMPDecl);
1992 PushOnScopeChains(IMPDecl, TUScope);
1993 // Warn on implementating deprecated class under
1994 // -Wdeprecated-implementations flag.
1995 DiagnoseObjCImplementedDeprecations(*this,
1996 dyn_cast<NamedDecl>(IDecl),
1997 IMPDecl->getLocation(), 1);
2000 // If the superclass has the objc_runtime_visible attribute, we
2001 // cannot implement a subclass of it.
2002 if (IDecl->getSuperClass() &&
2003 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2004 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2005 << IDecl->getDeclName()
2006 << IDecl->getSuperClass()->getDeclName();
2009 return ActOnObjCContainerStartDefinition(IMPDecl);
2012 Sema::DeclGroupPtrTy
2013 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2014 SmallVector<Decl *, 64> DeclsInGroup;
2015 DeclsInGroup.reserve(Decls.size() + 1);
2017 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2018 Decl *Dcl = Decls[i];
2021 if (Dcl->getDeclContext()->isFileContext())
2022 Dcl->setTopLevelDeclInObjCContainer();
2023 DeclsInGroup.push_back(Dcl);
2026 DeclsInGroup.push_back(ObjCImpDecl);
2028 return BuildDeclaratorGroup(DeclsInGroup);
2031 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2032 ObjCIvarDecl **ivars, unsigned numIvars,
2033 SourceLocation RBrace) {
2034 assert(ImpDecl && "missing implementation decl");
2035 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2038 /// Check case of non-existing \@interface decl.
2039 /// (legacy objective-c \@implementation decl without an \@interface decl).
2040 /// Add implementations's ivar to the synthesize class's ivar list.
2041 if (IDecl->isImplicitInterfaceDecl()) {
2042 IDecl->setEndOfDefinitionLoc(RBrace);
2043 // Add ivar's to class's DeclContext.
2044 for (unsigned i = 0, e = numIvars; i != e; ++i) {
2045 ivars[i]->setLexicalDeclContext(ImpDecl);
2046 IDecl->makeDeclVisibleInContext(ivars[i]);
2047 ImpDecl->addDecl(ivars[i]);
2052 // If implementation has empty ivar list, just return.
2056 assert(ivars && "missing @implementation ivars");
2057 if (LangOpts.ObjCRuntime.isNonFragile()) {
2058 if (ImpDecl->getSuperClass())
2059 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2060 for (unsigned i = 0; i < numIvars; i++) {
2061 ObjCIvarDecl* ImplIvar = ivars[i];
2062 if (const ObjCIvarDecl *ClsIvar =
2063 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2064 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2065 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2068 // Check class extensions (unnamed categories) for duplicate ivars.
2069 for (const auto *CDecl : IDecl->visible_extensions()) {
2070 if (const ObjCIvarDecl *ClsExtIvar =
2071 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2072 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2073 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2077 // Instance ivar to Implementation's DeclContext.
2078 ImplIvar->setLexicalDeclContext(ImpDecl);
2079 IDecl->makeDeclVisibleInContext(ImplIvar);
2080 ImpDecl->addDecl(ImplIvar);
2084 // Check interface's Ivar list against those in the implementation.
2085 // names and types must match.
2088 ObjCInterfaceDecl::ivar_iterator
2089 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2090 for (; numIvars > 0 && IVI != IVE; ++IVI) {
2091 ObjCIvarDecl* ImplIvar = ivars[j++];
2092 ObjCIvarDecl* ClsIvar = *IVI;
2093 assert (ImplIvar && "missing implementation ivar");
2094 assert (ClsIvar && "missing class ivar");
2096 // First, make sure the types match.
2097 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2098 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2099 << ImplIvar->getIdentifier()
2100 << ImplIvar->getType() << ClsIvar->getType();
2101 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2102 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2103 ImplIvar->getBitWidthValue(Context) !=
2104 ClsIvar->getBitWidthValue(Context)) {
2105 Diag(ImplIvar->getBitWidth()->getLocStart(),
2106 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2107 Diag(ClsIvar->getBitWidth()->getLocStart(),
2108 diag::note_previous_definition);
2110 // Make sure the names are identical.
2111 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2112 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2113 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2114 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2120 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2121 else if (IVI != IVE)
2122 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2125 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2126 ObjCMethodDecl *method,
2127 bool &IncompleteImpl,
2129 NamedDecl *NeededFor = nullptr) {
2130 // No point warning no definition of method which is 'unavailable'.
2131 switch (method->getAvailability()) {
2136 // Don't warn about unavailable or not-yet-introduced methods.
2137 case AR_NotYetIntroduced:
2138 case AR_Unavailable:
2142 // FIXME: For now ignore 'IncompleteImpl'.
2143 // Previously we grouped all unimplemented methods under a single
2144 // warning, but some users strongly voiced that they would prefer
2145 // separate warnings. We will give that approach a try, as that
2146 // matches what we do with protocols.
2148 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2154 // Issue a note to the original declaration.
2155 SourceLocation MethodLoc = method->getLocStart();
2156 if (MethodLoc.isValid())
2157 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2160 /// Determines if type B can be substituted for type A. Returns true if we can
2161 /// guarantee that anything that the user will do to an object of type A can
2162 /// also be done to an object of type B. This is trivially true if the two
2163 /// types are the same, or if B is a subclass of A. It becomes more complex
2164 /// in cases where protocols are involved.
2166 /// Object types in Objective-C describe the minimum requirements for an
2167 /// object, rather than providing a complete description of a type. For
2168 /// example, if A is a subclass of B, then B* may refer to an instance of A.
2169 /// The principle of substitutability means that we may use an instance of A
2170 /// anywhere that we may use an instance of B - it will implement all of the
2171 /// ivars of B and all of the methods of B.
2173 /// This substitutability is important when type checking methods, because
2174 /// the implementation may have stricter type definitions than the interface.
2175 /// The interface specifies minimum requirements, but the implementation may
2176 /// have more accurate ones. For example, a method may privately accept
2177 /// instances of B, but only publish that it accepts instances of A. Any
2178 /// object passed to it will be type checked against B, and so will implicitly
2179 /// by a valid A*. Similarly, a method may return a subclass of the class that
2180 /// it is declared as returning.
2182 /// This is most important when considering subclassing. A method in a
2183 /// subclass must accept any object as an argument that its superclass's
2184 /// implementation accepts. It may, however, accept a more general type
2185 /// without breaking substitutability (i.e. you can still use the subclass
2186 /// anywhere that you can use the superclass, but not vice versa). The
2187 /// converse requirement applies to return types: the return type for a
2188 /// subclass method must be a valid object of the kind that the superclass
2189 /// advertises, but it may be specified more accurately. This avoids the need
2190 /// for explicit down-casting by callers.
2192 /// Note: This is a stricter requirement than for assignment.
2193 static bool isObjCTypeSubstitutable(ASTContext &Context,
2194 const ObjCObjectPointerType *A,
2195 const ObjCObjectPointerType *B,
2197 // Reject a protocol-unqualified id.
2198 if (rejectId && B->isObjCIdType()) return false;
2200 // If B is a qualified id, then A must also be a qualified id and it must
2201 // implement all of the protocols in B. It may not be a qualified class.
2202 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2203 // stricter definition so it is not substitutable for id<A>.
2204 if (B->isObjCQualifiedIdType()) {
2205 return A->isObjCQualifiedIdType() &&
2206 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2212 // id is a special type that bypasses type checking completely. We want a
2213 // warning when it is used in one place but not another.
2214 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2217 // If B is a qualified id, then A must also be a qualified id (which it isn't
2218 // if we've got this far)
2219 if (B->isObjCQualifiedIdType()) return false;
2222 // Now we know that A and B are (potentially-qualified) class types. The
2223 // normal rules for assignment apply.
2224 return Context.canAssignObjCInterfaces(A, B);
2227 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2228 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2231 /// Determine whether two set of Objective-C declaration qualifiers conflict.
2232 static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2233 Decl::ObjCDeclQualifier y) {
2234 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2235 (y & ~Decl::OBJC_TQ_CSNullability);
2238 static bool CheckMethodOverrideReturn(Sema &S,
2239 ObjCMethodDecl *MethodImpl,
2240 ObjCMethodDecl *MethodDecl,
2241 bool IsProtocolMethodDecl,
2242 bool IsOverridingMode,
2244 if (IsProtocolMethodDecl &&
2245 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2246 MethodImpl->getObjCDeclQualifier())) {
2248 S.Diag(MethodImpl->getLocation(),
2250 ? diag::warn_conflicting_overriding_ret_type_modifiers
2251 : diag::warn_conflicting_ret_type_modifiers))
2252 << MethodImpl->getDeclName()
2253 << MethodImpl->getReturnTypeSourceRange();
2254 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2255 << MethodDecl->getReturnTypeSourceRange();
2260 if (Warn && IsOverridingMode &&
2261 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2262 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2263 MethodDecl->getReturnType(),
2265 auto nullabilityMethodImpl =
2266 *MethodImpl->getReturnType()->getNullability(S.Context);
2267 auto nullabilityMethodDecl =
2268 *MethodDecl->getReturnType()->getNullability(S.Context);
2269 S.Diag(MethodImpl->getLocation(),
2270 diag::warn_conflicting_nullability_attr_overriding_ret_types)
2271 << DiagNullabilityKind(
2272 nullabilityMethodImpl,
2273 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2275 << DiagNullabilityKind(
2276 nullabilityMethodDecl,
2277 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2279 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2282 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2283 MethodDecl->getReturnType()))
2289 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2290 : diag::warn_conflicting_ret_types;
2292 // Mismatches between ObjC pointers go into a different warning
2293 // category, and sometimes they're even completely whitelisted.
2294 if (const ObjCObjectPointerType *ImplPtrTy =
2295 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2296 if (const ObjCObjectPointerType *IfacePtrTy =
2297 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2298 // Allow non-matching return types as long as they don't violate
2299 // the principle of substitutability. Specifically, we permit
2300 // return types that are subclasses of the declared return type,
2301 // or that are more-qualified versions of the declared type.
2302 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2306 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2307 : diag::warn_non_covariant_ret_types;
2311 S.Diag(MethodImpl->getLocation(), DiagID)
2312 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2313 << MethodImpl->getReturnType()
2314 << MethodImpl->getReturnTypeSourceRange();
2315 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2316 ? diag::note_previous_declaration
2317 : diag::note_previous_definition)
2318 << MethodDecl->getReturnTypeSourceRange();
2322 static bool CheckMethodOverrideParam(Sema &S,
2323 ObjCMethodDecl *MethodImpl,
2324 ObjCMethodDecl *MethodDecl,
2325 ParmVarDecl *ImplVar,
2326 ParmVarDecl *IfaceVar,
2327 bool IsProtocolMethodDecl,
2328 bool IsOverridingMode,
2330 if (IsProtocolMethodDecl &&
2331 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2332 IfaceVar->getObjCDeclQualifier())) {
2334 if (IsOverridingMode)
2335 S.Diag(ImplVar->getLocation(),
2336 diag::warn_conflicting_overriding_param_modifiers)
2337 << getTypeRange(ImplVar->getTypeSourceInfo())
2338 << MethodImpl->getDeclName();
2339 else S.Diag(ImplVar->getLocation(),
2340 diag::warn_conflicting_param_modifiers)
2341 << getTypeRange(ImplVar->getTypeSourceInfo())
2342 << MethodImpl->getDeclName();
2343 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2344 << getTypeRange(IfaceVar->getTypeSourceInfo());
2350 QualType ImplTy = ImplVar->getType();
2351 QualType IfaceTy = IfaceVar->getType();
2352 if (Warn && IsOverridingMode &&
2353 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2354 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2355 S.Diag(ImplVar->getLocation(),
2356 diag::warn_conflicting_nullability_attr_overriding_param_types)
2357 << DiagNullabilityKind(
2358 *ImplTy->getNullability(S.Context),
2359 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2361 << DiagNullabilityKind(
2362 *IfaceTy->getNullability(S.Context),
2363 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2365 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2367 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2373 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2374 : diag::warn_conflicting_param_types;
2376 // Mismatches between ObjC pointers go into a different warning
2377 // category, and sometimes they're even completely whitelisted.
2378 if (const ObjCObjectPointerType *ImplPtrTy =
2379 ImplTy->getAs<ObjCObjectPointerType>()) {
2380 if (const ObjCObjectPointerType *IfacePtrTy =
2381 IfaceTy->getAs<ObjCObjectPointerType>()) {
2382 // Allow non-matching argument types as long as they don't
2383 // violate the principle of substitutability. Specifically, the
2384 // implementation must accept any objects that the superclass
2385 // accepts, however it may also accept others.
2386 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2390 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2391 : diag::warn_non_contravariant_param_types;
2395 S.Diag(ImplVar->getLocation(), DiagID)
2396 << getTypeRange(ImplVar->getTypeSourceInfo())
2397 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2398 S.Diag(IfaceVar->getLocation(),
2399 (IsOverridingMode ? diag::note_previous_declaration
2400 : diag::note_previous_definition))
2401 << getTypeRange(IfaceVar->getTypeSourceInfo());
2405 /// In ARC, check whether the conventional meanings of the two methods
2406 /// match. If they don't, it's a hard error.
2407 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2408 ObjCMethodDecl *decl) {
2409 ObjCMethodFamily implFamily = impl->getMethodFamily();
2410 ObjCMethodFamily declFamily = decl->getMethodFamily();
2411 if (implFamily == declFamily) return false;
2413 // Since conventions are sorted by selector, the only possibility is
2414 // that the types differ enough to cause one selector or the other
2415 // to fall out of the family.
2416 assert(implFamily == OMF_None || declFamily == OMF_None);
2418 // No further diagnostics required on invalid declarations.
2419 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2421 const ObjCMethodDecl *unmatched = impl;
2422 ObjCMethodFamily family = declFamily;
2423 unsigned errorID = diag::err_arc_lost_method_convention;
2424 unsigned noteID = diag::note_arc_lost_method_convention;
2425 if (declFamily == OMF_None) {
2427 family = implFamily;
2428 errorID = diag::err_arc_gained_method_convention;
2429 noteID = diag::note_arc_gained_method_convention;
2432 // Indexes into a %select clause in the diagnostic.
2433 enum FamilySelector {
2434 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2436 FamilySelector familySelector = FamilySelector();
2439 case OMF_None: llvm_unreachable("logic error, no method convention");
2442 case OMF_autorelease:
2445 case OMF_retainCount:
2447 case OMF_initialize:
2448 case OMF_performSelector:
2449 // Mismatches for these methods don't change ownership
2450 // conventions, so we don't care.
2453 case OMF_init: familySelector = F_init; break;
2454 case OMF_alloc: familySelector = F_alloc; break;
2455 case OMF_copy: familySelector = F_copy; break;
2456 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2457 case OMF_new: familySelector = F_new; break;
2460 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2461 ReasonSelector reasonSelector;
2463 // The only reason these methods don't fall within their families is
2464 // due to unusual result types.
2465 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2466 reasonSelector = R_UnrelatedReturn;
2468 reasonSelector = R_NonObjectReturn;
2471 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2472 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2477 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2478 ObjCMethodDecl *MethodDecl,
2479 bool IsProtocolMethodDecl) {
2480 if (getLangOpts().ObjCAutoRefCount &&
2481 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2484 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2485 IsProtocolMethodDecl, false,
2488 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2489 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2490 EF = MethodDecl->param_end();
2491 IM != EM && IF != EF; ++IM, ++IF) {
2492 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2493 IsProtocolMethodDecl, false, true);
2496 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2497 Diag(ImpMethodDecl->getLocation(),
2498 diag::warn_conflicting_variadic);
2499 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2503 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2504 ObjCMethodDecl *Overridden,
2505 bool IsProtocolMethodDecl) {
2507 CheckMethodOverrideReturn(*this, Method, Overridden,
2508 IsProtocolMethodDecl, true,
2511 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
2512 IF = Overridden->param_begin(), EM = Method->param_end(),
2513 EF = Overridden->param_end();
2514 IM != EM && IF != EF; ++IM, ++IF) {
2515 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2516 IsProtocolMethodDecl, true, true);
2519 if (Method->isVariadic() != Overridden->isVariadic()) {
2520 Diag(Method->getLocation(),
2521 diag::warn_conflicting_overriding_variadic);
2522 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2526 /// WarnExactTypedMethods - This routine issues a warning if method
2527 /// implementation declaration matches exactly that of its declaration.
2528 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2529 ObjCMethodDecl *MethodDecl,
2530 bool IsProtocolMethodDecl) {
2531 // don't issue warning when protocol method is optional because primary
2532 // class is not required to implement it and it is safe for protocol
2534 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2536 // don't issue warning when primary class's method is
2537 // depecated/unavailable.
2538 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2539 MethodDecl->hasAttr<DeprecatedAttr>())
2542 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2543 IsProtocolMethodDecl, false, false);
2545 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2546 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2547 EF = MethodDecl->param_end();
2548 IM != EM && IF != EF; ++IM, ++IF) {
2549 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2551 IsProtocolMethodDecl, false, false);
2556 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
2558 match = !(MethodDecl->isClassMethod() &&
2559 MethodDecl->getSelector() == GetNullarySelector("load", Context));
2562 Diag(ImpMethodDecl->getLocation(),
2563 diag::warn_category_method_impl_match);
2564 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2565 << MethodDecl->getDeclName();
2569 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2570 /// improve the efficiency of selector lookups and type checking by associating
2571 /// with each protocol / interface / category the flattened instance tables. If
2572 /// we used an immutable set to keep the table then it wouldn't add significant
2573 /// memory cost and it would be handy for lookups.
2575 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
2576 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
2578 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2579 ProtocolNameSet &PNS) {
2580 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2581 PNS.insert(PDecl->getIdentifier());
2582 for (const auto *PI : PDecl->protocols())
2583 findProtocolsWithExplicitImpls(PI, PNS);
2586 /// Recursively populates a set with all conformed protocols in a class
2587 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2589 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2590 ProtocolNameSet &PNS) {
2594 for (const auto *I : Super->all_referenced_protocols())
2595 findProtocolsWithExplicitImpls(I, PNS);
2597 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
2600 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
2601 /// Declared in protocol, and those referenced by it.
2602 static void CheckProtocolMethodDefs(Sema &S,
2603 SourceLocation ImpLoc,
2604 ObjCProtocolDecl *PDecl,
2605 bool& IncompleteImpl,
2606 const Sema::SelectorSet &InsMap,
2607 const Sema::SelectorSet &ClsMap,
2608 ObjCContainerDecl *CDecl,
2609 LazyProtocolNameSet &ProtocolsExplictImpl) {
2610 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2611 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2612 : dyn_cast<ObjCInterfaceDecl>(CDecl);
2613 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2615 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
2616 ObjCInterfaceDecl *NSIDecl = nullptr;
2618 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2619 // then we should check if any class in the super class hierarchy also
2620 // conforms to this protocol, either directly or via protocol inheritance.
2621 // If so, we can skip checking this protocol completely because we
2622 // know that a parent class already satisfies this protocol.
2624 // Note: we could generalize this logic for all protocols, and merely
2625 // add the limit on looking at the super class chain for just
2626 // specially marked protocols. This may be a good optimization. This
2627 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2628 // protocols for now for controlled evaluation.
2629 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
2630 if (!ProtocolsExplictImpl) {
2631 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2632 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2634 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2635 ProtocolsExplictImpl->end())
2638 // If no super class conforms to the protocol, we should not search
2639 // for methods in the super class to implicitly satisfy the protocol.
2643 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
2644 // check to see if class implements forwardInvocation method and objects
2645 // of this class are derived from 'NSProxy' so that to forward requests
2646 // from one object to another.
2647 // Under such conditions, which means that every method possible is
2648 // implemented in the class, we should not issue "Method definition not
2650 // FIXME: Use a general GetUnarySelector method for this.
2651 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2652 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
2653 if (InsMap.count(fISelector))
2654 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2655 // need be implemented in the implementation.
2656 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
2659 // If this is a forward protocol declaration, get its definition.
2660 if (!PDecl->isThisDeclarationADefinition() &&
2661 PDecl->getDefinition())
2662 PDecl = PDecl->getDefinition();
2664 // If a method lookup fails locally we still need to look and see if
2665 // the method was implemented by a base class or an inherited
2666 // protocol. This lookup is slow, but occurs rarely in correct code
2667 // and otherwise would terminate in a warning.
2669 // check unimplemented instance methods.
2671 for (auto *method : PDecl->instance_methods()) {
2672 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2673 !method->isPropertyAccessor() &&
2674 !InsMap.count(method->getSelector()) &&
2675 (!Super || !Super->lookupMethod(method->getSelector(),
2676 true /* instance */,
2677 false /* shallowCategory */,
2678 true /* followsSuper */,
2679 nullptr /* category */))) {
2680 // If a method is not implemented in the category implementation but
2681 // has been declared in its primary class, superclass,
2682 // or in one of their protocols, no need to issue the warning.
2683 // This is because method will be implemented in the primary class
2684 // or one of its super class implementation.
2686 // Ugly, but necessary. Method declared in protcol might have
2687 // have been synthesized due to a property declared in the class which
2688 // uses the protocol.
2689 if (ObjCMethodDecl *MethodInClass =
2690 IDecl->lookupMethod(method->getSelector(),
2691 true /* instance */,
2692 true /* shallowCategoryLookup */,
2693 false /* followSuper */))
2694 if (C || MethodInClass->isPropertyAccessor())
2696 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2697 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2698 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
2703 // check unimplemented class methods
2704 for (auto *method : PDecl->class_methods()) {
2705 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2706 !ClsMap.count(method->getSelector()) &&
2707 (!Super || !Super->lookupMethod(method->getSelector(),
2708 false /* class method */,
2709 false /* shallowCategoryLookup */,
2710 true /* followSuper */,
2711 nullptr /* category */))) {
2712 // See above comment for instance method lookups.
2713 if (C && IDecl->lookupMethod(method->getSelector(),
2715 true /* shallowCategoryLookup */,
2716 false /* followSuper */))
2719 unsigned DIAG = diag::warn_unimplemented_protocol_method;
2720 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
2721 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
2725 // Check on this protocols's referenced protocols, recursively.
2726 for (auto *PI : PDecl->protocols())
2727 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
2728 CDecl, ProtocolsExplictImpl);
2731 /// MatchAllMethodDeclarations - Check methods declared in interface
2732 /// or protocol against those declared in their implementations.
2734 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2735 const SelectorSet &ClsMap,
2736 SelectorSet &InsMapSeen,
2737 SelectorSet &ClsMapSeen,
2738 ObjCImplDecl* IMPDecl,
2739 ObjCContainerDecl* CDecl,
2740 bool &IncompleteImpl,
2741 bool ImmediateClass,
2742 bool WarnCategoryMethodImpl) {
2743 // Check and see if instance methods in class interface have been
2744 // implemented in the implementation class. If so, their types match.
2745 for (auto *I : CDecl->instance_methods()) {
2746 if (!InsMapSeen.insert(I->getSelector()).second)
2748 if (!I->isPropertyAccessor() &&
2749 !InsMap.count(I->getSelector())) {
2751 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2752 diag::warn_undef_method_impl);
2755 ObjCMethodDecl *ImpMethodDecl =
2756 IMPDecl->getInstanceMethod(I->getSelector());
2757 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2758 "Expected to find the method through lookup as well");
2759 // ImpMethodDecl may be null as in a @dynamic property.
2760 if (ImpMethodDecl) {
2761 if (!WarnCategoryMethodImpl)
2762 WarnConflictingTypedMethods(ImpMethodDecl, I,
2763 isa<ObjCProtocolDecl>(CDecl));
2764 else if (!I->isPropertyAccessor())
2765 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2770 // Check and see if class methods in class interface have been
2771 // implemented in the implementation class. If so, their types match.
2772 for (auto *I : CDecl->class_methods()) {
2773 if (!ClsMapSeen.insert(I->getSelector()).second)
2775 if (!I->isPropertyAccessor() &&
2776 !ClsMap.count(I->getSelector())) {
2778 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
2779 diag::warn_undef_method_impl);
2781 ObjCMethodDecl *ImpMethodDecl =
2782 IMPDecl->getClassMethod(I->getSelector());
2783 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2784 "Expected to find the method through lookup as well");
2785 // ImpMethodDecl may be null as in a @dynamic property.
2786 if (ImpMethodDecl) {
2787 if (!WarnCategoryMethodImpl)
2788 WarnConflictingTypedMethods(ImpMethodDecl, I,
2789 isa<ObjCProtocolDecl>(CDecl));
2790 else if (!I->isPropertyAccessor())
2791 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2796 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2797 // Also, check for methods declared in protocols inherited by
2799 for (auto *PI : PD->protocols())
2800 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2801 IMPDecl, PI, IncompleteImpl, false,
2802 WarnCategoryMethodImpl);
2805 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2806 // when checking that methods in implementation match their declaration,
2807 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2808 // extension; as well as those in categories.
2809 if (!WarnCategoryMethodImpl) {
2810 for (auto *Cat : I->visible_categories())
2811 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2812 IMPDecl, Cat, IncompleteImpl,
2813 ImmediateClass && Cat->IsClassExtension(),
2814 WarnCategoryMethodImpl);
2816 // Also methods in class extensions need be looked at next.
2817 for (auto *Ext : I->visible_extensions())
2818 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2819 IMPDecl, Ext, IncompleteImpl, false,
2820 WarnCategoryMethodImpl);
2823 // Check for any implementation of a methods declared in protocol.
2824 for (auto *PI : I->all_referenced_protocols())
2825 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2826 IMPDecl, PI, IncompleteImpl, false,
2827 WarnCategoryMethodImpl);
2829 // FIXME. For now, we are not checking for extact match of methods
2830 // in category implementation and its primary class's super class.
2831 if (!WarnCategoryMethodImpl && I->getSuperClass())
2832 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2834 I->getSuperClass(), IncompleteImpl, false);
2838 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2839 /// category matches with those implemented in its primary class and
2840 /// warns each time an exact match is found.
2841 void Sema::CheckCategoryVsClassMethodMatches(
2842 ObjCCategoryImplDecl *CatIMPDecl) {
2843 // Get category's primary class.
2844 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2847 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2850 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2851 SelectorSet InsMap, ClsMap;
2853 for (const auto *I : CatIMPDecl->instance_methods()) {
2854 Selector Sel = I->getSelector();
2855 // When checking for methods implemented in the category, skip over
2856 // those declared in category class's super class. This is because
2857 // the super class must implement the method.
2858 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2863 for (const auto *I : CatIMPDecl->class_methods()) {
2864 Selector Sel = I->getSelector();
2865 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2869 if (InsMap.empty() && ClsMap.empty())
2872 SelectorSet InsMapSeen, ClsMapSeen;
2873 bool IncompleteImpl = false;
2874 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2876 IncompleteImpl, false,
2877 true /*WarnCategoryMethodImpl*/);
2880 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
2881 ObjCContainerDecl* CDecl,
2882 bool IncompleteImpl) {
2884 // Check and see if instance methods in class interface have been
2885 // implemented in the implementation class.
2886 for (const auto *I : IMPDecl->instance_methods())
2887 InsMap.insert(I->getSelector());
2889 // Add the selectors for getters/setters of @dynamic properties.
2890 for (const auto *PImpl : IMPDecl->property_impls()) {
2891 // We only care about @dynamic implementations.
2892 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2895 const auto *P = PImpl->getPropertyDecl();
2898 InsMap.insert(P->getGetterName());
2899 if (!P->getSetterName().isNull())
2900 InsMap.insert(P->getSetterName());
2903 // Check and see if properties declared in the interface have either 1)
2904 // an implementation or 2) there is a @synthesize/@dynamic implementation
2905 // of the property in the @implementation.
2906 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2907 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2908 LangOpts.ObjCRuntime.isNonFragile() &&
2909 !IDecl->isObjCRequiresPropertyDefs();
2910 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2913 // Diagnose null-resettable synthesized setters.
2914 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2917 for (const auto *I : IMPDecl->class_methods())
2918 ClsMap.insert(I->getSelector());
2920 // Check for type conflict of methods declared in a class/protocol and
2921 // its implementation; if any.
2922 SelectorSet InsMapSeen, ClsMapSeen;
2923 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2925 IncompleteImpl, true);
2927 // check all methods implemented in category against those declared
2928 // in its primary class.
2929 if (ObjCCategoryImplDecl *CatDecl =
2930 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2931 CheckCategoryVsClassMethodMatches(CatDecl);
2933 // Check the protocol list for unimplemented methods in the @implementation
2935 // Check and see if class methods in class interface have been
2936 // implemented in the implementation class.
2938 LazyProtocolNameSet ExplicitImplProtocols;
2940 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2941 for (auto *PI : I->all_referenced_protocols())
2942 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2943 InsMap, ClsMap, I, ExplicitImplProtocols);
2944 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2945 // For extended class, unimplemented methods in its protocols will
2946 // be reported in the primary class.
2947 if (!C->IsClassExtension()) {
2948 for (auto *P : C->protocols())
2949 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
2950 IncompleteImpl, InsMap, ClsMap, CDecl,
2951 ExplicitImplProtocols);
2952 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2953 /*SynthesizeProperties=*/false);
2956 llvm_unreachable("invalid ObjCContainerDecl type.");
2959 Sema::DeclGroupPtrTy
2960 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
2961 IdentifierInfo **IdentList,
2962 SourceLocation *IdentLocs,
2963 ArrayRef<ObjCTypeParamList *> TypeParamLists,
2965 SmallVector<Decl *, 8> DeclsInGroup;
2966 for (unsigned i = 0; i != NumElts; ++i) {
2967 // Check for another declaration kind with the same name.
2969 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
2970 LookupOrdinaryName, ForRedeclaration);
2971 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2972 // GCC apparently allows the following idiom:
2974 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2975 // @class XCElementToggler;
2977 // Here we have chosen to ignore the forward class declaration
2978 // with a warning. Since this is the implied behavior.
2979 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
2980 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
2981 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
2982 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2984 // a forward class declaration matching a typedef name of a class refers
2985 // to the underlying class. Just ignore the forward class with a warning
2986 // as this will force the intended behavior which is to lookup the
2988 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2989 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2991 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2997 // Create a declaration to describe this forward declaration.
2998 ObjCInterfaceDecl *PrevIDecl
2999 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3001 IdentifierInfo *ClassName = IdentList[i];
3002 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3003 // A previous decl with a different name is because of
3004 // @compatibility_alias, for example:
3007 // @compatibility_alias OldImage NewImage;
3009 // A lookup for 'OldImage' will return the 'NewImage' decl.
3011 // In such a case use the real declaration name, instead of the alias one,
3012 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3013 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3014 // has been aliased.
3015 ClassName = PrevIDecl->getIdentifier();
3018 // If this forward declaration has type parameters, compare them with the
3019 // type parameters of the previous declaration.
3020 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3021 if (PrevIDecl && TypeParams) {
3022 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3023 // Check for consistency with the previous declaration.
3024 if (checkTypeParamListConsistency(
3025 *this, PrevTypeParams, TypeParams,
3026 TypeParamListContext::ForwardDeclaration)) {
3027 TypeParams = nullptr;
3029 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3030 // The @interface does not have type parameters. Complain.
3031 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3033 << TypeParams->getSourceRange();
3034 Diag(Def->getLocation(), diag::note_defined_here)
3037 TypeParams = nullptr;
3041 ObjCInterfaceDecl *IDecl
3042 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
3043 ClassName, TypeParams, PrevIDecl,
3045 IDecl->setAtEndRange(IdentLocs[i]);
3047 PushOnScopeChains(IDecl, TUScope);
3048 CheckObjCDeclScope(IDecl);
3049 DeclsInGroup.push_back(IDecl);
3052 return BuildDeclaratorGroup(DeclsInGroup);
3055 static bool tryMatchRecordTypes(ASTContext &Context,
3056 Sema::MethodMatchStrategy strategy,
3057 const Type *left, const Type *right);
3059 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3060 QualType leftQT, QualType rightQT) {
3062 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3064 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3066 if (left == right) return true;
3068 // If we're doing a strict match, the types have to match exactly.
3069 if (strategy == Sema::MMS_strict) return false;
3071 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3073 // Otherwise, use this absurdly complicated algorithm to try to
3074 // validate the basic, low-level compatibility of the two types.
3076 // As a minimum, require the sizes and alignments to match.
3077 TypeInfo LeftTI = Context.getTypeInfo(left);
3078 TypeInfo RightTI = Context.getTypeInfo(right);
3079 if (LeftTI.Width != RightTI.Width)
3082 if (LeftTI.Align != RightTI.Align)
3085 // Consider all the kinds of non-dependent canonical types:
3086 // - functions and arrays aren't possible as return and parameter types
3088 // - vector types of equal size can be arbitrarily mixed
3089 if (isa<VectorType>(left)) return isa<VectorType>(right);
3090 if (isa<VectorType>(right)) return false;
3092 // - references should only match references of identical type
3093 // - structs, unions, and Objective-C objects must match more-or-less
3095 // - everything else should be a scalar
3096 if (!left->isScalarType() || !right->isScalarType())
3097 return tryMatchRecordTypes(Context, strategy, left, right);
3099 // Make scalars agree in kind, except count bools as chars, and group
3100 // all non-member pointers together.
3101 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3102 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3103 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3104 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3105 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3106 leftSK = Type::STK_ObjCObjectPointer;
3107 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3108 rightSK = Type::STK_ObjCObjectPointer;
3110 // Note that data member pointers and function member pointers don't
3111 // intermix because of the size differences.
3113 return (leftSK == rightSK);
3116 static bool tryMatchRecordTypes(ASTContext &Context,
3117 Sema::MethodMatchStrategy strategy,
3118 const Type *lt, const Type *rt) {
3119 assert(lt && rt && lt != rt);
3121 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3122 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3123 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3125 // Require union-hood to match.
3126 if (left->isUnion() != right->isUnion()) return false;
3128 // Require an exact match if either is non-POD.
3129 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3130 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3133 // Require size and alignment to match.
3134 TypeInfo LeftTI = Context.getTypeInfo(lt);
3135 TypeInfo RightTI = Context.getTypeInfo(rt);
3136 if (LeftTI.Width != RightTI.Width)
3139 if (LeftTI.Align != RightTI.Align)
3142 // Require fields to match.
3143 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3144 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3145 for (; li != le && ri != re; ++li, ++ri) {
3146 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3149 return (li == le && ri == re);
3152 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3153 /// returns true, or false, accordingly.
3154 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3155 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3156 const ObjCMethodDecl *right,
3157 MethodMatchStrategy strategy) {
3158 if (!matchTypes(Context, strategy, left->getReturnType(),
3159 right->getReturnType()))
3162 // If either is hidden, it is not considered to match.
3163 if (left->isHidden() || right->isHidden())
3166 if (getLangOpts().ObjCAutoRefCount &&
3167 (left->hasAttr<NSReturnsRetainedAttr>()
3168 != right->hasAttr<NSReturnsRetainedAttr>() ||
3169 left->hasAttr<NSConsumesSelfAttr>()
3170 != right->hasAttr<NSConsumesSelfAttr>()))
3173 ObjCMethodDecl::param_const_iterator
3174 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3175 re = right->param_end();
3177 for (; li != le && ri != re; ++li, ++ri) {
3178 assert(ri != right->param_end() && "Param mismatch");
3179 const ParmVarDecl *lparm = *li, *rparm = *ri;
3181 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3184 if (getLangOpts().ObjCAutoRefCount &&
3185 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3191 static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3192 ObjCMethodDecl *MethodInList) {
3193 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3194 auto *MethodInListProtocol =
3195 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3196 // If this method belongs to a protocol but the method in list does not, or
3197 // vice versa, we say the context is not the same.
3198 if ((MethodProtocol && !MethodInListProtocol) ||
3199 (!MethodProtocol && MethodInListProtocol))
3202 if (MethodProtocol && MethodInListProtocol)
3205 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3206 ObjCInterfaceDecl *MethodInListInterface =
3207 MethodInList->getClassInterface();
3208 return MethodInterface == MethodInListInterface;
3211 void Sema::addMethodToGlobalList(ObjCMethodList *List,
3212 ObjCMethodDecl *Method) {
3213 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3214 // inside categories.
3215 if (ObjCCategoryDecl *CD =
3216 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3217 if (!CD->IsClassExtension() && List->getBits() < 2)
3218 List->setBits(List->getBits() + 1);
3220 // If the list is empty, make it a singleton list.
3221 if (List->getMethod() == nullptr) {
3222 List->setMethod(Method);
3223 List->setNext(nullptr);
3227 // We've seen a method with this name, see if we have already seen this type
3229 ObjCMethodList *Previous = List;
3230 ObjCMethodList *ListWithSameDeclaration = nullptr;
3231 for (; List; Previous = List, List = List->getNext()) {
3232 // If we are building a module, keep all of the methods.
3233 if (getLangOpts().isCompilingModule())
3236 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3238 // Looking for method with a type bound requires the correct context exists.
3239 // We need to insert a method into the list if the context is different.
3240 // If the method's declaration matches the list
3241 // a> the method belongs to a different context: we need to insert it, in
3242 // order to emit the availability message, we need to prioritize over
3243 // availability among the methods with the same declaration.
3244 // b> the method belongs to the same context: there is no need to insert a
3246 // If the method's declaration does not match the list, we insert it to the
3248 if (!SameDeclaration ||
3249 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3250 // Even if two method types do not match, we would like to say
3251 // there is more than one declaration so unavailability/deprecated
3252 // warning is not too noisy.
3253 if (!Method->isDefined())
3254 List->setHasMoreThanOneDecl(true);
3256 // For methods with the same declaration, the one that is deprecated
3257 // should be put in the front for better diagnostics.
3258 if (Method->isDeprecated() && SameDeclaration &&
3259 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3260 ListWithSameDeclaration = List;
3262 if (Method->isUnavailable() && SameDeclaration &&
3263 !ListWithSameDeclaration &&
3264 List->getMethod()->getAvailability() < AR_Deprecated)
3265 ListWithSameDeclaration = List;
3269 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3271 // Propagate the 'defined' bit.
3272 if (Method->isDefined())
3273 PrevObjCMethod->setDefined(true);
3275 // Objective-C doesn't allow an @interface for a class after its
3276 // @implementation. So if Method is not defined and there already is
3277 // an entry for this type signature, Method has to be for a different
3278 // class than PrevObjCMethod.
3279 List->setHasMoreThanOneDecl(true);
3282 // If a method is deprecated, push it in the global pool.
3283 // This is used for better diagnostics.
3284 if (Method->isDeprecated()) {
3285 if (!PrevObjCMethod->isDeprecated())
3286 List->setMethod(Method);
3288 // If the new method is unavailable, push it into global pool
3289 // unless previous one is deprecated.
3290 if (Method->isUnavailable()) {
3291 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3292 List->setMethod(Method);
3298 // We have a new signature for an existing method - add it.
3299 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3300 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3302 // We insert it right before ListWithSameDeclaration.
3303 if (ListWithSameDeclaration) {
3304 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3305 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3306 ListWithSameDeclaration->setMethod(Method);
3307 ListWithSameDeclaration->setNext(List);
3311 Previous->setNext(new (Mem) ObjCMethodList(Method));
3314 /// \brief Read the contents of the method pool for a given selector from
3315 /// external storage.
3316 void Sema::ReadMethodPool(Selector Sel) {
3317 assert(ExternalSource && "We need an external AST source");
3318 ExternalSource->ReadMethodPool(Sel);
3321 void Sema::updateOutOfDateSelector(Selector Sel) {
3322 if (!ExternalSource)
3324 ExternalSource->updateOutOfDateSelector(Sel);
3327 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3329 // Ignore methods of invalid containers.
3330 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3334 ReadMethodPool(Method->getSelector());
3336 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
3337 if (Pos == MethodPool.end())
3338 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3339 GlobalMethods())).first;
3341 Method->setDefined(impl);
3343 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3344 addMethodToGlobalList(&Entry, Method);
3347 /// Determines if this is an "acceptable" loose mismatch in the global
3348 /// method pool. This exists mostly as a hack to get around certain
3349 /// global mismatches which we can't afford to make warnings / errors.
3350 /// Really, what we want is a way to take a method out of the global
3352 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3353 ObjCMethodDecl *other) {
3354 if (!chosen->isInstanceMethod())
3357 Selector sel = chosen->getSelector();
3358 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3361 // Don't complain about mismatches for -length if the method we
3362 // chose has an integral result type.
3363 return (chosen->getReturnType()->isIntegerType());
3366 /// Return true if the given method is wthin the type bound.
3367 static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3368 const ObjCObjectType *TypeBound) {
3372 if (TypeBound->isObjCId())
3373 // FIXME: should we handle the case of bounding to id<A, B> differently?
3376 auto *BoundInterface = TypeBound->getInterface();
3377 assert(BoundInterface && "unexpected object type!");
3379 // Check if the Method belongs to a protocol. We should allow any method
3380 // defined in any protocol, because any subclass could adopt the protocol.
3381 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3382 if (MethodProtocol) {
3386 // If the Method belongs to a class, check if it belongs to the class
3387 // hierarchy of the class bound.
3388 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3389 // We allow methods declared within classes that are part of the hierarchy
3390 // of the class bound (superclass of, subclass of, or the same as the class
3392 return MethodInterface == BoundInterface ||
3393 MethodInterface->isSuperClassOf(BoundInterface) ||
3394 BoundInterface->isSuperClassOf(MethodInterface);
3396 llvm_unreachable("unknow method context");
3399 /// We first select the type of the method: Instance or Factory, then collect
3400 /// all methods with that type.
3401 bool Sema::CollectMultipleMethodsInGlobalPool(
3402 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
3403 bool InstanceFirst, bool CheckTheOther,
3404 const ObjCObjectType *TypeBound) {
3406 ReadMethodPool(Sel);
3408 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3409 if (Pos == MethodPool.end())
3412 // Gather the non-hidden methods.
3413 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3415 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3416 if (M->getMethod() && !M->getMethod()->isHidden()) {
3417 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3418 Methods.push_back(M->getMethod());
3421 // Return if we find any method with the desired kind.
3422 if (!Methods.empty())
3423 return Methods.size() > 1;
3428 // Gather the other kind.
3429 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3431 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3432 if (M->getMethod() && !M->getMethod()->isHidden()) {
3433 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3434 Methods.push_back(M->getMethod());
3437 return Methods.size() > 1;
3440 bool Sema::AreMultipleMethodsInGlobalPool(
3441 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3442 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3443 // Diagnose finding more than one method in global pool.
3444 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3445 FilteredMethods.push_back(BestMethod);
3447 for (auto *M : Methods)
3448 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3449 FilteredMethods.push_back(M);
3451 if (FilteredMethods.size() > 1)
3452 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3455 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3456 // Test for no method in the pool which should not trigger any warning by
3458 if (Pos == MethodPool.end())
3460 ObjCMethodList &MethList =
3461 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3462 return MethList.hasMoreThanOneDecl();
3465 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3466 bool receiverIdOrClass,
3469 ReadMethodPool(Sel);
3471 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3472 if (Pos == MethodPool.end())
3475 // Gather the non-hidden methods.
3476 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3477 SmallVector<ObjCMethodDecl *, 4> Methods;
3478 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3479 if (M->getMethod() && !M->getMethod()->isHidden())
3480 return M->getMethod();
3485 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3486 Selector Sel, SourceRange R,
3487 bool receiverIdOrClass) {
3488 // We found multiple methods, so we may have to complain.
3489 bool issueDiagnostic = false, issueError = false;
3491 // We support a warning which complains about *any* difference in
3492 // method signature.
3493 bool strictSelectorMatch =
3494 receiverIdOrClass &&
3495 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3496 if (strictSelectorMatch) {
3497 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3498 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3499 issueDiagnostic = true;
3505 // If we didn't see any strict differences, we won't see any loose
3506 // differences. In ARC, however, we also need to check for loose
3507 // mismatches, because most of them are errors.
3508 if (!strictSelectorMatch ||
3509 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3510 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3511 // This checks if the methods differ in type mismatch.
3512 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3513 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3514 issueDiagnostic = true;
3515 if (getLangOpts().ObjCAutoRefCount)
3521 if (issueDiagnostic) {
3523 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3524 else if (strictSelectorMatch)
3525 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3527 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3529 Diag(Methods[0]->getLocStart(),
3530 issueError ? diag::note_possibility : diag::note_using)
3531 << Methods[0]->getSourceRange();
3532 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3533 Diag(Methods[I]->getLocStart(), diag::note_also_found)
3534 << Methods[I]->getSourceRange();
3539 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
3540 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3541 if (Pos == MethodPool.end())
3544 GlobalMethods &Methods = Pos->second;
3545 for (const ObjCMethodList *Method = &Methods.first; Method;
3546 Method = Method->getNext())
3547 if (Method->getMethod() &&
3548 (Method->getMethod()->isDefined() ||
3549 Method->getMethod()->isPropertyAccessor()))
3550 return Method->getMethod();
3552 for (const ObjCMethodList *Method = &Methods.second; Method;
3553 Method = Method->getNext())
3554 if (Method->getMethod() &&
3555 (Method->getMethod()->isDefined() ||
3556 Method->getMethod()->isPropertyAccessor()))
3557 return Method->getMethod();
3562 HelperSelectorsForTypoCorrection(
3563 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3564 StringRef Typo, const ObjCMethodDecl * Method) {
3565 const unsigned MaxEditDistance = 1;
3566 unsigned BestEditDistance = MaxEditDistance + 1;
3567 std::string MethodName = Method->getSelector().getAsString();
3569 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3570 if (MinPossibleEditDistance > 0 &&
3571 Typo.size() / MinPossibleEditDistance < 1)
3573 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3574 if (EditDistance > MaxEditDistance)
3576 if (EditDistance == BestEditDistance)
3577 BestMethod.push_back(Method);
3578 else if (EditDistance < BestEditDistance) {
3580 BestMethod.push_back(Method);
3584 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3585 QualType ObjectType) {
3586 if (ObjectType.isNull())
3588 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3590 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3594 const ObjCMethodDecl *
3595 Sema::SelectorsForTypoCorrection(Selector Sel,
3596 QualType ObjectType) {
3597 unsigned NumArgs = Sel.getNumArgs();
3598 SmallVector<const ObjCMethodDecl *, 8> Methods;
3599 bool ObjectIsId = true, ObjectIsClass = true;
3600 if (ObjectType.isNull())
3601 ObjectIsId = ObjectIsClass = false;
3602 else if (!ObjectType->isObjCObjectPointerType())
3604 else if (const ObjCObjectPointerType *ObjCPtr =
3605 ObjectType->getAsObjCInterfacePointerType()) {
3606 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3607 ObjectIsId = ObjectIsClass = false;
3609 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3610 ObjectIsClass = false;
3611 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3616 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3617 e = MethodPool.end(); b != e; b++) {
3619 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3620 if (M->getMethod() &&
3621 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3622 (M->getMethod()->getSelector() != Sel)) {
3624 Methods.push_back(M->getMethod());
3625 else if (!ObjectIsClass &&
3626 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3628 Methods.push_back(M->getMethod());
3631 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3632 if (M->getMethod() &&
3633 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3634 (M->getMethod()->getSelector() != Sel)) {
3636 Methods.push_back(M->getMethod());
3637 else if (!ObjectIsId &&
3638 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3640 Methods.push_back(M->getMethod());
3644 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3645 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3646 HelperSelectorsForTypoCorrection(SelectedMethods,
3647 Sel.getAsString(), Methods[i]);
3649 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3652 /// DiagnoseDuplicateIvars -
3653 /// Check for duplicate ivars in the entire class at the start of
3654 /// \@implementation. This becomes necesssary because class extension can
3655 /// add ivars to a class in random order which will not be known until
3656 /// class's \@implementation is seen.
3657 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3658 ObjCInterfaceDecl *SID) {
3659 for (auto *Ivar : ID->ivars()) {
3660 if (Ivar->isInvalidDecl())
3662 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3663 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3665 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3666 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3667 Ivar->setInvalidDecl();
3673 /// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3674 static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3675 if (S.getLangOpts().ObjCWeak) return;
3677 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3678 ivar; ivar = ivar->getNextIvar()) {
3679 if (ivar->isInvalidDecl()) continue;
3680 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3681 if (S.getLangOpts().ObjCWeakRuntime) {
3682 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3684 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3690 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3691 switch (CurContext->getDeclKind()) {
3692 case Decl::ObjCInterface:
3693 return Sema::OCK_Interface;
3694 case Decl::ObjCProtocol:
3695 return Sema::OCK_Protocol;
3696 case Decl::ObjCCategory:
3697 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3698 return Sema::OCK_ClassExtension;
3699 return Sema::OCK_Category;
3700 case Decl::ObjCImplementation:
3701 return Sema::OCK_Implementation;
3702 case Decl::ObjCCategoryImpl:
3703 return Sema::OCK_CategoryImplementation;
3706 return Sema::OCK_None;
3710 // Note: For class/category implementations, allMethods is always null.
3711 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
3712 ArrayRef<DeclGroupPtrTy> allTUVars) {
3713 if (getObjCContainerKind() == Sema::OCK_None)
3716 assert(AtEnd.isValid() && "Invalid location for '@end'");
3718 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3719 Decl *ClassDecl = cast<Decl>(OCD);
3721 bool isInterfaceDeclKind =
3722 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3723 || isa<ObjCProtocolDecl>(ClassDecl);
3724 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
3726 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3727 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3728 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3730 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
3731 ObjCMethodDecl *Method =
3732 cast_or_null<ObjCMethodDecl>(allMethods[i]);
3734 if (!Method) continue; // Already issued a diagnostic.
3735 if (Method->isInstanceMethod()) {
3736 /// Check for instance method of the same name with incompatible types
3737 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
3738 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
3740 if ((isInterfaceDeclKind && PrevMethod && !match)
3741 || (checkIdenticalMethods && match)) {
3742 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
3743 << Method->getDeclName();
3744 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3745 Method->setInvalidDecl();
3748 Method->setAsRedeclaration(PrevMethod);
3749 if (!Context.getSourceManager().isInSystemHeader(
3750 Method->getLocation()))
3751 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3752 << Method->getDeclName();
3753 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3755 InsMap[Method->getSelector()] = Method;
3756 /// The following allows us to typecheck messages to "id".
3757 AddInstanceMethodToGlobalPool(Method);
3760 /// Check for class method of the same name with incompatible types
3761 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
3762 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
3764 if ((isInterfaceDeclKind && PrevMethod && !match)
3765 || (checkIdenticalMethods && match)) {
3766 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
3767 << Method->getDeclName();
3768 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3769 Method->setInvalidDecl();
3772 Method->setAsRedeclaration(PrevMethod);
3773 if (!Context.getSourceManager().isInSystemHeader(
3774 Method->getLocation()))
3775 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3776 << Method->getDeclName();
3777 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3779 ClsMap[Method->getSelector()] = Method;
3780 AddFactoryMethodToGlobalPool(Method);
3784 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3785 // Nothing to do here.
3786 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
3787 // Categories are used to extend the class by declaring new methods.
3788 // By the same token, they are also used to add new properties. No
3789 // need to compare the added property to those in the class.
3791 if (C->IsClassExtension()) {
3792 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3793 DiagnoseClassExtensionDupMethods(C, CCPrimary);
3796 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
3797 if (CDecl->getIdentifier())
3798 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3799 // user-defined setter/getter. It also synthesizes setter/getter methods
3800 // and adds them to the DeclContext and global method pools.
3801 for (auto *I : CDecl->properties())
3802 ProcessPropertyDecl(I);
3803 CDecl->setAtEndRange(AtEnd);
3805 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
3806 IC->setAtEndRange(AtEnd);
3807 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
3808 // Any property declared in a class extension might have user
3809 // declared setter or getter in current class extension or one
3810 // of the other class extensions. Mark them as synthesized as
3811 // property will be synthesized when property with same name is
3812 // seen in the @implementation.
3813 for (const auto *Ext : IDecl->visible_extensions()) {
3814 for (const auto *Property : Ext->instance_properties()) {
3815 // Skip over properties declared @dynamic
3816 if (const ObjCPropertyImplDecl *PIDecl
3817 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3818 Property->getQueryKind()))
3819 if (PIDecl->getPropertyImplementation()
3820 == ObjCPropertyImplDecl::Dynamic)
3823 for (const auto *Ext : IDecl->visible_extensions()) {
3824 if (ObjCMethodDecl *GetterMethod
3825 = Ext->getInstanceMethod(Property->getGetterName()))
3826 GetterMethod->setPropertyAccessor(true);
3827 if (!Property->isReadOnly())
3828 if (ObjCMethodDecl *SetterMethod
3829 = Ext->getInstanceMethod(Property->getSetterName()))
3830 SetterMethod->setPropertyAccessor(true);
3834 ImplMethodsVsClassMethods(S, IC, IDecl);
3835 AtomicPropertySetterGetterRules(IC, IDecl);
3836 DiagnoseOwningPropertyGetterSynthesis(IC);
3837 DiagnoseUnusedBackingIvarInAccessor(S, IC);
3838 if (IDecl->hasDesignatedInitializers())
3839 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
3840 DiagnoseWeakIvars(*this, IC);
3842 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
3843 if (IDecl->getSuperClass() == nullptr) {
3844 // This class has no superclass, so check that it has been marked with
3845 // __attribute((objc_root_class)).
3846 if (!HasRootClassAttr) {
3847 SourceLocation DeclLoc(IDecl->getLocation());
3848 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
3849 Diag(DeclLoc, diag::warn_objc_root_class_missing)
3850 << IDecl->getIdentifier();
3851 // See if NSObject is in the current scope, and if it is, suggest
3852 // adding " : NSObject " to the class declaration.
3853 NamedDecl *IF = LookupSingleName(TUScope,
3854 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
3855 DeclLoc, LookupOrdinaryName);
3856 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
3857 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
3858 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
3859 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
3861 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
3864 } else if (HasRootClassAttr) {
3865 // Complain that only root classes may have this attribute.
3866 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
3869 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
3870 // An interface can subclass another interface with a
3871 // objc_subclassing_restricted attribute when it has that attribute as
3872 // well (because of interfaces imported from Swift). Therefore we have
3873 // to check if we can subclass in the implementation as well.
3874 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
3875 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
3876 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
3877 Diag(Super->getLocation(), diag::note_class_declared);
3881 if (LangOpts.ObjCRuntime.isNonFragile()) {
3882 while (IDecl->getSuperClass()) {
3883 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
3884 IDecl = IDecl->getSuperClass();
3888 SetIvarInitializers(IC);
3889 } else if (ObjCCategoryImplDecl* CatImplClass =
3890 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
3891 CatImplClass->setAtEndRange(AtEnd);
3893 // Find category interface decl and then check that all methods declared
3894 // in this interface are implemented in the category @implementation.
3895 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
3896 if (ObjCCategoryDecl *Cat
3897 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
3898 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
3901 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
3902 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
3903 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
3904 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
3905 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
3906 Diag(Super->getLocation(), diag::note_class_declared);
3910 if (isInterfaceDeclKind) {
3911 // Reject invalid vardecls.
3912 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
3913 DeclGroupRef DG = allTUVars[i].get();
3914 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3915 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
3916 if (!VDecl->hasExternalStorage())
3917 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
3921 ActOnObjCContainerFinishDefinition();
3923 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
3924 DeclGroupRef DG = allTUVars[i].get();
3925 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3926 (*I)->setTopLevelDeclInObjCContainer();
3927 Consumer.HandleTopLevelDeclInObjCContainer(DG);
3930 ActOnDocumentableDecl(ClassDecl);
3934 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
3935 /// objective-c's type qualifier from the parser version of the same info.
3936 static Decl::ObjCDeclQualifier
3937 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
3938 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
3941 /// \brief Check whether the declared result type of the given Objective-C
3942 /// method declaration is compatible with the method's class.
3944 static Sema::ResultTypeCompatibilityKind
3945 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
3946 ObjCInterfaceDecl *CurrentClass) {
3947 QualType ResultType = Method->getReturnType();
3949 // If an Objective-C method inherits its related result type, then its
3950 // declared result type must be compatible with its own class type. The
3951 // declared result type is compatible if:
3952 if (const ObjCObjectPointerType *ResultObjectType
3953 = ResultType->getAs<ObjCObjectPointerType>()) {
3954 // - it is id or qualified id, or
3955 if (ResultObjectType->isObjCIdType() ||
3956 ResultObjectType->isObjCQualifiedIdType())
3957 return Sema::RTC_Compatible;
3960 if (ObjCInterfaceDecl *ResultClass
3961 = ResultObjectType->getInterfaceDecl()) {
3962 // - it is the same as the method's class type, or
3963 if (declaresSameEntity(CurrentClass, ResultClass))
3964 return Sema::RTC_Compatible;
3966 // - it is a superclass of the method's class type
3967 if (ResultClass->isSuperClassOf(CurrentClass))
3968 return Sema::RTC_Compatible;
3971 // Any Objective-C pointer type might be acceptable for a protocol
3972 // method; we just don't know.
3973 return Sema::RTC_Unknown;
3977 return Sema::RTC_Incompatible;
3981 /// A helper class for searching for methods which a particular method
3983 class OverrideSearch {
3986 ObjCMethodDecl *Method;
3987 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
3991 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
3992 Selector selector = method->getSelector();
3994 // Bypass this search if we've never seen an instance/class method
3995 // with this selector before.
3996 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
3997 if (it == S.MethodPool.end()) {
3998 if (!S.getExternalSource()) return;
3999 S.ReadMethodPool(selector);
4001 it = S.MethodPool.find(selector);
4002 if (it == S.MethodPool.end())
4005 ObjCMethodList &list =
4006 method->isInstanceMethod() ? it->second.first : it->second.second;
4007 if (!list.getMethod()) return;
4009 ObjCContainerDecl *container
4010 = cast<ObjCContainerDecl>(method->getDeclContext());
4012 // Prevent the search from reaching this container again. This is
4013 // important with categories, which override methods from the
4014 // interface and each other.
4015 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4016 searchFromContainer(container);
4017 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4018 searchFromContainer(Interface);
4020 searchFromContainer(container);
4024 typedef llvm::SmallPtrSetImpl<ObjCMethodDecl*>::iterator iterator;
4025 iterator begin() const { return Overridden.begin(); }
4026 iterator end() const { return Overridden.end(); }
4029 void searchFromContainer(ObjCContainerDecl *container) {
4030 if (container->isInvalidDecl()) return;
4032 switch (container->getDeclKind()) {
4033 #define OBJCCONTAINER(type, base) \
4035 searchFrom(cast<type##Decl>(container)); \
4037 #define ABSTRACT_DECL(expansion)
4038 #define DECL(type, base) \
4040 #include "clang/AST/DeclNodes.inc"
4041 llvm_unreachable("not an ObjC container!");
4045 void searchFrom(ObjCProtocolDecl *protocol) {
4046 if (!protocol->hasDefinition())
4049 // A method in a protocol declaration overrides declarations from
4050 // referenced ("parent") protocols.
4051 search(protocol->getReferencedProtocols());
4054 void searchFrom(ObjCCategoryDecl *category) {
4055 // A method in a category declaration overrides declarations from
4056 // the main class and from protocols the category references.
4057 // The main class is handled in the constructor.
4058 search(category->getReferencedProtocols());
4061 void searchFrom(ObjCCategoryImplDecl *impl) {
4062 // A method in a category definition that has a category
4063 // declaration overrides declarations from the category
4065 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4067 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4070 // Otherwise it overrides declarations from the class.
4071 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4076 void searchFrom(ObjCInterfaceDecl *iface) {
4077 // A method in a class declaration overrides declarations from
4078 if (!iface->hasDefinition())
4082 for (auto *Cat : iface->known_categories())
4085 // - the super class, and
4086 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4089 // - any referenced protocols.
4090 search(iface->getReferencedProtocols());
4093 void searchFrom(ObjCImplementationDecl *impl) {
4094 // A method in a class implementation overrides declarations from
4095 // the class interface.
4096 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4100 void search(const ObjCProtocolList &protocols) {
4101 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4106 void search(ObjCContainerDecl *container) {
4107 // Check for a method in this container which matches this selector.
4108 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4109 Method->isInstanceMethod(),
4110 /*AllowHidden=*/true);
4112 // If we find one, record it and bail out.
4114 Overridden.insert(meth);
4118 // Otherwise, search for methods that a hypothetical method here
4119 // would have overridden.
4121 // Note that we're now in a recursive case.
4124 searchFromContainer(container);
4127 } // end anonymous namespace
4129 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4130 ObjCInterfaceDecl *CurrentClass,
4131 ResultTypeCompatibilityKind RTC) {
4132 // Search for overridden methods and merge information down from them.
4133 OverrideSearch overrides(*this, ObjCMethod);
4134 // Keep track if the method overrides any method in the class's base classes,
4135 // its protocols, or its categories' protocols; we will keep that info
4136 // in the ObjCMethodDecl.
4137 // For this info, a method in an implementation is not considered as
4138 // overriding the same method in the interface or its categories.
4139 bool hasOverriddenMethodsInBaseOrProtocol = false;
4140 for (OverrideSearch::iterator
4141 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4142 ObjCMethodDecl *overridden = *i;
4144 if (!hasOverriddenMethodsInBaseOrProtocol) {
4145 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4146 CurrentClass != overridden->getClassInterface() ||
4147 overridden->isOverriding()) {
4148 hasOverriddenMethodsInBaseOrProtocol = true;
4150 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4151 // OverrideSearch will return as "overridden" the same method in the
4152 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4153 // check whether a category of a base class introduced a method with the
4154 // same selector, after the interface method declaration.
4155 // To avoid unnecessary lookups in the majority of cases, we use the
4156 // extra info bits in GlobalMethodPool to check whether there were any
4157 // category methods with this selector.
4158 GlobalMethodPool::iterator It =
4159 MethodPool.find(ObjCMethod->getSelector());
4160 if (It != MethodPool.end()) {
4161 ObjCMethodList &List =
4162 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4163 unsigned CategCount = List.getBits();
4164 if (CategCount > 0) {
4165 // If the method is in a category we'll do lookup if there were at
4166 // least 2 category methods recorded, otherwise only one will do.
4167 if (CategCount > 1 ||
4168 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4169 OverrideSearch overrides(*this, overridden);
4170 for (OverrideSearch::iterator
4171 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4172 ObjCMethodDecl *SuperOverridden = *OI;
4173 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4174 CurrentClass != SuperOverridden->getClassInterface()) {
4175 hasOverriddenMethodsInBaseOrProtocol = true;
4176 overridden->setOverriding(true);
4186 // Propagate down the 'related result type' bit from overridden methods.
4187 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4188 ObjCMethod->SetRelatedResultType();
4190 // Then merge the declarations.
4191 mergeObjCMethodDecls(ObjCMethod, overridden);
4193 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4194 continue; // Conflicting properties are detected elsewhere.
4196 // Check for overriding methods
4197 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4198 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4199 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4200 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4202 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4203 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4204 !overridden->isImplicit() /* not meant for properties */) {
4205 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4206 E = ObjCMethod->param_end();
4207 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4208 PrevE = overridden->param_end();
4209 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4210 assert(PrevI != overridden->param_end() && "Param mismatch");
4211 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4212 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4213 // If type of argument of method in this class does not match its
4214 // respective argument type in the super class method, issue warning;
4215 if (!Context.typesAreCompatible(T1, T2)) {
4216 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4218 Diag(overridden->getLocation(), diag::note_previous_declaration);
4225 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4228 /// Merge type nullability from for a redeclaration of the same entity,
4229 /// producing the updated type of the redeclared entity.
4230 static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4233 SourceLocation prevLoc,
4235 bool prevUsesCSKeyword) {
4236 // Determine the nullability of both types.
4237 auto nullability = type->getNullability(S.Context);
4238 auto prevNullability = prevType->getNullability(S.Context);
4240 // Easy case: both have nullability.
4241 if (nullability.hasValue() == prevNullability.hasValue()) {
4242 // Neither has nullability; continue.
4246 // The nullabilities are equivalent; do nothing.
4247 if (*nullability == *prevNullability)
4250 // Complain about mismatched nullability.
4251 S.Diag(loc, diag::err_nullability_conflicting)
4252 << DiagNullabilityKind(*nullability, usesCSKeyword)
4253 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4257 // If it's the redeclaration that has nullability, don't change anything.
4261 // Otherwise, provide the result with the same nullability.
4262 return S.Context.getAttributedType(
4263 AttributedType::getNullabilityAttrKind(*prevNullability),
4267 /// Merge information from the declaration of a method in the \@interface
4268 /// (or a category/extension) into the corresponding method in the
4269 /// @implementation (for a class or category).
4270 static void mergeInterfaceMethodToImpl(Sema &S,
4271 ObjCMethodDecl *method,
4272 ObjCMethodDecl *prevMethod) {
4273 // Merge the objc_requires_super attribute.
4274 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4275 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4276 // merge the attribute into implementation.
4278 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4279 method->getLocation()));
4282 // Merge nullability of the result type.
4283 QualType newReturnType
4284 = mergeTypeNullabilityForRedecl(
4285 S, method->getReturnTypeSourceRange().getBegin(),
4286 method->getReturnType(),
4287 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4288 prevMethod->getReturnTypeSourceRange().getBegin(),
4289 prevMethod->getReturnType(),
4290 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4291 method->setReturnType(newReturnType);
4293 // Handle each of the parameters.
4294 unsigned numParams = method->param_size();
4295 unsigned numPrevParams = prevMethod->param_size();
4296 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4297 ParmVarDecl *param = method->param_begin()[i];
4298 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4300 // Merge nullability.
4301 QualType newParamType
4302 = mergeTypeNullabilityForRedecl(
4303 S, param->getLocation(), param->getType(),
4304 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4305 prevParam->getLocation(), prevParam->getType(),
4306 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4307 param->setType(newParamType);
4311 Decl *Sema::ActOnMethodDeclaration(
4313 SourceLocation MethodLoc, SourceLocation EndLoc,
4314 tok::TokenKind MethodType,
4315 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4316 ArrayRef<SourceLocation> SelectorLocs,
4318 // optional arguments. The number of types/arguments is obtained
4319 // from the Sel.getNumArgs().
4320 ObjCArgInfo *ArgInfo,
4321 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
4322 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
4323 bool isVariadic, bool MethodDefinition) {
4324 // Make sure we can establish a context for the method.
4325 if (!CurContext->isObjCContainer()) {
4326 Diag(MethodLoc, diag::err_missing_method_context);
4329 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
4330 Decl *ClassDecl = cast<Decl>(OCD);
4331 QualType resultDeclType;
4333 bool HasRelatedResultType = false;
4334 TypeSourceInfo *ReturnTInfo = nullptr;
4336 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4338 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4341 QualType bareResultType = resultDeclType;
4342 (void)AttributedType::stripOuterNullability(bareResultType);
4343 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4344 } else { // get the type for "id".
4345 resultDeclType = Context.getObjCIdType();
4346 Diag(MethodLoc, diag::warn_missing_method_return_type)
4347 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4350 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4351 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4352 MethodType == tok::minus, isVariadic,
4353 /*isPropertyAccessor=*/false,
4354 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4355 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4356 : ObjCMethodDecl::Required,
4357 HasRelatedResultType);
4359 SmallVector<ParmVarDecl*, 16> Params;
4361 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4365 if (!ArgInfo[i].Type) {
4366 ArgType = Context.getObjCIdType();
4369 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4372 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4373 LookupOrdinaryName, ForRedeclaration);
4375 if (R.isSingleResult()) {
4376 NamedDecl *PrevDecl = R.getFoundDecl();
4377 if (S->isDeclScope(PrevDecl)) {
4378 Diag(ArgInfo[i].NameLoc,
4379 (MethodDefinition ? diag::warn_method_param_redefinition
4380 : diag::warn_method_param_declaration))
4382 Diag(PrevDecl->getLocation(),
4383 diag::note_previous_declaration);
4387 SourceLocation StartLoc = DI
4388 ? DI->getTypeLoc().getBeginLoc()
4389 : ArgInfo[i].NameLoc;
4391 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4392 ArgInfo[i].NameLoc, ArgInfo[i].Name,
4393 ArgType, DI, SC_None);
4395 Param->setObjCMethodScopeInfo(i);
4397 Param->setObjCDeclQualifier(
4398 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4400 // Apply the attributes to the parameter.
4401 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4403 if (Param->hasAttr<BlocksAttr>()) {
4404 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4405 Param->setInvalidDecl();
4408 IdResolver.AddDecl(Param);
4410 Params.push_back(Param);
4413 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4414 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4415 QualType ArgType = Param->getType();
4416 if (ArgType.isNull())
4417 ArgType = Context.getObjCIdType();
4419 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4420 ArgType = Context.getAdjustedParameterType(ArgType);
4422 Param->setDeclContext(ObjCMethod);
4423 Params.push_back(Param);
4426 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4427 ObjCMethod->setObjCDeclQualifier(
4428 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
4431 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4433 // Add the method now.
4434 const ObjCMethodDecl *PrevMethod = nullptr;
4435 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4436 if (MethodType == tok::minus) {
4437 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4438 ImpDecl->addInstanceMethod(ObjCMethod);
4440 PrevMethod = ImpDecl->getClassMethod(Sel);
4441 ImpDecl->addClassMethod(ObjCMethod);
4444 // Merge information from the @interface declaration into the
4446 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4447 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4448 ObjCMethod->isInstanceMethod())) {
4449 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4451 // Warn about defining -dealloc in a category.
4452 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4453 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4454 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4455 << ObjCMethod->getDeclName();
4460 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4464 // You can never have two method definitions with the same name.
4465 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
4466 << ObjCMethod->getDeclName();
4467 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4468 ObjCMethod->setInvalidDecl();
4472 // If this Objective-C method does not have a related result type, but we
4473 // are allowed to infer related result types, try to do so based on the
4475 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4476 if (!CurrentClass) {
4477 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4478 CurrentClass = Cat->getClassInterface();
4479 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4480 CurrentClass = Impl->getClassInterface();
4481 else if (ObjCCategoryImplDecl *CatImpl
4482 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4483 CurrentClass = CatImpl->getClassInterface();
4486 ResultTypeCompatibilityKind RTC
4487 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
4489 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
4491 bool ARCError = false;
4492 if (getLangOpts().ObjCAutoRefCount)
4493 ARCError = CheckARCMethodDecl(ObjCMethod);
4495 // Infer the related result type when possible.
4496 if (!ARCError && RTC == Sema::RTC_Compatible &&
4497 !ObjCMethod->hasRelatedResultType() &&
4498 LangOpts.ObjCInferRelatedResultType) {
4499 bool InferRelatedResultType = false;
4500 switch (ObjCMethod->getMethodFamily()) {
4505 case OMF_mutableCopy:
4507 case OMF_retainCount:
4508 case OMF_initialize:
4509 case OMF_performSelector:
4514 InferRelatedResultType = ObjCMethod->isClassMethod();
4518 case OMF_autorelease:
4521 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4525 if (InferRelatedResultType &&
4526 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
4527 ObjCMethod->SetRelatedResultType();
4530 ActOnDocumentableDecl(ObjCMethod);
4535 bool Sema::CheckObjCDeclScope(Decl *D) {
4536 // Following is also an error. But it is caused by a missing @end
4537 // and diagnostic is issued elsewhere.
4538 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
4541 // If we switched context to translation unit while we are still lexically in
4542 // an objc container, it means the parser missed emitting an error.
4543 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4546 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4547 D->setInvalidDecl();
4552 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
4553 /// instance variables of ClassName into Decls.
4554 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
4555 IdentifierInfo *ClassName,
4556 SmallVectorImpl<Decl*> &Decls) {
4557 // Check that ClassName is a valid class
4558 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
4560 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4563 if (LangOpts.ObjCRuntime.isNonFragile()) {
4564 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4568 // Collect the instance variables
4569 SmallVector<const ObjCIvarDecl*, 32> Ivars;
4570 Context.DeepCollectObjCIvars(Class, true, Ivars);
4571 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
4572 for (unsigned i = 0; i < Ivars.size(); i++) {
4573 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
4574 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
4575 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4576 /*FIXME: StartL=*/ID->getLocation(),
4578 ID->getIdentifier(), ID->getType(),
4580 Decls.push_back(FD);
4583 // Introduce all of these fields into the appropriate scope.
4584 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
4585 D != Decls.end(); ++D) {
4586 FieldDecl *FD = cast<FieldDecl>(*D);
4587 if (getLangOpts().CPlusPlus)
4588 PushOnScopeChains(cast<FieldDecl>(FD), S);
4589 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
4590 Record->addDecl(FD);
4594 /// \brief Build a type-check a new Objective-C exception variable declaration.
4595 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4596 SourceLocation StartLoc,
4597 SourceLocation IdLoc,
4600 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4601 // duration shall not be qualified by an address-space qualifier."
4602 // Since all parameters have automatic store duration, they can not have
4603 // an address space.
4604 if (T.getAddressSpace() != 0) {
4605 Diag(IdLoc, diag::err_arg_with_address_space);
4609 // An @catch parameter must be an unqualified object pointer type;
4610 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4612 // Don't do any further checking.
4613 } else if (T->isDependentType()) {
4614 // Okay: we don't know what this type will instantiate to.
4615 } else if (!T->isObjCObjectPointerType()) {
4617 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
4618 } else if (T->isObjCQualifiedIdType()) {
4620 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
4623 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
4625 New->setExceptionVariable(true);
4627 // In ARC, infer 'retaining' for variables of retainable type.
4628 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
4632 New->setInvalidDecl();
4636 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
4637 const DeclSpec &DS = D.getDeclSpec();
4639 // We allow the "register" storage class on exception variables because
4640 // GCC did, but we drop it completely. Any other storage class is an error.
4641 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4642 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4643 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
4644 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
4645 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
4646 << DeclSpec::getSpecifierName(SCS);
4648 if (DS.isInlineSpecified())
4649 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4650 << getLangOpts().CPlusPlus1z;
4651 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4652 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4653 diag::err_invalid_thread)
4654 << DeclSpec::getSpecifierName(TSCS);
4655 D.getMutableDeclSpec().ClearStorageClassSpecs();
4657 DiagnoseFunctionSpecifiers(D.getDeclSpec());
4659 // Check that there are no default arguments inside the type of this
4660 // exception object (C++ only).
4661 if (getLangOpts().CPlusPlus)
4662 CheckExtraCXXDefaultArguments(D);
4664 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
4665 QualType ExceptionType = TInfo->getType();
4667 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4668 D.getSourceRange().getBegin(),
4669 D.getIdentifierLoc(),
4673 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4674 if (D.getCXXScopeSpec().isSet()) {
4675 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4676 << D.getCXXScopeSpec().getRange();
4677 New->setInvalidDecl();
4680 // Add the parameter declaration into this scope.
4682 if (D.getIdentifier())
4683 IdResolver.AddDecl(New);
4685 ProcessDeclAttributes(S, New, D);
4687 if (New->hasAttr<BlocksAttr>())
4688 Diag(New->getLocation(), diag::err_block_on_nonlocal);
4692 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
4694 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
4695 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
4696 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4697 Iv= Iv->getNextIvar()) {
4698 QualType QT = Context.getBaseElementType(Iv->getType());
4699 if (QT->isRecordType())
4700 Ivars.push_back(Iv);
4704 void Sema::DiagnoseUseOfUnimplementedSelectors() {
4705 // Load referenced selectors from the external source.
4706 if (ExternalSource) {
4707 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4708 ExternalSource->ReadReferencedSelectors(Sels);
4709 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4710 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4713 // Warning will be issued only when selector table is
4714 // generated (which means there is at lease one implementation
4715 // in the TU). This is to match gcc's behavior.
4716 if (ReferencedSelectors.empty() ||
4717 !Context.AnyObjCImplementation())
4719 for (auto &SelectorAndLocation : ReferencedSelectors) {
4720 Selector Sel = SelectorAndLocation.first;
4721 SourceLocation Loc = SelectorAndLocation.second;
4722 if (!LookupImplementedMethodInGlobalPool(Sel))
4723 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
4728 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4729 const ObjCPropertyDecl *&PDecl) const {
4730 if (Method->isClassMethod())
4732 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4735 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4736 /*shallowCategoryLookup=*/false,
4737 /*followSuper=*/false);
4738 if (!Method || !Method->isPropertyAccessor())
4740 if ((PDecl = Method->findPropertyDecl()))
4741 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4742 // property backing ivar must belong to property's class
4743 // or be a private ivar in class's implementation.
4744 // FIXME. fix the const-ness issue.
4745 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4746 IV->getIdentifier());
4753 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4754 /// accessor references the backing ivar.
4755 class UnusedBackingIvarChecker :
4756 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
4759 const ObjCMethodDecl *Method;
4760 const ObjCIvarDecl *IvarD;
4762 bool InvokedSelfMethod;
4764 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4765 const ObjCIvarDecl *IvarD)
4766 : S(S), Method(Method), IvarD(IvarD),
4767 AccessedIvar(false), InvokedSelfMethod(false) {
4771 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4772 if (E->getDecl() == IvarD) {
4773 AccessedIvar = true;
4779 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4780 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4781 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4782 InvokedSelfMethod = true;
4787 } // end anonymous namespace
4789 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4790 const ObjCImplementationDecl *ImplD) {
4791 if (S->hasUnrecoverableErrorOccurred())
4794 for (const auto *CurMethod : ImplD->instance_methods()) {
4795 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4796 SourceLocation Loc = CurMethod->getLocation();
4797 if (Diags.isIgnored(DIAG, Loc))
4800 const ObjCPropertyDecl *PDecl;
4801 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
4805 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
4806 Checker.TraverseStmt(CurMethod->getBody());
4807 if (Checker.AccessedIvar)
4810 // Do not issue this warning if backing ivar is used somewhere and accessor
4811 // implementation makes a self call. This is to prevent false positive in
4812 // cases where the ivar is accessed by another method that the accessor
4814 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
4815 Diag(Loc, DIAG) << IV;
4816 Diag(PDecl->getLocation(), diag::note_property_declare);