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