clang 19.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"
24#include "clang/Sema/Lookup.h"
25#include "clang/Sema/Scope.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/DenseSet.h"
30
31using namespace clang;
32
33/// Check whether the given method, which must be in the 'init'
34/// family, is a valid member of that family.
35///
36/// \param receiverTypeIfCall - if null, check this as if declaring it;
37/// if non-null, check this as if making a call to it with the given
38/// receiver type
39///
40/// \return true to indicate that there was an error and appropriate
41/// actions were taken
43 QualType receiverTypeIfCall) {
44 if (method->isInvalidDecl()) return true;
45
46 // This castAs is safe: methods that don't return an object
47 // pointer won't be inferred as inits and will reject an explicit
48 // objc_method_family(init).
49
50 // We ignore protocols here. Should we? What about Class?
51
52 const ObjCObjectType *result =
54
55 if (result->isObjCId()) {
56 return false;
57 } else if (result->isObjCClass()) {
58 // fall through: always an error
59 } else {
60 ObjCInterfaceDecl *resultClass = result->getInterface();
61 assert(resultClass && "unexpected object type!");
62
63 // It's okay for the result type to still be a forward declaration
64 // if we're checking an interface declaration.
65 if (!resultClass->hasDefinition()) {
66 if (receiverTypeIfCall.isNull() &&
67 !isa<ObjCImplementationDecl>(method->getDeclContext()))
68 return false;
69
70 // Otherwise, we try to compare class types.
71 } else {
72 // If this method was declared in a protocol, we can't check
73 // anything unless we have a receiver type that's an interface.
74 const ObjCInterfaceDecl *receiverClass = nullptr;
75 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76 if (receiverTypeIfCall.isNull())
77 return false;
78
79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
80 ->getInterfaceDecl();
81
82 // This can be null for calls to e.g. id<Foo>.
83 if (!receiverClass) return false;
84 } else {
85 receiverClass = method->getClassInterface();
86 assert(receiverClass && "method not associated with a class!");
87 }
88
89 // If either class is a subclass of the other, it's fine.
90 if (receiverClass->isSuperClassOf(resultClass) ||
91 resultClass->isSuperClassOf(receiverClass))
92 return false;
93 }
94 }
95
96 SourceLocation loc = method->getLocation();
97
98 // If we're in a system header, and this is not a call, just make
99 // the method unusable.
100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
101 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
103 return true;
104 }
105
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
109 return true;
110}
111
112/// Issue a warning if the parameter of the overridden method is non-escaping
113/// but the parameter of the overriding method is not.
114static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
115 Sema &S) {
116 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
117 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
118 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
119 return false;
120 }
121
122 return true;
123}
124
125/// Produce additional diagnostics if a category conforms to a protocol that
126/// defines a method taking a non-escaping parameter.
127static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
128 const ObjCCategoryDecl *CD,
129 const ObjCProtocolDecl *PD, Sema &S) {
130 if (!diagnoseNoescape(NewD, OldD, S))
131 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
132 << CD->IsClassExtension() << PD
133 << cast<ObjCMethodDecl>(NewD->getDeclContext());
134}
135
137 const ObjCMethodDecl *Overridden) {
138 if (Overridden->hasRelatedResultType() &&
139 !NewMethod->hasRelatedResultType()) {
140 // This can only happen when the method follows a naming convention that
141 // implies a related result type, and the original (overridden) method has
142 // a suitable return type, but the new (overriding) method does not have
143 // a suitable return type.
144 QualType ResultType = NewMethod->getReturnType();
145 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
146
147 // Figure out which class this method is part of, if any.
148 ObjCInterfaceDecl *CurrentClass
149 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
150 if (!CurrentClass) {
151 DeclContext *DC = NewMethod->getDeclContext();
152 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
153 CurrentClass = Cat->getClassInterface();
154 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
155 CurrentClass = Impl->getClassInterface();
156 else if (ObjCCategoryImplDecl *CatImpl
157 = dyn_cast<ObjCCategoryImplDecl>(DC))
158 CurrentClass = CatImpl->getClassInterface();
159 }
160
161 if (CurrentClass) {
162 Diag(NewMethod->getLocation(),
163 diag::warn_related_result_type_compatibility_class)
164 << Context.getObjCInterfaceType(CurrentClass)
165 << ResultType
166 << ResultTypeRange;
167 } else {
168 Diag(NewMethod->getLocation(),
169 diag::warn_related_result_type_compatibility_protocol)
170 << ResultType
171 << ResultTypeRange;
172 }
173
174 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
175 Diag(Overridden->getLocation(),
176 diag::note_related_result_type_family)
177 << /*overridden method*/ 0
178 << Family;
179 else
180 Diag(Overridden->getLocation(),
181 diag::note_related_result_type_overridden);
182 }
183
184 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
185 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
186 Diag(NewMethod->getLocation(),
187 getLangOpts().ObjCAutoRefCount
188 ? diag::err_nsreturns_retained_attribute_mismatch
189 : diag::warn_nsreturns_retained_attribute_mismatch)
190 << 1;
191 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
192 }
193 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
194 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
195 Diag(NewMethod->getLocation(),
196 getLangOpts().ObjCAutoRefCount
197 ? diag::err_nsreturns_retained_attribute_mismatch
198 : diag::warn_nsreturns_retained_attribute_mismatch)
199 << 0;
200 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
201 }
202
204 oe = Overridden->param_end();
205 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
206 ne = NewMethod->param_end();
207 ni != ne && oi != oe; ++ni, ++oi) {
208 const ParmVarDecl *oldDecl = (*oi);
209 ParmVarDecl *newDecl = (*ni);
210 if (newDecl->hasAttr<NSConsumedAttr>() !=
211 oldDecl->hasAttr<NSConsumedAttr>()) {
212 Diag(newDecl->getLocation(),
213 getLangOpts().ObjCAutoRefCount
214 ? diag::err_nsconsumed_attribute_mismatch
215 : diag::warn_nsconsumed_attribute_mismatch);
216 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
217 }
218
219 diagnoseNoescape(newDecl, oldDecl, *this);
220 }
221}
222
223/// Check a method declaration for compatibility with the Objective-C
224/// ARC conventions.
226 ObjCMethodFamily family = method->getMethodFamily();
227 switch (family) {
228 case OMF_None:
229 case OMF_finalize:
230 case OMF_retain:
231 case OMF_release:
232 case OMF_autorelease:
233 case OMF_retainCount:
234 case OMF_self:
235 case OMF_initialize:
237 return false;
238
239 case OMF_dealloc:
241 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
242 if (ResultTypeRange.isInvalid())
243 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
244 << method->getReturnType()
245 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
246 else
247 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
248 << method->getReturnType()
249 << FixItHint::CreateReplacement(ResultTypeRange, "void");
250 return true;
251 }
252 return false;
253
254 case OMF_init:
255 // If the method doesn't obey the init rules, don't bother annotating it.
256 if (checkInitMethod(method, QualType()))
257 return true;
258
259 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
260
261 // Don't add a second copy of this attribute, but otherwise don't
262 // let it be suppressed.
263 if (method->hasAttr<NSReturnsRetainedAttr>())
264 return false;
265 break;
266
267 case OMF_alloc:
268 case OMF_copy:
269 case OMF_mutableCopy:
270 case OMF_new:
271 if (method->hasAttr<NSReturnsRetainedAttr>() ||
272 method->hasAttr<NSReturnsNotRetainedAttr>() ||
273 method->hasAttr<NSReturnsAutoreleasedAttr>())
274 return false;
275 break;
276 }
277
278 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
279 return false;
280}
281
283 SourceLocation ImplLoc) {
284 if (!ND)
285 return;
286 bool IsCategory = false;
287 StringRef RealizedPlatform;
288 AvailabilityResult Availability = ND->getAvailability(
289 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
290 &RealizedPlatform);
291 if (Availability != AR_Deprecated) {
292 if (isa<ObjCMethodDecl>(ND)) {
293 if (Availability != AR_Unavailable)
294 return;
295 if (RealizedPlatform.empty())
296 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
297 // Warn about implementing unavailable methods, unless the unavailable
298 // is for an app extension.
299 if (RealizedPlatform.ends_with("_app_extension"))
300 return;
301 S.Diag(ImplLoc, diag::warn_unavailable_def);
302 S.Diag(ND->getLocation(), diag::note_method_declared_at)
303 << ND->getDeclName();
304 return;
305 }
306 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
307 if (!CD->getClassInterface()->isDeprecated())
308 return;
309 ND = CD->getClassInterface();
310 IsCategory = true;
311 } else
312 return;
313 }
314 S.Diag(ImplLoc, diag::warn_deprecated_def)
315 << (isa<ObjCMethodDecl>(ND)
316 ? /*Method*/ 0
317 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
318 : /*Class*/ 1);
319 if (isa<ObjCMethodDecl>(ND))
320 S.Diag(ND->getLocation(), diag::note_method_declared_at)
321 << ND->getDeclName();
322 else
323 S.Diag(ND->getLocation(), diag::note_previous_decl)
324 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
325}
326
327/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
328/// pool.
330 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
331
332 // If we don't have a valid method decl, simply return.
333 if (!MDecl)
334 return;
335 if (MDecl->isInstanceMethod())
337 else
338 AddFactoryMethodToGlobalPool(MDecl, true);
339}
340
341/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
342/// has explicit ownership attribute; false otherwise.
343static bool
345 QualType T = Param->getType();
346
347 if (const PointerType *PT = T->getAs<PointerType>()) {
348 T = PT->getPointeeType();
349 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
350 T = RT->getPointeeType();
351 } else {
352 return true;
353 }
354
355 // If we have a lifetime qualifier, but it's local, we must have
356 // inferred it. So, it is implicit.
358}
359
360/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
361/// and user declared, in the method definition's AST.
364 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
365 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
366
368
369 // If we don't have a valid method decl, simply return.
370 if (!MDecl)
371 return;
372
373 QualType ResultType = MDecl->getReturnType();
374 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
375 !MDecl->isInvalidDecl() &&
376 RequireCompleteType(MDecl->getLocation(), ResultType,
377 diag::err_func_def_incomplete_result))
378 MDecl->setInvalidDecl();
379
380 // Allow all of Sema to see that we are entering a method definition.
381 PushDeclContext(FnBodyScope, MDecl);
383
384 // Create Decl objects for each parameter, entrring them in the scope for
385 // binding to their use.
386
387 // Insert the invisible arguments, self and _cmd!
389
390 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
391 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
392
393 // The ObjC parser requires parameter names so there's no need to check.
395 /*CheckParameterNames=*/false);
396
397 // Introduce all of the other parameters into this scope.
398 for (auto *Param : MDecl->parameters()) {
399 if (!Param->isInvalidDecl() &&
400 getLangOpts().ObjCAutoRefCount &&
401 !HasExplicitOwnershipAttr(*this, Param))
402 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
403 Param->getType();
404
405 if (Param->getIdentifier())
406 PushOnScopeChains(Param, FnBodyScope);
407 }
408
409 // In ARC, disallow definition of retain/release/autorelease/retainCount
410 if (getLangOpts().ObjCAutoRefCount) {
411 switch (MDecl->getMethodFamily()) {
412 case OMF_retain:
413 case OMF_retainCount:
414 case OMF_release:
415 case OMF_autorelease:
416 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
417 << 0 << MDecl->getSelector();
418 break;
419
420 case OMF_None:
421 case OMF_dealloc:
422 case OMF_finalize:
423 case OMF_alloc:
424 case OMF_init:
425 case OMF_mutableCopy:
426 case OMF_copy:
427 case OMF_new:
428 case OMF_self:
429 case OMF_initialize:
431 break;
432 }
433 }
434
435 // Warn on deprecated methods under -Wdeprecated-implementations,
436 // and prepare for warning on missing super calls.
437 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
438 ObjCMethodDecl *IMD =
439 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
440
441 if (IMD) {
442 ObjCImplDecl *ImplDeclOfMethodDef =
443 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
444 ObjCContainerDecl *ContDeclOfMethodDecl =
445 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
446 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
447 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
448 ImplDeclOfMethodDecl = OID->getImplementation();
449 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
450 if (CD->IsClassExtension()) {
451 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
452 ImplDeclOfMethodDecl = OID->getImplementation();
453 } else
454 ImplDeclOfMethodDecl = CD->getImplementation();
455 }
456 // No need to issue deprecated warning if deprecated mehod in class/category
457 // is being implemented in its own implementation (no overriding is involved).
458 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
460 }
461
462 if (MDecl->getMethodFamily() == OMF_init) {
466 IC->getSuperClass() != nullptr;
467 } else if (IC->hasDesignatedInitializers()) {
470 }
471 }
472
473 // If this is "dealloc" or "finalize", set some bit here.
474 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
475 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
476 // Only do this if the current class actually has a superclass.
477 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
478 ObjCMethodFamily Family = MDecl->getMethodFamily();
479 if (Family == OMF_dealloc) {
480 if (!(getLangOpts().ObjCAutoRefCount ||
481 getLangOpts().getGC() == LangOptions::GCOnly))
483
484 } else if (Family == OMF_finalize) {
485 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
487
488 } else {
489 const ObjCMethodDecl *SuperMethod =
490 SuperClass->lookupMethod(MDecl->getSelector(),
491 MDecl->isInstanceMethod());
493 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
494 }
495 }
496 }
497}
498
499namespace {
500
501// Callback to only accept typo corrections that are Objective-C classes.
502// If an ObjCInterfaceDecl* is given to the constructor, then the validation
503// function will reject corrections to that class.
504class ObjCInterfaceValidatorCCC final : public CorrectionCandidateCallback {
505 public:
506 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
507 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
508 : CurrentIDecl(IDecl) {}
509
510 bool ValidateCandidate(const TypoCorrection &candidate) override {
512 return ID && !declaresSameEntity(ID, CurrentIDecl);
513 }
514
515 std::unique_ptr<CorrectionCandidateCallback> clone() override {
516 return std::make_unique<ObjCInterfaceValidatorCCC>(*this);
517 }
518
519 private:
520 ObjCInterfaceDecl *CurrentIDecl;
521};
522
523} // end anonymous namespace
524
525static void diagnoseUseOfProtocols(Sema &TheSema,
527 ObjCProtocolDecl *const *ProtoRefs,
528 unsigned NumProtoRefs,
529 const SourceLocation *ProtoLocs) {
530 assert(ProtoRefs);
531 // Diagnose availability in the context of the ObjC container.
532 Sema::ContextRAII SavedContext(TheSema, CD);
533 for (unsigned i = 0; i < NumProtoRefs; ++i) {
534 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
535 /*UnknownObjCClass=*/nullptr,
536 /*ObjCPropertyAccess=*/false,
537 /*AvoidPartialAvailabilityChecks=*/true);
538 }
539}
540
543 SourceLocation AtInterfaceLoc,
544 ObjCInterfaceDecl *IDecl,
545 IdentifierInfo *ClassName,
546 SourceLocation ClassLoc,
547 IdentifierInfo *SuperName,
548 SourceLocation SuperLoc,
549 ArrayRef<ParsedType> SuperTypeArgs,
550 SourceRange SuperTypeArgsRange) {
551 // Check if a different kind of symbol declared in this scope.
552 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
554
555 if (!PrevDecl) {
556 // Try to correct for a typo in the superclass name without correcting
557 // to the class we're defining.
558 ObjCInterfaceValidatorCCC CCC(IDecl);
559 if (TypoCorrection Corrected = CorrectTypo(
560 DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName,
561 TUScope, nullptr, CCC, CTK_ErrorRecovery)) {
562 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
563 << SuperName << ClassName);
564 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
565 }
566 }
567
568 if (declaresSameEntity(PrevDecl, IDecl)) {
569 Diag(SuperLoc, diag::err_recursive_superclass)
570 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
571 IDecl->setEndOfDefinitionLoc(ClassLoc);
572 } else {
573 ObjCInterfaceDecl *SuperClassDecl =
574 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
575 QualType SuperClassType;
576
577 // Diagnose classes that inherit from deprecated classes.
578 if (SuperClassDecl) {
579 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
580 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
581 }
582
583 if (PrevDecl && !SuperClassDecl) {
584 // The previous declaration was not a class decl. Check if we have a
585 // typedef. If we do, get the underlying class type.
586 if (const TypedefNameDecl *TDecl =
587 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
588 QualType T = TDecl->getUnderlyingType();
589 if (T->isObjCObjectType()) {
590 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
591 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
592 SuperClassType = Context.getTypeDeclType(TDecl);
593
594 // This handles the following case:
595 // @interface NewI @end
596 // typedef NewI DeprI __attribute__((deprecated("blah")))
597 // @interface SI : DeprI /* warn here */ @end
598 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
599 }
600 }
601 }
602
603 // This handles the following case:
604 //
605 // typedef int SuperClass;
606 // @interface MyClass : SuperClass {} @end
607 //
608 if (!SuperClassDecl) {
609 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
610 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
611 }
612 }
613
614 if (!isa_and_nonnull<TypedefNameDecl>(PrevDecl)) {
615 if (!SuperClassDecl)
616 Diag(SuperLoc, diag::err_undef_superclass)
617 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
618 else if (RequireCompleteType(SuperLoc,
619 SuperClassType,
620 diag::err_forward_superclass,
621 SuperClassDecl->getDeclName(),
622 ClassName,
623 SourceRange(AtInterfaceLoc, ClassLoc))) {
624 SuperClassDecl = nullptr;
625 SuperClassType = QualType();
626 }
627 }
628
629 if (SuperClassType.isNull()) {
630 assert(!SuperClassDecl && "Failed to set SuperClassType?");
631 return;
632 }
633
634 // Handle type arguments on the superclass.
635 TypeSourceInfo *SuperClassTInfo = nullptr;
636 if (!SuperTypeArgs.empty()) {
638 S,
639 SuperLoc,
640 CreateParsedType(SuperClassType,
641 nullptr),
642 SuperTypeArgsRange.getBegin(),
643 SuperTypeArgs,
644 SuperTypeArgsRange.getEnd(),
646 { },
647 { },
649 if (!fullSuperClassType.isUsable())
650 return;
651
652 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
653 &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 ObjCTypeParamVariance variance,
668 SourceLocation varianceLoc,
669 unsigned index,
670 IdentifierInfo *paramName,
671 SourceLocation paramLoc,
672 SourceLocation colonLoc,
673 ParsedType parsedTypeBound) {
674 // If there was an explicitly-provided type bound, check it.
675 TypeSourceInfo *typeBoundInfo = nullptr;
676 if (parsedTypeBound) {
677 // The type bound can be any Objective-C pointer type.
678 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
679 if (typeBound->isObjCObjectPointerType()) {
680 // okay
681 } else if (typeBound->isObjCObjectType()) {
682 // The user forgot the * on an Objective-C pointer type, e.g.,
683 // "T : NSView".
685 typeBoundInfo->getTypeLoc().getEndLoc());
686 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
687 diag::err_objc_type_param_bound_missing_pointer)
688 << typeBound << paramName
689 << FixItHint::CreateInsertion(starLoc, " *");
690
691 // Create a new type location builder so we can update the type
692 // location information we have.
693 TypeLocBuilder builder;
694 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
695
696 // Create the Objective-C pointer type.
697 typeBound = Context.getObjCObjectPointerType(typeBound);
699 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
700 newT.setStarLoc(starLoc);
701
702 // Form the new type source information.
703 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
704 } else {
705 // Not a valid type bound.
706 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
707 diag::err_objc_type_param_bound_nonobject)
708 << typeBound << paramName;
709
710 // Forget the bound; we'll default to id later.
711 typeBoundInfo = nullptr;
712 }
713
714 // Type bounds cannot have qualifiers (even indirectly) or explicit
715 // nullability.
716 if (typeBoundInfo) {
717 QualType typeBound = typeBoundInfo->getType();
718 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
719 if (qual || typeBound.hasQualifiers()) {
720 bool diagnosed = false;
721 SourceRange rangeToRemove;
722 if (qual) {
723 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
724 rangeToRemove = attr.getLocalSourceRange();
725 if (attr.getTypePtr()->getImmediateNullability()) {
726 Diag(attr.getBeginLoc(),
727 diag::err_objc_type_param_bound_explicit_nullability)
728 << paramName << typeBound
729 << FixItHint::CreateRemoval(rangeToRemove);
730 diagnosed = true;
731 }
732 }
733 }
734
735 if (!diagnosed) {
736 Diag(qual ? qual.getBeginLoc()
737 : typeBoundInfo->getTypeLoc().getBeginLoc(),
738 diag::err_objc_type_param_bound_qualified)
739 << paramName << typeBound
740 << typeBound.getQualifiers().getAsString()
741 << FixItHint::CreateRemoval(rangeToRemove);
742 }
743
744 // If the type bound has qualifiers other than CVR, we need to strip
745 // them or we'll probably assert later when trying to apply new
746 // qualifiers.
747 Qualifiers quals = typeBound.getQualifiers();
748 quals.removeCVRQualifiers();
749 if (!quals.empty()) {
750 typeBoundInfo =
752 }
753 }
754 }
755 }
756
757 // If there was no explicit type bound (or we removed it due to an error),
758 // use 'id' instead.
759 if (!typeBoundInfo) {
760 colonLoc = SourceLocation();
762 }
763
764 // Create the type parameter.
765 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
766 index, paramLoc, paramName, colonLoc,
767 typeBoundInfo);
768}
769
771 SourceLocation lAngleLoc,
772 ArrayRef<Decl *> typeParamsIn,
773 SourceLocation rAngleLoc) {
774 // We know that the array only contains Objective-C type parameters.
776 typeParams(
777 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
778 typeParamsIn.size());
779
780 // Diagnose redeclarations of type parameters.
781 // We do this now because Objective-C type parameters aren't pushed into
782 // scope until later (after the instance variable block), but we want the
783 // diagnostics to occur right after we parse the type parameter list.
784 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
785 for (auto *typeParam : typeParams) {
786 auto known = knownParams.find(typeParam->getIdentifier());
787 if (known != knownParams.end()) {
788 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
789 << typeParam->getIdentifier()
790 << SourceRange(known->second->getLocation());
791
792 typeParam->setInvalidDecl();
793 } else {
794 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
795
796 // Push the type parameter into scope.
797 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
798 }
799 }
800
801 // Create the parameter list.
802 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
803}
804
806 for (auto *typeParam : *typeParamList) {
807 if (!typeParam->isInvalidDecl()) {
808 S->RemoveDecl(typeParam);
809 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 // Check for another declaration kind with the same name.
985 NamedDecl *PrevDecl =
986 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
988
989 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
990 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
991 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
992 }
993
994 // Create a declaration to describe this @interface.
995 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
996
997 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
998 // A previous decl with a different name is because of
999 // @compatibility_alias, for example:
1000 // \code
1001 // @class NewImage;
1002 // @compatibility_alias OldImage NewImage;
1003 // \endcode
1004 // A lookup for 'OldImage' will return the 'NewImage' decl.
1005 //
1006 // In such a case use the real declaration name, instead of the alias one,
1007 // otherwise we will break IdentifierResolver and redecls-chain invariants.
1008 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1009 // has been aliased.
1010 ClassName = PrevIDecl->getIdentifier();
1011 }
1012
1013 // If there was a forward declaration with type parameters, check
1014 // for consistency.
1015 if (PrevIDecl) {
1016 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1017 if (typeParamList) {
1018 // Both have type parameter lists; check for consistency.
1019 if (checkTypeParamListConsistency(*this, prevTypeParamList,
1020 typeParamList,
1021 TypeParamListContext::Definition)) {
1022 typeParamList = nullptr;
1023 }
1024 } else {
1025 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1026 << ClassName;
1027 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1028 << ClassName;
1029
1030 // Clone the type parameter list.
1031 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1032 for (auto *typeParam : *prevTypeParamList) {
1033 clonedTypeParams.push_back(
1035 Context,
1036 CurContext,
1037 typeParam->getVariance(),
1039 typeParam->getIndex(),
1041 typeParam->getIdentifier(),
1043 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1044 }
1045
1046 typeParamList = ObjCTypeParamList::create(Context,
1048 clonedTypeParams,
1049 SourceLocation());
1050 }
1051 }
1052 }
1053
1054 ObjCInterfaceDecl *IDecl
1055 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
1056 typeParamList, PrevIDecl, ClassLoc);
1057 if (PrevIDecl) {
1058 // Class already seen. Was it a definition?
1059 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1060 if (SkipBody && !hasVisibleDefinition(Def)) {
1061 SkipBody->CheckSameAsPrevious = true;
1062 SkipBody->New = IDecl;
1063 SkipBody->Previous = Def;
1064 } else {
1065 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1066 << PrevIDecl->getDeclName();
1067 Diag(Def->getLocation(), diag::note_previous_definition);
1068 IDecl->setInvalidDecl();
1069 }
1070 }
1071 }
1072
1073 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
1075 ProcessAPINotes(IDecl);
1076
1077 // Merge attributes from previous declarations.
1078 if (PrevIDecl)
1079 mergeDeclAttributes(IDecl, PrevIDecl);
1080
1081 PushOnScopeChains(IDecl, TUScope);
1082
1083 // Start the definition of this class. If we're in a redefinition case, there
1084 // may already be a definition, so we'll end up adding to it.
1085 if (SkipBody && SkipBody->CheckSameAsPrevious)
1087 else if (!IDecl->hasDefinition())
1088 IDecl->startDefinition();
1089
1090 if (SuperName) {
1091 // Diagnose availability in the context of the @interface.
1092 ContextRAII SavedContext(*this, IDecl);
1093
1094 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1095 ClassName, ClassLoc,
1096 SuperName, SuperLoc, SuperTypeArgs,
1097 SuperTypeArgsRange);
1098 } else { // we have a root class.
1099 IDecl->setEndOfDefinitionLoc(ClassLoc);
1100 }
1101
1102 // Check then save referenced protocols.
1103 if (NumProtoRefs) {
1104 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1105 NumProtoRefs, ProtoLocs);
1106 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1107 ProtoLocs, Context);
1108 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
1109 }
1110
1111 CheckObjCDeclScope(IDecl);
1113 return IDecl;
1114}
1115
1116/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1117/// typedef'ed use for a qualified super class and adds them to the list
1118/// of the protocols.
1120 SmallVectorImpl<SourceLocation> &ProtocolLocs,
1121 IdentifierInfo *SuperName,
1122 SourceLocation SuperLoc) {
1123 if (!SuperName)
1124 return;
1125 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1127 if (!IDecl)
1128 return;
1129
1130 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1131 QualType T = TDecl->getUnderlyingType();
1132 if (T->isObjCObjectType())
1133 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
1134 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
1135 // FIXME: Consider whether this should be an invalid loc since the loc
1136 // is not actually pointing to a protocol name reference but to the
1137 // typedef reference. Note that the base class name loc is also pointing
1138 // at the typedef.
1139 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1140 }
1141 }
1142}
1143
1144/// ActOnCompatibilityAlias - this action is called after complete parsing of
1145/// a \@compatibility_alias declaration. It sets up the alias relationships.
1147 IdentifierInfo *AliasName,
1148 SourceLocation AliasLocation,
1149 IdentifierInfo *ClassName,
1150 SourceLocation ClassLocation) {
1151 // Look for previous declaration of alias name
1152 NamedDecl *ADecl =
1153 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1155 if (ADecl) {
1156 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
1157 Diag(ADecl->getLocation(), diag::note_previous_declaration);
1158 return nullptr;
1159 }
1160 // Check for class declaration
1161 NamedDecl *CDeclU =
1162 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1164 if (const TypedefNameDecl *TDecl =
1165 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
1166 QualType T = TDecl->getUnderlyingType();
1167 if (T->isObjCObjectType()) {
1168 if (NamedDecl *IDecl = T->castAs<ObjCObjectType>()->getInterface()) {
1169 ClassName = IDecl->getIdentifier();
1170 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
1173 }
1174 }
1175 }
1176 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
1177 if (!CDecl) {
1178 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
1179 if (CDeclU)
1180 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
1181 return nullptr;
1182 }
1183
1184 // Everything checked out, instantiate a new alias declaration AST.
1186 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
1187
1190
1191 return AliasDecl;
1192}
1193
1195 IdentifierInfo *PName,
1196 SourceLocation &Ploc, SourceLocation PrevLoc,
1197 const ObjCList<ObjCProtocolDecl> &PList) {
1198
1199 bool res = false;
1201 E = PList.end(); I != E; ++I) {
1202 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1203 Ploc)) {
1204 if (PDecl->getIdentifier() == PName) {
1205 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1206 Diag(PrevLoc, diag::note_previous_definition);
1207 res = true;
1208 }
1209
1210 if (!PDecl->hasDefinition())
1211 continue;
1212
1214 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1215 res = true;
1216 }
1217 }
1218 return res;
1219}
1220
1222 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1223 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1224 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1225 const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody) {
1226 bool err = false;
1227 // FIXME: Deal with AttrList.
1228 assert(ProtocolName && "Missing protocol identifier");
1229 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
1231 ObjCProtocolDecl *PDecl = nullptr;
1232 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
1233 // Create a new protocol that is completely distinct from previous
1234 // declarations, and do not make this protocol available for name lookup.
1235 // That way, we'll end up completely ignoring the duplicate.
1236 // FIXME: Can we turn this into an error?
1237 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1238 ProtocolLoc, AtProtoInterfaceLoc,
1239 /*PrevDecl=*/Def);
1240
1241 if (SkipBody && !hasVisibleDefinition(Def)) {
1242 SkipBody->CheckSameAsPrevious = true;
1243 SkipBody->New = PDecl;
1244 SkipBody->Previous = Def;
1245 } else {
1246 // If we already have a definition, complain.
1247 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1248 Diag(Def->getLocation(), diag::note_previous_definition);
1249 }
1250
1251 // If we are using modules, add the decl to the context in order to
1252 // serialize something meaningful.
1253 if (getLangOpts().Modules)
1254 PushOnScopeChains(PDecl, TUScope);
1256 } else {
1257 if (PrevDecl) {
1258 // Check for circular dependencies among protocol declarations. This can
1259 // only happen if this protocol was forward-declared.
1261 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1263 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
1264 }
1265
1266 // Create the new declaration.
1267 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1268 ProtocolLoc, AtProtoInterfaceLoc,
1269 /*PrevDecl=*/PrevDecl);
1270
1271 PushOnScopeChains(PDecl, TUScope);
1272 PDecl->startDefinition();
1273 }
1274
1275 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
1277 ProcessAPINotes(PDecl);
1278
1279 // Merge attributes from previous declarations.
1280 if (PrevDecl)
1281 mergeDeclAttributes(PDecl, PrevDecl);
1282
1283 if (!err && NumProtoRefs ) {
1284 /// Check then save referenced protocols.
1285 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1286 NumProtoRefs, ProtoLocs);
1287 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1288 ProtoLocs, Context);
1289 }
1290
1291 CheckObjCDeclScope(PDecl);
1293 return PDecl;
1294}
1295
1297 ObjCProtocolDecl *&UndefinedProtocol) {
1298 if (!PDecl->hasDefinition() ||
1300 UndefinedProtocol = PDecl;
1301 return true;
1302 }
1303
1304 for (auto *PI : PDecl->protocols())
1305 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1306 UndefinedProtocol = PI;
1307 return true;
1308 }
1309 return false;
1310}
1311
1312/// FindProtocolDeclaration - This routine looks up protocols and
1313/// issues an error if they are not declared. It returns list of
1314/// protocol declarations in its 'Protocols' argument.
1315void
1316Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
1317 ArrayRef<IdentifierLocPair> ProtocolId,
1318 SmallVectorImpl<Decl *> &Protocols) {
1319 for (const IdentifierLocPair &Pair : ProtocolId) {
1320 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
1321 if (!PDecl) {
1323 TypoCorrection Corrected = CorrectTypo(
1324 DeclarationNameInfo(Pair.first, Pair.second), LookupObjCProtocolName,
1325 TUScope, nullptr, CCC, CTK_ErrorRecovery);
1326 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1327 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
1328 << Pair.first);
1329 }
1330
1331 if (!PDecl) {
1332 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
1333 continue;
1334 }
1335 // If this is a forward protocol declaration, get its definition.
1336 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1337 PDecl = PDecl->getDefinition();
1338
1339 // For an objc container, delay protocol reference checking until after we
1340 // can set the objc decl as the availability context, otherwise check now.
1341 if (!ForObjCContainer) {
1342 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
1343 }
1344
1345 // If this is a forward declaration and we are supposed to warn in this
1346 // case, do it.
1347 // FIXME: Recover nicely in the hidden case.
1348 ObjCProtocolDecl *UndefinedProtocol;
1349
1350 if (WarnOnDeclarations &&
1351 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
1352 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
1353 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1354 << UndefinedProtocol;
1355 }
1356 Protocols.push_back(PDecl);
1357 }
1358}
1359
1360namespace {
1361// Callback to only accept typo corrections that are either
1362// Objective-C protocols or valid Objective-C type arguments.
1363class ObjCTypeArgOrProtocolValidatorCCC final
1365 ASTContext &Context;
1366 Sema::LookupNameKind LookupKind;
1367 public:
1368 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1369 Sema::LookupNameKind lookupKind)
1370 : Context(context), LookupKind(lookupKind) { }
1371
1372 bool ValidateCandidate(const TypoCorrection &candidate) override {
1373 // If we're allowed to find protocols and we have a protocol, accept it.
1374 if (LookupKind != Sema::LookupOrdinaryName) {
1375 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1376 return true;
1377 }
1378
1379 // If we're allowed to find type names and we have one, accept it.
1380 if (LookupKind != Sema::LookupObjCProtocolName) {
1381 // If we have a type declaration, we might accept this result.
1382 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1383 // If we found a tag declaration outside of C++, skip it. This
1384 // can happy because we look for any name when there is no
1385 // bias to protocol or type names.
1386 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1387 return false;
1388
1389 // Make sure the type is something we would accept as a type
1390 // argument.
1391 auto type = Context.getTypeDeclType(typeDecl);
1392 if (type->isObjCObjectPointerType() ||
1393 type->isBlockPointerType() ||
1394 type->isDependentType() ||
1395 type->isObjCObjectType())
1396 return true;
1397
1398 return false;
1399 }
1400
1401 // If we have an Objective-C class type, accept it; there will
1402 // be another fix to add the '*'.
1403 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1404 return true;
1405
1406 return false;
1407 }
1408
1409 return false;
1410 }
1411
1412 std::unique_ptr<CorrectionCandidateCallback> clone() override {
1413 return std::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(*this);
1414 }
1415};
1416} // end anonymous namespace
1417
1419 SourceLocation ProtocolLoc,
1420 IdentifierInfo *TypeArgId,
1421 SourceLocation TypeArgLoc,
1422 bool SelectProtocolFirst) {
1423 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1424 << SelectProtocolFirst << TypeArgId << ProtocolId
1425 << SourceRange(ProtocolLoc);
1426}
1427
1429 Scope *S,
1430 ParsedType baseType,
1431 SourceLocation lAngleLoc,
1432 ArrayRef<IdentifierInfo *> identifiers,
1433 ArrayRef<SourceLocation> identifierLocs,
1434 SourceLocation rAngleLoc,
1435 SourceLocation &typeArgsLAngleLoc,
1437 SourceLocation &typeArgsRAngleLoc,
1438 SourceLocation &protocolLAngleLoc,
1439 SmallVectorImpl<Decl *> &protocols,
1440 SourceLocation &protocolRAngleLoc,
1441 bool warnOnIncompleteProtocols) {
1442 // Local function that updates the declaration specifiers with
1443 // protocol information.
1444 unsigned numProtocolsResolved = 0;
1445 auto resolvedAsProtocols = [&] {
1446 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1447
1448 // Determine whether the base type is a parameterized class, in
1449 // which case we want to warn about typos such as
1450 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1451 ObjCInterfaceDecl *baseClass = nullptr;
1452 QualType base = GetTypeFromParser(baseType, nullptr);
1453 bool allAreTypeNames = false;
1454 SourceLocation firstClassNameLoc;
1455 if (!base.isNull()) {
1456 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1457 baseClass = objcObjectType->getInterface();
1458 if (baseClass) {
1459 if (auto typeParams = baseClass->getTypeParamList()) {
1460 if (typeParams->size() == numProtocolsResolved) {
1461 // Note that we should be looking for type names, too.
1462 allAreTypeNames = true;
1463 }
1464 }
1465 }
1466 }
1467 }
1468
1469 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
1470 ObjCProtocolDecl *&proto
1471 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
1472 // For an objc container, delay protocol reference checking until after we
1473 // can set the objc decl as the availability context, otherwise check now.
1474 if (!warnOnIncompleteProtocols) {
1475 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1476 }
1477
1478 // If this is a forward protocol declaration, get its definition.
1479 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1480 proto = proto->getDefinition();
1481
1482 // If this is a forward declaration and we are supposed to warn in this
1483 // case, do it.
1484 // FIXME: Recover nicely in the hidden case.
1485 ObjCProtocolDecl *forwardDecl = nullptr;
1486 if (warnOnIncompleteProtocols &&
1487 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1488 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1489 << proto->getDeclName();
1490 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1491 << forwardDecl;
1492 }
1493
1494 // If everything this far has been a type name (and we care
1495 // about such things), check whether this name refers to a type
1496 // as well.
1497 if (allAreTypeNames) {
1498 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1500 if (isa<ObjCInterfaceDecl>(decl)) {
1501 if (firstClassNameLoc.isInvalid())
1502 firstClassNameLoc = identifierLocs[i];
1503 } else if (!isa<TypeDecl>(decl)) {
1504 // Not a type.
1505 allAreTypeNames = false;
1506 }
1507 } else {
1508 allAreTypeNames = false;
1509 }
1510 }
1511 }
1512
1513 // All of the protocols listed also have type names, and at least
1514 // one is an Objective-C class name. Check whether all of the
1515 // protocol conformances are declared by the base class itself, in
1516 // which case we warn.
1517 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1519 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1520 bool allProtocolsDeclared = true;
1521 for (auto *proto : protocols) {
1522 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1523 allProtocolsDeclared = false;
1524 break;
1525 }
1526 }
1527
1528 if (allProtocolsDeclared) {
1529 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1530 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
1531 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1532 " *");
1533 }
1534 }
1535
1536 protocolLAngleLoc = lAngleLoc;
1537 protocolRAngleLoc = rAngleLoc;
1538 assert(protocols.size() == identifierLocs.size());
1539 };
1540
1541 // Attempt to resolve all of the identifiers as protocols.
1542 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1543 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1544 protocols.push_back(proto);
1545 if (proto)
1546 ++numProtocolsResolved;
1547 }
1548
1549 // If all of the names were protocols, these were protocol qualifiers.
1550 if (numProtocolsResolved == identifiers.size())
1551 return resolvedAsProtocols();
1552
1553 // Attempt to resolve all of the identifiers as type names or
1554 // Objective-C class names. The latter is technically ill-formed,
1555 // but is probably something like \c NSArray<NSView *> missing the
1556 // \c*.
1557 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1559 unsigned numTypeDeclsResolved = 0;
1560 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1561 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1563 if (!decl) {
1564 typeDecls.push_back(TypeOrClassDecl());
1565 continue;
1566 }
1567
1568 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1569 typeDecls.push_back(typeDecl);
1570 ++numTypeDeclsResolved;
1571 continue;
1572 }
1573
1574 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1575 typeDecls.push_back(objcClass);
1576 ++numTypeDeclsResolved;
1577 continue;
1578 }
1579
1580 typeDecls.push_back(TypeOrClassDecl());
1581 }
1582
1583 AttributeFactory attrFactory;
1584
1585 // Local function that forms a reference to the given type or
1586 // Objective-C class declaration.
1587 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1588 -> TypeResult {
1589 // Form declaration specifiers. They simply refer to the type.
1590 DeclSpec DS(attrFactory);
1591 const char* prevSpec; // unused
1592 unsigned diagID; // unused
1593 QualType type;
1594 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1595 type = Context.getTypeDeclType(actualTypeDecl);
1596 else
1599 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1600 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1601 parsedType, Context.getPrintingPolicy());
1602 // Use the identifier location for the type source range.
1603 DS.SetRangeStart(loc);
1604 DS.SetRangeEnd(loc);
1605
1606 // Form the declarator.
1608
1609 // If we have a typedef of an Objective-C class type that is missing a '*',
1610 // add the '*'.
1611 if (type->getAs<ObjCInterfaceType>()) {
1612 SourceLocation starLoc = getLocForEndOfToken(loc);
1613 D.AddTypeInfo(DeclaratorChunk::getPointer(/*TypeQuals=*/0, starLoc,
1618 SourceLocation()),
1619 starLoc);
1620
1621 // Diagnose the missing '*'.
1622 Diag(loc, diag::err_objc_type_arg_missing_star)
1623 << type
1624 << FixItHint::CreateInsertion(starLoc, " *");
1625 }
1626
1627 // Convert this to a type.
1628 return ActOnTypeName(D);
1629 };
1630
1631 // Local function that updates the declaration specifiers with
1632 // type argument information.
1633 auto resolvedAsTypeDecls = [&] {
1634 // We did not resolve these as protocols.
1635 protocols.clear();
1636
1637 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1638 // Map type declarations to type arguments.
1639 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1640 // Map type reference to a type.
1641 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
1642 if (!type.isUsable()) {
1643 typeArgs.clear();
1644 return;
1645 }
1646
1647 typeArgs.push_back(type.get());
1648 }
1649
1650 typeArgsLAngleLoc = lAngleLoc;
1651 typeArgsRAngleLoc = rAngleLoc;
1652 };
1653
1654 // If all of the identifiers can be resolved as type names or
1655 // Objective-C class names, we have type arguments.
1656 if (numTypeDeclsResolved == identifiers.size())
1657 return resolvedAsTypeDecls();
1658
1659 // Error recovery: some names weren't found, or we have a mix of
1660 // type and protocol names. Go resolve all of the unresolved names
1661 // and complain if we can't find a consistent answer.
1662 LookupNameKind lookupKind = LookupAnyName;
1663 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1664 // If we already have a protocol or type. Check whether it is the
1665 // right thing.
1666 if (protocols[i] || typeDecls[i]) {
1667 // If we haven't figured out whether we want types or protocols
1668 // yet, try to figure it out from this name.
1669 if (lookupKind == LookupAnyName) {
1670 // If this name refers to both a protocol and a type (e.g., \c
1671 // NSObject), don't conclude anything yet.
1672 if (protocols[i] && typeDecls[i])
1673 continue;
1674
1675 // Otherwise, let this name decide whether we'll be correcting
1676 // toward types or protocols.
1677 lookupKind = protocols[i] ? LookupObjCProtocolName
1679 continue;
1680 }
1681
1682 // If we want protocols and we have a protocol, there's nothing
1683 // more to do.
1684 if (lookupKind == LookupObjCProtocolName && protocols[i])
1685 continue;
1686
1687 // If we want types and we have a type declaration, there's
1688 // nothing more to do.
1689 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1690 continue;
1691
1692 // We have a conflict: some names refer to protocols and others
1693 // refer to types.
1694 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1695 identifiers[i], identifierLocs[i],
1696 protocols[i] != nullptr);
1697
1698 protocols.clear();
1699 typeArgs.clear();
1700 return;
1701 }
1702
1703 // Perform typo correction on the name.
1704 ObjCTypeArgOrProtocolValidatorCCC CCC(Context, lookupKind);
1705 TypoCorrection corrected =
1706 CorrectTypo(DeclarationNameInfo(identifiers[i], identifierLocs[i]),
1707 lookupKind, S, nullptr, CCC, CTK_ErrorRecovery);
1708 if (corrected) {
1709 // Did we find a protocol?
1710 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1711 diagnoseTypo(corrected,
1712 PDiag(diag::err_undeclared_protocol_suggest)
1713 << identifiers[i]);
1714 lookupKind = LookupObjCProtocolName;
1715 protocols[i] = proto;
1716 ++numProtocolsResolved;
1717 continue;
1718 }
1719
1720 // Did we find a type?
1721 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1722 diagnoseTypo(corrected,
1723 PDiag(diag::err_unknown_typename_suggest)
1724 << identifiers[i]);
1725 lookupKind = LookupOrdinaryName;
1726 typeDecls[i] = typeDecl;
1727 ++numTypeDeclsResolved;
1728 continue;
1729 }
1730
1731 // Did we find an Objective-C class?
1732 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1733 diagnoseTypo(corrected,
1734 PDiag(diag::err_unknown_type_or_class_name_suggest)
1735 << identifiers[i] << true);
1736 lookupKind = LookupOrdinaryName;
1737 typeDecls[i] = objcClass;
1738 ++numTypeDeclsResolved;
1739 continue;
1740 }
1741 }
1742
1743 // We couldn't find anything.
1744 Diag(identifierLocs[i],
1745 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1746 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1747 : diag::err_unknown_typename))
1748 << identifiers[i];
1749 protocols.clear();
1750 typeArgs.clear();
1751 return;
1752 }
1753
1754 // If all of the names were (corrected to) protocols, these were
1755 // protocol qualifiers.
1756 if (numProtocolsResolved == identifiers.size())
1757 return resolvedAsProtocols();
1758
1759 // Otherwise, all of the names were (corrected to) types.
1760 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1761 return resolvedAsTypeDecls();
1762}
1763
1764/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
1765/// a class method in its extension.
1766///
1768 ObjCInterfaceDecl *ID) {
1769 if (!ID)
1770 return; // Possibly due to previous error
1771
1772 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
1773 for (auto *MD : ID->methods())
1774 MethodMap[MD->getSelector()] = MD;
1775
1776 if (MethodMap.empty())
1777 return;
1778 for (const auto *Method : CAT->methods()) {
1779 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
1780 if (PrevMethod &&
1781 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1782 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
1783 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1784 << Method->getDeclName();
1785 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1786 }
1787 }
1788}
1789
1790/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
1794 const ParsedAttributesView &attrList) {
1795 SmallVector<Decl *, 8> DeclsInGroup;
1796 for (const IdentifierLocPair &IdentPair : IdentList) {
1797 IdentifierInfo *Ident = IdentPair.first;
1798 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
1800 ObjCProtocolDecl *PDecl
1802 IdentPair.second, AtProtocolLoc,
1803 PrevDecl);
1804
1805 PushOnScopeChains(PDecl, TUScope);
1806 CheckObjCDeclScope(PDecl);
1807
1808 ProcessDeclAttributeList(TUScope, PDecl, attrList);
1810
1811 if (PrevDecl)
1812 mergeDeclAttributes(PDecl, PrevDecl);
1813
1814 DeclsInGroup.push_back(PDecl);
1815 }
1816
1817 return BuildDeclaratorGroup(DeclsInGroup);
1818}
1819
1821 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1822 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1823 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1824 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1825 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1826 const ParsedAttributesView &AttrList) {
1827 ObjCCategoryDecl *CDecl;
1828 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1829
1830 /// Check that class of this category is already completely declared.
1831
1832 if (!IDecl
1834 diag::err_category_forward_interface,
1835 CategoryName == nullptr)) {
1836 // Create an invalid ObjCCategoryDecl to serve as context for
1837 // the enclosing method declarations. We mark the decl invalid
1838 // to make it clear that this isn't a valid AST.
1839 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1840 ClassLoc, CategoryLoc, CategoryName,
1841 IDecl, typeParamList);
1842 CDecl->setInvalidDecl();
1843 CurContext->addDecl(CDecl);
1844
1845 if (!IDecl)
1846 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1848 return CDecl;
1849 }
1850
1851 if (!CategoryName && IDecl->getImplementation()) {
1852 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1854 diag::note_implementation_declared);
1855 }
1856
1857 if (CategoryName) {
1858 /// Check for duplicate interface declaration for this category
1860 = IDecl->FindCategoryDeclaration(CategoryName)) {
1861 // Class extensions can be declared multiple times, categories cannot.
1862 Diag(CategoryLoc, diag::warn_dup_category_def)
1863 << ClassName << CategoryName;
1864 Diag(Previous->getLocation(), diag::note_previous_definition);
1865 }
1866 }
1867
1868 // If we have a type parameter list, check it.
1869 if (typeParamList) {
1870 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1871 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1872 CategoryName
1873 ? TypeParamListContext::Category
1874 : TypeParamListContext::Extension))
1875 typeParamList = nullptr;
1876 } else {
1877 Diag(typeParamList->getLAngleLoc(),
1878 diag::err_objc_parameterized_category_nonclass)
1879 << (CategoryName != nullptr)
1880 << ClassName
1881 << typeParamList->getSourceRange();
1882
1883 typeParamList = nullptr;
1884 }
1885 }
1886
1887 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
1888 ClassLoc, CategoryLoc, CategoryName, IDecl,
1889 typeParamList);
1890 // FIXME: PushOnScopeChains?
1891 CurContext->addDecl(CDecl);
1892
1893 // Process the attributes before looking at protocols to ensure that the
1894 // availability attribute is attached to the category to provide availability
1895 // checking for protocol uses.
1896 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
1898
1899 if (NumProtoRefs) {
1900 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1901 NumProtoRefs, ProtoLocs);
1902 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
1903 ProtoLocs, Context);
1904 // Protocols in the class extension belong to the class.
1905 if (CDecl->IsClassExtension())
1906 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1907 NumProtoRefs, Context);
1908 }
1909
1910 CheckObjCDeclScope(CDecl);
1912 return CDecl;
1913}
1914
1915/// ActOnStartCategoryImplementation - Perform semantic checks on the
1916/// category implementation declaration and build an ObjCCategoryImplDecl
1917/// object.
1919 SourceLocation AtCatImplLoc, IdentifierInfo *ClassName,
1920 SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc,
1921 const ParsedAttributesView &Attrs) {
1922 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
1923 ObjCCategoryDecl *CatIDecl = nullptr;
1924 if (IDecl && IDecl->hasDefinition()) {
1925 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1926 if (!CatIDecl) {
1927 // Category @implementation with no corresponding @interface.
1928 // Create and install one.
1929 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1930 ClassLoc, CatLoc,
1931 CatName, IDecl,
1932 /*typeParamList=*/nullptr);
1933 CatIDecl->setImplicit();
1934 }
1935 }
1936
1937 ObjCCategoryImplDecl *CDecl =
1939 ClassLoc, AtCatImplLoc, CatLoc);
1940 /// Check that class of this category is already completely declared.
1941 if (!IDecl) {
1942 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
1943 CDecl->setInvalidDecl();
1944 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1945 diag::err_undef_interface)) {
1946 CDecl->setInvalidDecl();
1947 }
1948
1949 ProcessDeclAttributeList(TUScope, CDecl, Attrs);
1951
1952 // FIXME: PushOnScopeChains?
1953 CurContext->addDecl(CDecl);
1954
1955 // If the interface has the objc_runtime_visible attribute, we
1956 // cannot implement a category for it.
1957 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1958 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1959 << IDecl->getDeclName();
1960 }
1961
1962 /// Check that CatName, category name, is not used in another implementation.
1963 if (CatIDecl) {
1964 if (CatIDecl->getImplementation()) {
1965 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1966 << CatName;
1967 Diag(CatIDecl->getImplementation()->getLocation(),
1968 diag::note_previous_definition);
1969 CDecl->setInvalidDecl();
1970 } else {
1971 CatIDecl->setImplementation(CDecl);
1972 // Warn on implementating category of deprecated class under
1973 // -Wdeprecated-implementations flag.
1975 CDecl->getLocation());
1976 }
1977 }
1978
1979 CheckObjCDeclScope(CDecl);
1981 return CDecl;
1982}
1983
1985 SourceLocation AtClassImplLoc, IdentifierInfo *ClassName,
1986 SourceLocation ClassLoc, IdentifierInfo *SuperClassname,
1987 SourceLocation SuperClassLoc, const ParsedAttributesView &Attrs) {
1988 ObjCInterfaceDecl *IDecl = nullptr;
1989 // Check for another declaration kind with the same name.
1990 NamedDecl *PrevDecl
1991 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1993 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1994 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1995 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1996 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1997 // FIXME: This will produce an error if the definition of the interface has
1998 // been imported from a module but is not visible.
2000 diag::warn_undef_interface);
2001 } else {
2002 // We did not find anything with the name ClassName; try to correct for
2003 // typos in the class name.
2004 ObjCInterfaceValidatorCCC CCC{};
2005 TypoCorrection Corrected =
2006 CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
2007 LookupOrdinaryName, TUScope, nullptr, CCC, CTK_NonError);
2008 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
2009 // Suggest the (potentially) correct interface name. Don't provide a
2010 // code-modification hint or use the typo name for recovery, because
2011 // this is just a warning. The program may actually be correct.
2012 diagnoseTypo(Corrected,
2013 PDiag(diag::warn_undef_interface_suggest) << ClassName,
2014 /*ErrorRecovery*/false);
2015 } else {
2016 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
2017 }
2018 }
2019
2020 // Check that super class name is valid class name
2021 ObjCInterfaceDecl *SDecl = nullptr;
2022 if (SuperClassname) {
2023 // Check if a different kind of symbol declared in this scope.
2024 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
2026 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2027 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
2028 << SuperClassname;
2029 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2030 } else {
2031 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2032 if (SDecl && !SDecl->hasDefinition())
2033 SDecl = nullptr;
2034 if (!SDecl)
2035 Diag(SuperClassLoc, diag::err_undef_superclass)
2036 << SuperClassname << ClassName;
2037 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
2038 // This implementation and its interface do not have the same
2039 // super class.
2040 Diag(SuperClassLoc, diag::err_conflicting_super_class)
2041 << SDecl->getDeclName();
2042 Diag(SDecl->getLocation(), diag::note_previous_definition);
2043 }
2044 }
2045 }
2046
2047 if (!IDecl) {
2048 // Legacy case of @implementation with no corresponding @interface.
2049 // Build, chain & install the interface decl into the identifier.
2050
2051 // FIXME: Do we support attributes on the @implementation? If so we should
2052 // copy them over.
2053 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
2054 ClassName, /*typeParamList=*/nullptr,
2055 /*PrevDecl=*/nullptr, ClassLoc,
2056 true);
2058 IDecl->startDefinition();
2059 if (SDecl) {
2062 SuperClassLoc));
2063 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2064 } else {
2065 IDecl->setEndOfDefinitionLoc(ClassLoc);
2066 }
2067
2068 PushOnScopeChains(IDecl, TUScope);
2069 } else {
2070 // Mark the interface as being completed, even if it was just as
2071 // @class ....;
2072 // declaration; the user cannot reopen it.
2073 if (!IDecl->hasDefinition())
2074 IDecl->startDefinition();
2075 }
2076
2077 ObjCImplementationDecl* IMPDecl =
2079 ClassLoc, AtClassImplLoc, SuperClassLoc);
2080
2081 ProcessDeclAttributeList(TUScope, IMPDecl, Attrs);
2082 AddPragmaAttributes(TUScope, IMPDecl);
2083
2084 if (CheckObjCDeclScope(IMPDecl)) {
2086 return IMPDecl;
2087 }
2088
2089 // Check that there is no duplicate implementation of this class.
2090 if (IDecl->getImplementation()) {
2091 // FIXME: Don't leak everything!
2092 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
2094 diag::note_previous_definition);
2095 IMPDecl->setInvalidDecl();
2096 } else { // add it to the list.
2097 IDecl->setImplementation(IMPDecl);
2098 PushOnScopeChains(IMPDecl, TUScope);
2099 // Warn on implementating deprecated class under
2100 // -Wdeprecated-implementations flag.
2101 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
2102 }
2103
2104 // If the superclass has the objc_runtime_visible attribute, we
2105 // cannot implement a subclass of it.
2106 if (IDecl->getSuperClass() &&
2107 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2108 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2109 << IDecl->getDeclName()
2110 << IDecl->getSuperClass()->getDeclName();
2111 }
2112
2114 return IMPDecl;
2115}
2116
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 BuildDeclaratorGroup(DeclsInGroup);
2134}
2135
2137 ObjCIvarDecl **ivars, unsigned numIvars,
2138 SourceLocation RBrace) {
2139 assert(ImpDecl && "missing implementation decl");
2140 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
2141 if (!IDecl)
2142 return;
2143 /// Check case of non-existing \@interface decl.
2144 /// (legacy objective-c \@implementation decl without an \@interface decl).
2145 /// Add implementations's ivar to the synthesize class's ivar list.
2146 if (IDecl->isImplicitInterfaceDecl()) {
2147 IDecl->setEndOfDefinitionLoc(RBrace);
2148 // Add ivar's to class's DeclContext.
2149 for (unsigned i = 0, e = numIvars; i != e; ++i) {
2150 ivars[i]->setLexicalDeclContext(ImpDecl);
2151 // In a 'fragile' runtime the ivar was added to the implicit
2152 // ObjCInterfaceDecl while in a 'non-fragile' runtime the ivar is
2153 // only in the ObjCImplementationDecl. In the non-fragile case the ivar
2154 // therefore also needs to be propagated to the ObjCInterfaceDecl.
2156 IDecl->makeDeclVisibleInContext(ivars[i]);
2157 ImpDecl->addDecl(ivars[i]);
2158 }
2159
2160 return;
2161 }
2162 // If implementation has empty ivar list, just return.
2163 if (numIvars == 0)
2164 return;
2165
2166 assert(ivars && "missing @implementation ivars");
2168 if (ImpDecl->getSuperClass())
2169 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2170 for (unsigned i = 0; i < numIvars; i++) {
2171 ObjCIvarDecl* ImplIvar = ivars[i];
2172 if (const ObjCIvarDecl *ClsIvar =
2173 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2174 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2175 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2176 continue;
2177 }
2178 // Check class extensions (unnamed categories) for duplicate ivars.
2179 for (const auto *CDecl : IDecl->visible_extensions()) {
2180 if (const ObjCIvarDecl *ClsExtIvar =
2181 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2182 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2183 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2184 continue;
2185 }
2186 }
2187 // Instance ivar to Implementation's DeclContext.
2188 ImplIvar->setLexicalDeclContext(ImpDecl);
2189 IDecl->makeDeclVisibleInContext(ImplIvar);
2190 ImpDecl->addDecl(ImplIvar);
2191 }
2192 return;
2193 }
2194 // Check interface's Ivar list against those in the implementation.
2195 // names and types must match.
2196 //
2197 unsigned j = 0;
2199 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2200 for (; numIvars > 0 && IVI != IVE; ++IVI) {
2201 ObjCIvarDecl* ImplIvar = ivars[j++];
2202 ObjCIvarDecl* ClsIvar = *IVI;
2203 assert (ImplIvar && "missing implementation ivar");
2204 assert (ClsIvar && "missing class ivar");
2205
2206 // First, make sure the types match.
2207 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
2208 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
2209 << ImplIvar->getIdentifier()
2210 << ImplIvar->getType() << ClsIvar->getType();
2211 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2212 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2213 ImplIvar->getBitWidthValue(Context) !=
2214 ClsIvar->getBitWidthValue(Context)) {
2215 Diag(ImplIvar->getBitWidth()->getBeginLoc(),
2216 diag::err_conflicting_ivar_bitwidth)
2217 << ImplIvar->getIdentifier();
2218 Diag(ClsIvar->getBitWidth()->getBeginLoc(),
2219 diag::note_previous_definition);
2220 }
2221 // Make sure the names are identical.
2222 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
2223 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
2224 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
2225 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2226 }
2227 --numIvars;
2228 }
2229
2230 if (numIvars > 0)
2231 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
2232 else if (IVI != IVE)
2233 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
2234}
2235
2237 // No point warning no definition of method which is 'unavailable'.
2238 return M->getAvailability() != AR_Unavailable;
2239}
2240
2242 ObjCMethodDecl *method, bool &IncompleteImpl,
2243 unsigned DiagID,
2244 NamedDecl *NeededFor = nullptr) {
2245 if (!shouldWarnUndefinedMethod(method))
2246 return;
2247
2248 // FIXME: For now ignore 'IncompleteImpl'.
2249 // Previously we grouped all unimplemented methods under a single
2250 // warning, but some users strongly voiced that they would prefer
2251 // separate warnings. We will give that approach a try, as that
2252 // matches what we do with protocols.
2253 {
2254 const Sema::SemaDiagnosticBuilder &B = S.Diag(Impl->getLocation(), DiagID);
2255 B << method;
2256 if (NeededFor)
2257 B << NeededFor;
2258
2259 // Add an empty definition at the end of the @implementation.
2260 std::string FixItStr;
2261 llvm::raw_string_ostream Out(FixItStr);
2262 method->print(Out, Impl->getASTContext().getPrintingPolicy());
2263 Out << " {\n}\n\n";
2264
2265 SourceLocation Loc = Impl->getAtEndRange().getBegin();
2266 B << FixItHint::CreateInsertion(Loc, FixItStr);
2267 }
2268
2269 // Issue a note to the original declaration.
2270 SourceLocation MethodLoc = method->getBeginLoc();
2271 if (MethodLoc.isValid())
2272 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
2273}
2274
2275/// Determines if type B can be substituted for type A. Returns true if we can
2276/// guarantee that anything that the user will do to an object of type A can
2277/// also be done to an object of type B. This is trivially true if the two
2278/// types are the same, or if B is a subclass of A. It becomes more complex
2279/// in cases where protocols are involved.
2280///
2281/// Object types in Objective-C describe the minimum requirements for an
2282/// object, rather than providing a complete description of a type. For
2283/// example, if A is a subclass of B, then B* may refer to an instance of A.
2284/// The principle of substitutability means that we may use an instance of A
2285/// anywhere that we may use an instance of B - it will implement all of the
2286/// ivars of B and all of the methods of B.
2287///
2288/// This substitutability is important when type checking methods, because
2289/// the implementation may have stricter type definitions than the interface.
2290/// The interface specifies minimum requirements, but the implementation may
2291/// have more accurate ones. For example, a method may privately accept
2292/// instances of B, but only publish that it accepts instances of A. Any
2293/// object passed to it will be type checked against B, and so will implicitly
2294/// by a valid A*. Similarly, a method may return a subclass of the class that
2295/// it is declared as returning.
2296///
2297/// This is most important when considering subclassing. A method in a
2298/// subclass must accept any object as an argument that its superclass's
2299/// implementation accepts. It may, however, accept a more general type
2300/// without breaking substitutability (i.e. you can still use the subclass
2301/// anywhere that you can use the superclass, but not vice versa). The
2302/// converse requirement applies to return types: the return type for a
2303/// subclass method must be a valid object of the kind that the superclass
2304/// advertises, but it may be specified more accurately. This avoids the need
2305/// for explicit down-casting by callers.
2306///
2307/// Note: This is a stricter requirement than for assignment.
2309 const ObjCObjectPointerType *A,
2310 const ObjCObjectPointerType *B,
2311 bool rejectId) {
2312 // Reject a protocol-unqualified id.
2313 if (rejectId && B->isObjCIdType()) return false;
2314
2315 // If B is a qualified id, then A must also be a qualified id and it must
2316 // implement all of the protocols in B. It may not be a qualified class.
2317 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2318 // stricter definition so it is not substitutable for id<A>.
2319 if (B->isObjCQualifiedIdType()) {
2320 return A->isObjCQualifiedIdType() &&
2321 Context.ObjCQualifiedIdTypesAreCompatible(A, B, false);
2322 }
2323
2324 /*
2325 // id is a special type that bypasses type checking completely. We want a
2326 // warning when it is used in one place but not another.
2327 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2328
2329
2330 // If B is a qualified id, then A must also be a qualified id (which it isn't
2331 // if we've got this far)
2332 if (B->isObjCQualifiedIdType()) return false;
2333 */
2334
2335 // Now we know that A and B are (potentially-qualified) class types. The
2336 // normal rules for assignment apply.
2337 return Context.canAssignObjCInterfaces(A, B);
2338}
2339
2341 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2342}
2343
2344/// Determine whether two set of Objective-C declaration qualifiers conflict.
2347 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2348 (y & ~Decl::OBJC_TQ_CSNullability);
2349}
2350
2352 ObjCMethodDecl *MethodImpl,
2353 ObjCMethodDecl *MethodDecl,
2354 bool IsProtocolMethodDecl,
2355 bool IsOverridingMode,
2356 bool Warn) {
2357 if (IsProtocolMethodDecl &&
2359 MethodImpl->getObjCDeclQualifier())) {
2360 if (Warn) {
2361 S.Diag(MethodImpl->getLocation(),
2362 (IsOverridingMode
2363 ? diag::warn_conflicting_overriding_ret_type_modifiers
2364 : diag::warn_conflicting_ret_type_modifiers))
2365 << MethodImpl->getDeclName()
2366 << MethodImpl->getReturnTypeSourceRange();
2367 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
2368 << MethodDecl->getReturnTypeSourceRange();
2369 }
2370 else
2371 return false;
2372 }
2373 if (Warn && IsOverridingMode &&
2374 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2376 MethodDecl->getReturnType(),
2377 false)) {
2378 auto nullabilityMethodImpl = *MethodImpl->getReturnType()->getNullability();
2379 auto nullabilityMethodDecl = *MethodDecl->getReturnType()->getNullability();
2380 S.Diag(MethodImpl->getLocation(),
2381 diag::warn_conflicting_nullability_attr_overriding_ret_types)
2382 << DiagNullabilityKind(nullabilityMethodImpl,
2383 ((MethodImpl->getObjCDeclQualifier() &
2385 << DiagNullabilityKind(nullabilityMethodDecl,
2386 ((MethodDecl->getObjCDeclQualifier() &
2388 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2389 }
2390
2391 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2392 MethodDecl->getReturnType()))
2393 return true;
2394 if (!Warn)
2395 return false;
2396
2397 unsigned DiagID =
2398 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2399 : diag::warn_conflicting_ret_types;
2400
2401 // Mismatches between ObjC pointers go into a different warning
2402 // category, and sometimes they're even completely explicitly allowed.
2403 if (const ObjCObjectPointerType *ImplPtrTy =
2404 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2405 if (const ObjCObjectPointerType *IfacePtrTy =
2406 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
2407 // Allow non-matching return types as long as they don't violate
2408 // the principle of substitutability. Specifically, we permit
2409 // return types that are subclasses of the declared return type,
2410 // or that are more-qualified versions of the declared type.
2411 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
2412 return false;
2413
2414 DiagID =
2415 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
2416 : diag::warn_non_covariant_ret_types;
2417 }
2418 }
2419
2420 S.Diag(MethodImpl->getLocation(), DiagID)
2421 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2422 << MethodImpl->getReturnType()
2423 << MethodImpl->getReturnTypeSourceRange();
2424 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2425 ? diag::note_previous_declaration
2426 : diag::note_previous_definition)
2427 << MethodDecl->getReturnTypeSourceRange();
2428 return false;
2429}
2430
2432 ObjCMethodDecl *MethodImpl,
2433 ObjCMethodDecl *MethodDecl,
2434 ParmVarDecl *ImplVar,
2435 ParmVarDecl *IfaceVar,
2436 bool IsProtocolMethodDecl,
2437 bool IsOverridingMode,
2438 bool Warn) {
2439 if (IsProtocolMethodDecl &&
2441 IfaceVar->getObjCDeclQualifier())) {
2442 if (Warn) {
2443 if (IsOverridingMode)
2444 S.Diag(ImplVar->getLocation(),
2445 diag::warn_conflicting_overriding_param_modifiers)
2446 << getTypeRange(ImplVar->getTypeSourceInfo())
2447 << MethodImpl->getDeclName();
2448 else S.Diag(ImplVar->getLocation(),
2449 diag::warn_conflicting_param_modifiers)
2450 << getTypeRange(ImplVar->getTypeSourceInfo())
2451 << MethodImpl->getDeclName();
2452 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2453 << getTypeRange(IfaceVar->getTypeSourceInfo());
2454 }
2455 else
2456 return false;
2457 }
2458
2459 QualType ImplTy = ImplVar->getType();
2460 QualType IfaceTy = IfaceVar->getType();
2461 if (Warn && IsOverridingMode &&
2462 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2463 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
2464 S.Diag(ImplVar->getLocation(),
2465 diag::warn_conflicting_nullability_attr_overriding_param_types)
2466 << DiagNullabilityKind(*ImplTy->getNullability(),
2467 ((ImplVar->getObjCDeclQualifier() &
2469 << DiagNullabilityKind(*IfaceTy->getNullability(),
2470 ((IfaceVar->getObjCDeclQualifier() &
2472 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
2473 }
2474 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
2475 return true;
2476
2477 if (!Warn)
2478 return false;
2479 unsigned DiagID =
2480 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2481 : diag::warn_conflicting_param_types;
2482
2483 // Mismatches between ObjC pointers go into a different warning
2484 // category, and sometimes they're even completely explicitly allowed..
2485 if (const ObjCObjectPointerType *ImplPtrTy =
2486 ImplTy->getAs<ObjCObjectPointerType>()) {
2487 if (const ObjCObjectPointerType *IfacePtrTy =
2488 IfaceTy->getAs<ObjCObjectPointerType>()) {
2489 // Allow non-matching argument types as long as they don't
2490 // violate the principle of substitutability. Specifically, the
2491 // implementation must accept any objects that the superclass
2492 // accepts, however it may also accept others.
2493 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
2494 return false;
2495
2496 DiagID =
2497 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
2498 : diag::warn_non_contravariant_param_types;
2499 }
2500 }
2501
2502 S.Diag(ImplVar->getLocation(), DiagID)
2503 << getTypeRange(ImplVar->getTypeSourceInfo())
2504 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2505 S.Diag(IfaceVar->getLocation(),
2506 (IsOverridingMode ? diag::note_previous_declaration
2507 : diag::note_previous_definition))
2508 << getTypeRange(IfaceVar->getTypeSourceInfo());
2509 return false;
2510}
2511
2512/// In ARC, check whether the conventional meanings of the two methods
2513/// match. If they don't, it's a hard error.
2516 ObjCMethodFamily implFamily = impl->getMethodFamily();
2517 ObjCMethodFamily declFamily = decl->getMethodFamily();
2518 if (implFamily == declFamily) return false;
2519
2520 // Since conventions are sorted by selector, the only possibility is
2521 // that the types differ enough to cause one selector or the other
2522 // to fall out of the family.
2523 assert(implFamily == OMF_None || declFamily == OMF_None);
2524
2525 // No further diagnostics required on invalid declarations.
2526 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2527
2528 const ObjCMethodDecl *unmatched = impl;
2529 ObjCMethodFamily family = declFamily;
2530 unsigned errorID = diag::err_arc_lost_method_convention;
2531 unsigned noteID = diag::note_arc_lost_method_convention;
2532 if (declFamily == OMF_None) {
2533 unmatched = decl;
2534 family = implFamily;
2535 errorID = diag::err_arc_gained_method_convention;
2536 noteID = diag::note_arc_gained_method_convention;
2537 }
2538
2539 // Indexes into a %select clause in the diagnostic.
2540 enum FamilySelector {
2541 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2542 };
2543 FamilySelector familySelector = FamilySelector();
2544
2545 switch (family) {
2546 case OMF_None: llvm_unreachable("logic error, no method convention");
2547 case OMF_retain:
2548 case OMF_release:
2549 case OMF_autorelease:
2550 case OMF_dealloc:
2551 case OMF_finalize:
2552 case OMF_retainCount:
2553 case OMF_self:
2554 case OMF_initialize:
2556 // Mismatches for these methods don't change ownership
2557 // conventions, so we don't care.
2558 return false;
2559
2560 case OMF_init: familySelector = F_init; break;
2561 case OMF_alloc: familySelector = F_alloc; break;
2562 case OMF_copy: familySelector = F_copy; break;
2563 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2564 case OMF_new: familySelector = F_new; break;
2565 }
2566
2567 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2568 ReasonSelector reasonSelector;
2569
2570 // The only reason these methods don't fall within their families is
2571 // due to unusual result types.
2572 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
2573 reasonSelector = R_UnrelatedReturn;
2574 } else {
2575 reasonSelector = R_NonObjectReturn;
2576 }
2577
2578 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2579 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
2580
2581 return true;
2582}
2583
2585 ObjCMethodDecl *MethodDecl,
2586 bool IsProtocolMethodDecl) {
2587 if (getLangOpts().ObjCAutoRefCount &&
2588 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2589 return;
2590
2591 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2592 IsProtocolMethodDecl, false,
2593 true);
2594
2595 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2596 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2597 EF = MethodDecl->param_end();
2598 IM != EM && IF != EF; ++IM, ++IF) {
2599 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
2600 IsProtocolMethodDecl, false, true);
2601 }
2602
2603 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
2604 Diag(ImpMethodDecl->getLocation(),
2605 diag::warn_conflicting_variadic);
2606 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2607 }
2608}
2609
2611 ObjCMethodDecl *Overridden,
2612 bool IsProtocolMethodDecl) {
2613
2614 CheckMethodOverrideReturn(*this, Method, Overridden,
2615 IsProtocolMethodDecl, true,
2616 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(*this, 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 // don't issue warning when protocol method is optional because primary
2639 // class is not required to implement it and it is safe for protocol
2640 // to implement it.
2641 if (MethodDecl->getImplementationControl() ==
2643 return;
2644 // don't issue warning when primary class's method is
2645 // deprecated/unavailable.
2646 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2647 MethodDecl->hasAttr<DeprecatedAttr>())
2648 return;
2649
2650 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2651 IsProtocolMethodDecl, false, false);
2652 if (match)
2653 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
2654 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2655 EF = MethodDecl->param_end();
2656 IM != EM && IF != EF; ++IM, ++IF) {
2657 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2658 *IM, *IF,
2659 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
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 Sema::SelectorSet &InsMap, const Sema::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 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 &ClsMap,
2836 SelectorSet &InsMapSeen,
2837 SelectorSet &ClsMapSeen,
2838 ObjCImplDecl* IMPDecl,
2839 ObjCContainerDecl* CDecl,
2840 bool &IncompleteImpl,
2841 bool ImmediateClass,
2842 bool WarnCategoryMethodImpl) {
2843 // Check and see if instance methods in class interface have been
2844 // implemented in the implementation class. If so, their types match.
2845 for (auto *I : CDecl->instance_methods()) {
2846 if (!InsMapSeen.insert(I->getSelector()).second)
2847 continue;
2848 if (!I->isPropertyAccessor() &&
2849 !InsMap.count(I->getSelector())) {
2850 if (ImmediateClass)
2851 WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl,
2852 diag::warn_undef_method_impl);
2853 continue;
2854 } else {
2855 ObjCMethodDecl *ImpMethodDecl =
2856 IMPDecl->getInstanceMethod(I->getSelector());
2857 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
2858 "Expected to find the method through lookup as well");
2859 // ImpMethodDecl may be null as in a @dynamic property.
2860 if (ImpMethodDecl) {
2861 // Skip property accessor function stubs.
2862 if (ImpMethodDecl->isSynthesizedAccessorStub())
2863 continue;
2864 if (!WarnCategoryMethodImpl)
2865 WarnConflictingTypedMethods(ImpMethodDecl, I,
2866 isa<ObjCProtocolDecl>(CDecl));
2867 else if (!I->isPropertyAccessor())
2868 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2869 }
2870 }
2871 }
2872
2873 // Check and see if class methods in class interface have been
2874 // implemented in the implementation class. If so, their types match.
2875 for (auto *I : CDecl->class_methods()) {
2876 if (!ClsMapSeen.insert(I->getSelector()).second)
2877 continue;
2878 if (!I->isPropertyAccessor() &&
2879 !ClsMap.count(I->getSelector())) {
2880 if (ImmediateClass)
2881 WarnUndefinedMethod(*this, IMPDecl, I, IncompleteImpl,
2882 diag::warn_undef_method_impl);
2883 } else {
2884 ObjCMethodDecl *ImpMethodDecl =
2885 IMPDecl->getClassMethod(I->getSelector());
2886 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
2887 "Expected to find the method through lookup as well");
2888 // ImpMethodDecl may be null as in a @dynamic property.
2889 if (ImpMethodDecl) {
2890 // Skip property accessor function stubs.
2891 if (ImpMethodDecl->isSynthesizedAccessorStub())
2892 continue;
2893 if (!WarnCategoryMethodImpl)
2894 WarnConflictingTypedMethods(ImpMethodDecl, I,
2895 isa<ObjCProtocolDecl>(CDecl));
2896 else if (!I->isPropertyAccessor())
2897 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2898 }
2899 }
2900 }
2901
2902 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2903 // Also, check for methods declared in protocols inherited by
2904 // this protocol.
2905 for (auto *PI : PD->protocols())
2906 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2907 IMPDecl, PI, IncompleteImpl, false,
2908 WarnCategoryMethodImpl);
2909 }
2910
2911 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2912 // when checking that methods in implementation match their declaration,
2913 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2914 // extension; as well as those in categories.
2915 if (!WarnCategoryMethodImpl) {
2916 for (auto *Cat : I->visible_categories())
2917 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2918 IMPDecl, Cat, IncompleteImpl,
2919 ImmediateClass && Cat->IsClassExtension(),
2920 WarnCategoryMethodImpl);
2921 } else {
2922 // Also methods in class extensions need be looked at next.
2923 for (auto *Ext : I->visible_extensions())
2924 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2925 IMPDecl, Ext, IncompleteImpl, false,
2926 WarnCategoryMethodImpl);
2927 }
2928
2929 // Check for any implementation of a methods declared in protocol.
2930 for (auto *PI : I->all_referenced_protocols())
2931 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2932 IMPDecl, PI, IncompleteImpl, false,
2933 WarnCategoryMethodImpl);
2934
2935 // FIXME. For now, we are not checking for exact match of methods
2936 // in category implementation and its primary class's super class.
2937 if (!WarnCategoryMethodImpl && I->getSuperClass())
2938 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2939 IMPDecl,
2940 I->getSuperClass(), IncompleteImpl, false);
2941 }
2942}
2943
2944/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2945/// category matches with those implemented in its primary class and
2946/// warns each time an exact match is found.
2948 ObjCCategoryImplDecl *CatIMPDecl) {
2949 // Get category's primary class.
2950 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2951 if (!CatDecl)
2952 return;
2953 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2954 if (!IDecl)
2955 return;
2956 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2957 SelectorSet InsMap, ClsMap;
2958
2959 for (const auto *I : CatIMPDecl->instance_methods()) {
2960 Selector Sel = I->getSelector();
2961 // When checking for methods implemented in the category, skip over
2962 // those declared in category class's super class. This is because
2963 // the super class must implement the method.
2964 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2965 continue;
2966 InsMap.insert(Sel);
2967 }
2968
2969 for (const auto *I : CatIMPDecl->class_methods()) {
2970 Selector Sel = I->getSelector();
2971 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2972 continue;
2973 ClsMap.insert(Sel);
2974 }
2975 if (InsMap.empty() && ClsMap.empty())
2976 return;
2977
2978 SelectorSet InsMapSeen, ClsMapSeen;
2979 bool IncompleteImpl = false;
2980 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2981 CatIMPDecl, IDecl,
2982 IncompleteImpl, false,
2983 true /*WarnCategoryMethodImpl*/);
2984}
2985
2987 ObjCContainerDecl* CDecl,
2988 bool IncompleteImpl) {
2989 SelectorSet InsMap;
2990 // Check and see if instance methods in class interface have been
2991 // implemented in the implementation class.
2992 for (const auto *I : IMPDecl->instance_methods())
2993 InsMap.insert(I->getSelector());
2994
2995 // Add the selectors for getters/setters of @dynamic properties.
2996 for (const auto *PImpl : IMPDecl->property_impls()) {
2997 // We only care about @dynamic implementations.
2998 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2999 continue;
3000
3001 const auto *P = PImpl->getPropertyDecl();
3002 if (!P) continue;
3003
3004 InsMap.insert(P->getGetterName());
3005 if (!P->getSetterName().isNull())
3006 InsMap.insert(P->getSetterName());
3007 }
3008
3009 // Check and see if properties declared in the interface have either 1)
3010 // an implementation or 2) there is a @synthesize/@dynamic implementation
3011 // of the property in the @implementation.
3012 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
3013 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
3015 !IDecl->isObjCRequiresPropertyDefs();
3016 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
3017 }
3018
3019 // Diagnose null-resettable synthesized setters.
3021
3022 SelectorSet ClsMap;
3023 for (const auto *I : IMPDecl->class_methods())
3024 ClsMap.insert(I->getSelector());
3025
3026 // Check for type conflict of methods declared in a class/protocol and
3027 // its implementation; if any.
3028 SelectorSet InsMapSeen, ClsMapSeen;
3029 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
3030 IMPDecl, CDecl,
3031 IncompleteImpl, true);
3032
3033 // check all methods implemented in category against those declared
3034 // in its primary class.
3035 if (ObjCCategoryImplDecl *CatDecl =
3036 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
3038
3039 // Check the protocol list for unimplemented methods in the @implementation
3040 // class.
3041 // Check and see if class methods in class interface have been
3042 // implemented in the implementation class.
3043
3044 LazyProtocolNameSet ExplicitImplProtocols;
3045
3046 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
3047 for (auto *PI : I->all_referenced_protocols())
3048 CheckProtocolMethodDefs(*this, IMPDecl, PI, IncompleteImpl, InsMap,
3049 ClsMap, I, ExplicitImplProtocols);
3050 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
3051 // For extended class, unimplemented methods in its protocols will
3052 // be reported in the primary class.
3053 if (!C->IsClassExtension()) {
3054 for (auto *P : C->protocols())
3055 CheckProtocolMethodDefs(*this, IMPDecl, P, IncompleteImpl, InsMap,
3056 ClsMap, CDecl, ExplicitImplProtocols);
3057 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
3058 /*SynthesizeProperties=*/false);
3059 }
3060 } else
3061 llvm_unreachable("invalid ObjCContainerDecl type.");
3062}
3063
3066 IdentifierInfo **IdentList,
3067 SourceLocation *IdentLocs,
3068 ArrayRef<ObjCTypeParamList *> TypeParamLists,
3069 unsigned NumElts) {
3070 SmallVector<Decl *, 8> DeclsInGroup;
3071 for (unsigned i = 0; i != NumElts; ++i) {
3072 // Check for another declaration kind with the same name.
3073 NamedDecl *PrevDecl
3074 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
3076 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
3077 // GCC apparently allows the following idiom:
3078 //
3079 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3080 // @class XCElementToggler;
3081 //
3082 // Here we have chosen to ignore the forward class declaration
3083 // with a warning. Since this is the implied behavior.
3084 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
3085 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
3086 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
3087 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3088 } else {
3089 // a forward class declaration matching a typedef name of a class refers
3090 // to the underlying class. Just ignore the forward class with a warning
3091 // as this will force the intended behavior which is to lookup the
3092 // typedef name.
3093 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
3094 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3095 << IdentList[i];
3096 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3097 continue;
3098 }
3099 }
3100 }
3101
3102 // Create a declaration to describe this forward declaration.
3103 ObjCInterfaceDecl *PrevIDecl
3104 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
3105
3106 IdentifierInfo *ClassName = IdentList[i];
3107 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3108 // A previous decl with a different name is because of
3109 // @compatibility_alias, for example:
3110 // \code
3111 // @class NewImage;
3112 // @compatibility_alias OldImage NewImage;
3113 // \endcode
3114 // A lookup for 'OldImage' will return the 'NewImage' decl.
3115 //
3116 // In such a case use the real declaration name, instead of the alias one,
3117 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3118 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3119 // has been aliased.
3120 ClassName = PrevIDecl->getIdentifier();
3121 }
3122
3123 // If this forward declaration has type parameters, compare them with the
3124 // type parameters of the previous declaration.
3125 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3126 if (PrevIDecl && TypeParams) {
3127 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3128 // Check for consistency with the previous declaration.
3130 *this, PrevTypeParams, TypeParams,
3131 TypeParamListContext::ForwardDeclaration)) {
3132 TypeParams = nullptr;
3133 }
3134 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3135 // The @interface does not have type parameters. Complain.
3136 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3137 << ClassName
3138 << TypeParams->getSourceRange();
3139 Diag(Def->getLocation(), diag::note_defined_here)
3140 << ClassName;
3141
3142 TypeParams = nullptr;
3143 }
3144 }
3145
3146 ObjCInterfaceDecl *IDecl
3148 ClassName, TypeParams, PrevIDecl,
3149 IdentLocs[i]);
3150 IDecl->setAtEndRange(IdentLocs[i]);
3151
3152 if (PrevIDecl)
3153 mergeDeclAttributes(IDecl, PrevIDecl);
3154
3155 PushOnScopeChains(IDecl, TUScope);
3156 CheckObjCDeclScope(IDecl);
3157 DeclsInGroup.push_back(IDecl);
3158 }
3159
3160 return BuildDeclaratorGroup(DeclsInGroup);
3161}
3162
3163static bool tryMatchRecordTypes(ASTContext &Context,
3165 const Type *left, const Type *right);
3166
3167static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3168 QualType leftQT, QualType rightQT) {
3169 const Type *left =
3171 const Type *right =
3172 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3173
3174 if (left == right) return true;
3175
3176 // If we're doing a strict match, the types have to match exactly.
3177 if (strategy == Sema::MMS_strict) return false;
3178
3179 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3180
3181 // Otherwise, use this absurdly complicated algorithm to try to
3182 // validate the basic, low-level compatibility of the two types.
3183
3184 // As a minimum, require the sizes and alignments to match.
3185 TypeInfo LeftTI = Context.getTypeInfo(left);
3186 TypeInfo RightTI = Context.getTypeInfo(right);
3187 if (LeftTI.Width != RightTI.Width)
3188 return false;
3189
3190 if (LeftTI.Align != RightTI.Align)
3191 return false;
3192
3193 // Consider all the kinds of non-dependent canonical types:
3194 // - functions and arrays aren't possible as return and parameter types
3195
3196 // - vector types of equal size can be arbitrarily mixed
3197 if (isa<VectorType>(left)) return isa<VectorType>(right);
3198 if (isa<VectorType>(right)) return false;
3199
3200 // - references should only match references of identical type
3201 // - structs, unions, and Objective-C objects must match more-or-less
3202 // exactly
3203 // - everything else should be a scalar
3204 if (!left->isScalarType() || !right->isScalarType())
3205 return tryMatchRecordTypes(Context, strategy, left, right);
3206
3207 // Make scalars agree in kind, except count bools as chars, and group
3208 // all non-member pointers together.
3209 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3210 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3211 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3212 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
3213 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3215 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3217
3218 // Note that data member pointers and function member pointers don't
3219 // intermix because of the size differences.
3220
3221 return (leftSK == rightSK);
3222}
3223
3224static bool tryMatchRecordTypes(ASTContext &Context,
3226 const Type *lt, const Type *rt) {
3227 assert(lt && rt && lt != rt);
3228
3229 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3230 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3231 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3232
3233 // Require union-hood to match.
3234 if (left->isUnion() != right->isUnion()) return false;
3235
3236 // Require an exact match if either is non-POD.
3237 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3238 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3239 return false;
3240
3241 // Require size and alignment to match.
3242 TypeInfo LeftTI = Context.getTypeInfo(lt);
3243 TypeInfo RightTI = Context.getTypeInfo(rt);
3244 if (LeftTI.Width != RightTI.Width)
3245 return false;
3246
3247 if (LeftTI.Align != RightTI.Align)
3248 return false;
3249
3250 // Require fields to match.
3251 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3252 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3253 for (; li != le && ri != re; ++li, ++ri) {
3254 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3255 return false;
3256 }
3257 return (li == le && ri == re);
3258}
3259
3260/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3261/// returns true, or false, accordingly.
3262/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
3264 const ObjCMethodDecl *right,
3265 MethodMatchStrategy strategy) {
3266 if (!matchTypes(Context, strategy, left->getReturnType(),
3267 right->getReturnType()))
3268 return false;
3269
3270 // If either is hidden, it is not considered to match.
3271 if (!left->isUnconditionallyVisible() || !right->isUnconditionallyVisible())
3272 return false;
3273
3274 if (left->isDirectMethod() != right->isDirectMethod())
3275 return false;
3276
3277 if (getLangOpts().ObjCAutoRefCount &&
3278 (left->hasAttr<NSReturnsRetainedAttr>()
3279 != right->hasAttr<NSReturnsRetainedAttr>() ||
3280 left->hasAttr<NSConsumesSelfAttr>()
3281 != right->hasAttr<NSConsumesSelfAttr>()))
3282 return false;
3283
3285 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3286 re = right->param_end();
3287
3288 for (; li != le && ri != re; ++li, ++ri) {
3289 assert(ri != right->param_end() && "Param mismatch");
3290 const ParmVarDecl *lparm = *li, *rparm = *ri;
3291
3292 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3293 return false;
3294
3295 if (getLangOpts().ObjCAutoRefCount &&
3296 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3297 return false;
3298 }
3299 return true;
3300}
3301
3303 ObjCMethodDecl *MethodInList) {
3304 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3305 auto *MethodInListProtocol =
3306 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3307 // If this method belongs to a protocol but the method in list does not, or
3308 // vice versa, we say the context is not the same.
3309 if ((MethodProtocol && !MethodInListProtocol) ||
3310 (!MethodProtocol && MethodInListProtocol))
3311 return false;
3312
3313 if (MethodProtocol && MethodInListProtocol)
3314 return true;
3315
3316 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3317 ObjCInterfaceDecl *MethodInListInterface =
3318 MethodInList->getClassInterface();
3319 return MethodInterface == MethodInListInterface;
3320}
3321
3323 ObjCMethodDecl *Method) {
3324 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3325 // inside categories.
3326 if (ObjCCategoryDecl *CD =
3327 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
3328 if (!CD->IsClassExtension() && List->getBits() < 2)
3329 List->setBits(List->getBits() + 1);
3330
3331 // If the list is empty, make it a singleton list.
3332 if (List->getMethod() == nullptr) {
3333 List->setMethod(Method);
3334 List->setNext(nullptr);
3335 return;
3336 }
3337
3338 // We've seen a method with this name, see if we have already seen this type
3339 // signature.
3340 ObjCMethodList *Previous = List;
3341 ObjCMethodList *ListWithSameDeclaration = nullptr;
3342 for (; List; Previous = List, List = List->getNext()) {
3343 // If we are building a module, keep all of the methods.
3344 if (getLangOpts().isCompilingModule())
3345 continue;
3346
3347 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3348 List->getMethod());
3349 // Looking for method with a type bound requires the correct context exists.
3350 // We need to insert a method into the list if the context is different.
3351 // If the method's declaration matches the list
3352 // a> the method belongs to a different context: we need to insert it, in
3353 // order to emit the availability message, we need to prioritize over
3354 // availability among the methods with the same declaration.
3355 // b> the method belongs to the same context: there is no need to insert a
3356 // new entry.
3357 // If the method's declaration does not match the list, we insert it to the
3358 // end.
3359 if (!SameDeclaration ||
3360 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
3361 // Even if two method types do not match, we would like to say
3362 // there is more than one declaration so unavailability/deprecated
3363 // warning is not too noisy.
3364 if (!Method->isDefined())
3365 List->setHasMoreThanOneDecl(true);
3366
3367 // For methods with the same declaration, the one that is deprecated
3368 // should be put in the front for better diagnostics.
3369 if (Method->isDeprecated() && SameDeclaration &&
3370 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3371 ListWithSameDeclaration = List;
3372
3373 if (Method->isUnavailable() && SameDeclaration &&
3374 !ListWithSameDeclaration &&
3375 List->getMethod()->getAvailability() < AR_Deprecated)
3376 ListWithSameDeclaration = List;
3377 continue;
3378 }
3379
3380 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
3381
3382 // Propagate the 'defined' bit.
3383 if (Method->isDefined())
3384 PrevObjCMethod->setDefined(true);
3385 else {
3386 // Objective-C doesn't allow an @interface for a class after its
3387 // @implementation. So if Method is not defined and there already is
3388 // an entry for this type signature, Method has to be for a different
3389 // class than PrevObjCMethod.
3390 List->setHasMoreThanOneDecl(true);
3391 }
3392
3393 // If a method is deprecated, push it in the global pool.
3394 // This is used for better diagnostics.
3395 if (Method->isDeprecated()) {
3396 if (!PrevObjCMethod->isDeprecated())
3397 List->setMethod(Method);
3398 }
3399 // If the new method is unavailable, push it into global pool
3400 // unless previous one is deprecated.
3401 if (Method->isUnavailable()) {
3402 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
3403 List->setMethod(Method);
3404 }
3405
3406 return;
3407 }
3408
3409 // We have a new signature for an existing method - add it.
3410 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
3411 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
3412
3413 // We insert it right before ListWithSameDeclaration.
3414 if (ListWithSameDeclaration) {
3415 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3416 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3417 ListWithSameDeclaration->setMethod(Method);
3418 ListWithSameDeclaration->setNext(List);
3419 return;
3420 }
3421
3422 Previous->setNext(new (Mem) ObjCMethodList(Method));
3423}
3424
3425/// Read the contents of the method pool for a given selector from
3426/// external storage.
3428 assert(ExternalSource && "We need an external AST source");
3429 ExternalSource->ReadMethodPool(Sel);
3430}
3431
3433 if (!ExternalSource)
3434 return;
3435 ExternalSource->updateOutOfDateSelector(Sel);
3436}
3437
3438void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
3439 bool instance) {
3440 // Ignore methods of invalid containers.
3441 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
3442 return;
3443
3444 if (ExternalSource)
3445 ReadMethodPool(Method->getSelector());
3446
3448 if (Pos == MethodPool.end())
3449 Pos = MethodPool
3450 .insert(std::make_pair(Method->getSelector(),
3452 .first;
3453
3454 Method->setDefined(impl);
3455
3456 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
3457 addMethodToGlobalList(&Entry, Method);
3458}
3459
3460/// Determines if this is an "acceptable" loose mismatch in the global
3461/// method pool. This exists mostly as a hack to get around certain
3462/// global mismatches which we can't afford to make warnings / errors.
3463/// Really, what we want is a way to take a method out of the global
3464/// method pool.
3466 ObjCMethodDecl *other) {
3467 if (!chosen->isInstanceMethod())
3468 return false;
3469
3470 if (chosen->isDirectMethod() != other->isDirectMethod())
3471 return false;
3472
3473 Selector sel = chosen->getSelector();
3474 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3475 return false;
3476
3477 // Don't complain about mismatches for -length if the method we
3478 // chose has an integral result type.
3479 return (chosen->getReturnType()->isIntegerType());
3480}
3481
3482/// Return true if the given method is wthin the type bound.
3484 const ObjCObjectType *TypeBound) {
3485 if (!TypeBound)
3486 return true;
3487
3488 if (TypeBound->isObjCId())
3489 // FIXME: should we handle the case of bounding to id<A, B> differently?
3490 return true;
3491
3492 auto *BoundInterface = TypeBound->getInterface();
3493 assert(BoundInterface && "unexpected object type!");
3494
3495 // Check if the Method belongs to a protocol. We should allow any method
3496 // defined in any protocol, because any subclass could adopt the protocol.
3497 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3498 if (MethodProtocol) {
3499 return true;
3500 }
3501
3502 // If the Method belongs to a class, check if it belongs to the class
3503 // hierarchy of the class bound.
3504 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3505 // We allow methods declared within classes that are part of the hierarchy
3506 // of the class bound (superclass of, subclass of, or the same as the class
3507 // bound).
3508 return MethodInterface == BoundInterface ||
3509 MethodInterface->isSuperClassOf(BoundInterface) ||
3510 BoundInterface->isSuperClassOf(MethodInterface);
3511 }
3512 llvm_unreachable("unknown method context");
3513}
3514
3515/// We first select the type of the method: Instance or Factory, then collect
3516/// all methods with that type.
3519 bool InstanceFirst, bool CheckTheOther,
3520 const ObjCObjectType *TypeBound) {
3521 if (ExternalSource)
3522 ReadMethodPool(Sel);
3523
3525 if (Pos == MethodPool.end())
3526 return false;
3527
3528 // Gather the non-hidden methods.
3529 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3530 Pos->second.second;
3531 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
3532 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3533 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3534 Methods.push_back(M->getMethod());
3535 }
3536
3537 // Return if we find any method with the desired kind.
3538 if (!Methods.empty())
3539 return Methods.size() > 1;
3540
3541 if (!CheckTheOther)
3542 return false;
3543
3544 // Gather the other kind.
3545 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3546 Pos->second.first;
3547 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
3548 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible()) {
3549 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3550 Methods.push_back(M->getMethod());
3551 }
3552
3553 return Methods.size() > 1;
3554}
3555
3557 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3558 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3559 // Diagnose finding more than one method in global pool.
3560 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3561 FilteredMethods.push_back(BestMethod);
3562
3563 for (auto *M : Methods)
3564 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3565 FilteredMethods.push_back(M);
3566
3567 if (FilteredMethods.size() > 1)
3568 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3569 receiverIdOrClass);
3570
3572 // Test for no method in the pool which should not trigger any warning by
3573 // caller.
3574 if (Pos == MethodPool.end())
3575 return true;
3576 ObjCMethodList &MethList =
3577 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
3578 return MethList.hasMoreThanOneDecl();
3579}
3580
3581ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
3582 bool receiverIdOrClass,
3583 bool instance) {
3584 if (ExternalSource)
3585 ReadMethodPool(Sel);
3586
3588 if (Pos == MethodPool.end())
3589 return nullptr;
3590
3591 // Gather the non-hidden methods.
3592 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
3594 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
3595 if (M->getMethod() && M->getMethod()->isUnconditionallyVisible())
3596 return M->getMethod();
3597 }
3598 return nullptr;
3599}
3600
3602 Selector Sel, SourceRange R,
3603 bool receiverIdOrClass) {
3604 // We found multiple methods, so we may have to complain.
3605 bool issueDiagnostic = false, issueError = false;
3606
3607 // We support a warning which complains about *any* difference in
3608 // method signature.
3609 bool strictSelectorMatch =
3610 receiverIdOrClass &&
3611 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
3612 if (strictSelectorMatch) {
3613 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3614 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3615 issueDiagnostic = true;
3616 break;
3617 }
3618 }
3619 }
3620
3621 // If we didn't see any strict differences, we won't see any loose
3622 // differences. In ARC, however, we also need to check for loose
3623 // mismatches, because most of them are errors.
3624 if (!strictSelectorMatch ||
3625 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3626 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3627 // This checks if the methods differ in type mismatch.
3628 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3629 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3630 issueDiagnostic = true;
3631 if (getLangOpts().ObjCAutoRefCount)
3632 issueError = true;
3633 break;
3634 }
3635 }
3636
3637 if (issueDiagnostic) {
3638 if (issueError)
3639 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3640 else if (strictSelectorMatch)
3641 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3642 else
3643 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
3644
3645 Diag(Methods[0]->getBeginLoc(),
3646 issueError ? diag::note_possibility : diag::note_using)
3647 << Methods[0]->getSourceRange();
3648 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3649 Diag(Methods[I]->getBeginLoc(), diag::note_also_found)
3650 << Methods[I]->getSourceRange();
3651 }
3652 }
3653}
3654
3657 if (Pos == MethodPool.end())
3658 return nullptr;
3659
3660 GlobalMethodPool::Lists &Methods = Pos->second;
3661 for (const ObjCMethodList *Method = &Methods.first; Method;
3662 Method = Method->getNext())
3663 if (Method->getMethod() &&
3664 (Method->getMethod()->isDefined() ||
3665 Method->getMethod()->isPropertyAccessor()))
3666 return Method->getMethod();
3667
3668 for (const ObjCMethodList *Method = &Methods.second; Method;
3669 Method = Method->getNext())
3670 if (Method->getMethod() &&
3671 (Method->getMethod()->isDefined() ||
3672 Method->getMethod()->isPropertyAccessor()))
3673 return Method->getMethod();
3674 return nullptr;
3675}
3676
3677static void
3680 StringRef Typo, const ObjCMethodDecl * Method) {
3681 const unsigned MaxEditDistance = 1;
3682 unsigned BestEditDistance = MaxEditDistance + 1;
3683 std::string MethodName = Method->getSelector().getAsString();
3684
3685 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3686 if (MinPossibleEditDistance > 0 &&
3687 Typo.size() / MinPossibleEditDistance < 1)
3688 return;
3689 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3690 if (EditDistance > MaxEditDistance)
3691 return;
3692 if (EditDistance == BestEditDistance)
3693 BestMethod.push_back(Method);
3694 else if (EditDistance < BestEditDistance) {
3695 BestMethod.clear();
3696 BestMethod.push_back(Method);
3697 }
3698}
3699
3701 QualType ObjectType) {
3702 if (ObjectType.isNull())
3703 return true;
3704 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3705 return true;
3706 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3707 nullptr;
3708}
3709
3710const ObjCMethodDecl *
3712 QualType ObjectType) {
3713 unsigned NumArgs = Sel.getNumArgs();
3715 bool ObjectIsId = true, ObjectIsClass = true;
3716 if (ObjectType.isNull())
3717 ObjectIsId = ObjectIsClass = false;
3718 else if (!ObjectType->isObjCObjectPointerType())
3719 return nullptr;
3720 else if (const ObjCObjectPointerType *ObjCPtr =
3721 ObjectType->getAsObjCInterfacePointerType()) {
3722 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3723 ObjectIsId = ObjectIsClass = false;
3724 }
3725 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3726 ObjectIsClass = false;
3727 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3728 ObjectIsId = false;
3729 else
3730 return nullptr;
3731
3733 e = MethodPool.end(); b != e; b++) {
3734 // instance methods
3735 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
3736 if (M->getMethod() &&
3737 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3738 (M->getMethod()->getSelector() != Sel)) {
3739 if (ObjectIsId)
3740 Methods.push_back(M->getMethod());
3741 else if (!ObjectIsClass &&
3742 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3743 ObjectType))
3744 Methods.push_back(M->getMethod());
3745 }
3746 // class methods
3747 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
3748 if (M->getMethod() &&
3749 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3750 (M->getMethod()->getSelector() != Sel)) {
3751 if (ObjectIsClass)
3752 Methods.push_back(M->getMethod());
3753 else if (!ObjectIsId &&
3754 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3755 ObjectType))
3756 Methods.push_back(M->getMethod());
3757 }
3758 }
3759
3761 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3762 HelperSelectorsForTypoCorrection(SelectedMethods,
3763 Sel.getAsString(), Methods[i]);
3764 }
3765 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
3766}
3767
3768/// DiagnoseDuplicateIvars -
3769/// Check for duplicate ivars in the entire class at the start of
3770/// \@implementation. This becomes necessary because class extension can
3771/// add ivars to a class in random order which will not be known until
3772/// class's \@implementation is seen.
3774 ObjCInterfaceDecl *SID) {
3775 for (auto *Ivar : ID->ivars()) {
3776 if (Ivar->isInvalidDecl())
3777 continue;
3778 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3779 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3780 if (prevIvar) {
3781 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3782 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3783 Ivar->setInvalidDecl();
3784 }
3785 }
3786 }
3787}
3788
3789/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3791 if (S.getLangOpts().ObjCWeak) return;
3792
3793 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3794 ivar; ivar = ivar->getNextIvar()) {
3795 if (ivar->isInvalidDecl()) continue;
3796 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3797 if (S.getLangOpts().ObjCWeakRuntime) {
3798 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3799 } else {
3800 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3801 }
3802 }
3803 }
3804}
3805
3806/// Diagnose attempts to use flexible array member with retainable object type.
3808 ObjCInterfaceDecl *ID) {
3809 if (!S.getLangOpts().ObjCAutoRefCount)
3810 return;
3811
3812 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3813 ivar = ivar->getNextIvar()) {
3814 if (ivar->isInvalidDecl())
3815 continue;
3816 QualType IvarTy = ivar->getType();
3817 if (IvarTy->isIncompleteArrayType() &&
3819 IvarTy->isObjCLifetimeType()) {
3820 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3821 ivar->setInvalidDecl();
3822 }
3823 }
3824}
3825
3827 switch (CurContext->getDeclKind()) {
3828 case Decl::ObjCInterface:
3829 return Sema::OCK_Interface;
3830 case Decl::ObjCProtocol:
3831 return Sema::OCK_Protocol;
3832 case Decl::ObjCCategory:
3833 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
3835 return Sema::OCK_Category;
3836 case Decl::ObjCImplementation:
3838 case Decl::ObjCCategoryImpl:
3840
3841 default:
3842 return Sema::OCK_None;
3843 }
3844}
3845
3847 if (T->isIncompleteArrayType())
3848 return true;
3849 const auto *RecordTy = T->getAs<RecordType>();
3850 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3851}
3852
3854 ObjCInterfaceDecl *IntfDecl = nullptr;
3855 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3857 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3858 Ivars = IntfDecl->ivars();
3859 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3860 IntfDecl = ImplDecl->getClassInterface();
3861 Ivars = ImplDecl->ivars();
3862 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3863 if (CategoryDecl->IsClassExtension()) {
3864 IntfDecl = CategoryDecl->getClassInterface();
3865 Ivars = CategoryDecl->ivars();
3866 }
3867 }
3868
3869 // Check if variable sized ivar is in interface and visible to subclasses.
3870 if (!isa<ObjCInterfaceDecl>(OCD)) {
3871 for (auto *ivar : Ivars) {
3872 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3873 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3874 << ivar->getDeclName() << ivar->getType();
3875 }
3876 }
3877 }
3878
3879 // Subsequent checks require interface decl.
3880 if (!IntfDecl)
3881 return;
3882
3883 // Check if variable sized ivar is followed by another ivar.
3884 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3885 ivar = ivar->getNextIvar()) {
3886 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3887 continue;
3888 QualType IvarTy = ivar->getType();
3889 bool IsInvalidIvar = false;
3890 if (IvarTy->isIncompleteArrayType()) {
3891 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3892 << ivar->getDeclName() << IvarTy
3893 << llvm::to_underlying(TagTypeKind::Class); // Use "class" for Obj-C.
3894 IsInvalidIvar = true;
3895 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3896 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3897 S.Diag(ivar->getLocation(),
3898 diag::err_objc_variable_sized_type_not_at_end)
3899 << ivar->getDeclName() << IvarTy;
3900 IsInvalidIvar = true;
3901 }
3902 }
3903 if (IsInvalidIvar) {
3904 S.Diag(ivar->getNextIvar()->getLocation(),
3905 diag::note_next_ivar_declaration)
3906 << ivar->getNextIvar()->getSynthesize();
3907 ivar->setInvalidDecl();
3908 }
3909 }
3910
3911 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3912 // Perform the check only if OCD is the first container to declare ivars to
3913 // avoid multiple warnings for the same ivar.
3914 ObjCIvarDecl *FirstIvar =
3915 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3916 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3917 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3918 while (SuperClass && SuperClass->ivar_empty())
3919 SuperClass = SuperClass->getSuperClass();
3920 if (SuperClass) {
3921 auto IvarIter = SuperClass->ivar_begin();
3922 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3923 const ObjCIvarDecl *LastIvar = *IvarIter;
3924 if (IsVariableSizedType(LastIvar->getType())) {
3925 S.Diag(FirstIvar->getLocation(),
3926 diag::warn_superclass_variable_sized_type_not_at_end)
3927 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3928 << LastIvar->getType() << SuperClass->getDeclName();
3929 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3930 << LastIvar->getDeclName();
3931 }
3932 }
3933 }
3934}
3935
3937 Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl);
3938
3940 Sema &S, ObjCCategoryDecl *CDecl,
3941 const llvm::iterator_range<ObjCProtocolList::iterator> &Protocols) {
3942 for (auto *PI : Protocols)
3944}
3945
3947 Sema &S, ObjCProtocolDecl *PDecl, ObjCCategoryDecl *CDecl) {
3948 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
3949 PDecl = PDecl->getDefinition();
3950
3952 const auto *IDecl = CDecl->getClassInterface();
3953 for (auto *MD : PDecl->methods()) {
3954 if (!MD->isPropertyAccessor()) {
3955 if (const auto *CMD =
3956 IDecl->getMethod(MD->getSelector(), MD->isInstanceMethod())) {
3957 if (CMD->isDirectMethod())
3958 DirectMembers.push_back(CMD);
3959 }
3960 }
3961 }
3962 for (auto *PD : PDecl->properties()) {
3963 if (const auto *CPD = IDecl->FindPropertyVisibleInPrimaryClass(
3964 PD->getIdentifier(),
3965 PD->isClassProperty()
3968 if (CPD->isDirectProperty())
3969 DirectMembers.push_back(CPD);
3970 }
3971 }
3972 if (!DirectMembers.empty()) {
3973 S.Diag(CDecl->getLocation(), diag::err_objc_direct_protocol_conformance)
3974 << CDecl->IsClassExtension() << CDecl << PDecl << IDecl;
3975 for (const auto *MD : DirectMembers)
3976 S.Diag(MD->getLocation(), diag::note_direct_member_here);
3977 return;
3978 }
3979
3980 // Check on this protocols's referenced protocols, recursively.
3982 PDecl->protocols());
3983}
3984
3985// Note: For class/category implementations, allMethods is always null.
3987 ArrayRef<DeclGroupPtrTy> allTUVars) {
3989 return nullptr;
3990
3991 assert(AtEnd.isValid() && "Invalid location for '@end'");
3992
3993 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3994 Decl *ClassDecl = OCD;
3995
3996 bool isInterfaceDeclKind =
3997 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3998 || isa<ObjCProtocolDecl>(ClassDecl);
3999 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
4000
4001 // Make synthesized accessor stub functions visible.
4002 // ActOnPropertyImplDecl() creates them as not visible in case
4003 // they are overridden by an explicit method that is encountered
4004 // later.
4005 if (auto *OID = dyn_cast<ObjCImplementationDecl>(CurContext)) {
4006 for (auto *PropImpl : OID->property_impls()) {
4007 if (auto *Getter = PropImpl->getGetterMethodDecl())
4008 if (Getter->isSynthesizedAccessorStub())
4009 OID->addDecl(Getter);
4010 if (auto *Setter = PropImpl->getSetterMethodDecl())
4011 if (Setter->isSynthesizedAccessorStub())
4012 OID->addDecl(Setter);
4013 }
4014 }
4015
4016 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
4017 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
4018 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
4019
4020 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
4021 ObjCMethodDecl *Method =
4022 cast_or_null<ObjCMethodDecl>(allMethods[i]);
4023
4024 if (!Method) continue; // Already issued a diagnostic.
4025 if (Method->isInstanceMethod()) {
4026 /// Check for instance method of the same name with incompatible types
4027 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
4028 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4029 : false;
4030 if ((isInterfaceDeclKind && PrevMethod && !match)
4031 || (checkIdenticalMethods && match)) {
4032 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4033 << Method->getDeclName();
4034 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4035 Method->setInvalidDecl();
4036 } else {
4037 if (PrevMethod) {
4038 Method->setAsRedeclaration(PrevMethod);
4040 Method->getLocation()))
4041 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4042 << Method->getDeclName();
4043 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4044 }
4045 InsMap[Method->getSelector()] = Method;
4046 /// The following allows us to typecheck messages to "id".
4048 }
4049 } else {
4050 /// Check for class method of the same name with incompatible types
4051 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
4052 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
4053 : false;
4054 if ((isInterfaceDeclKind && PrevMethod && !match)
4055 || (checkIdenticalMethods && match)) {
4056 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
4057 << Method->getDeclName();
4058 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4059 Method->setInvalidDecl();
4060 } else {
4061 if (PrevMethod) {
4062 Method->setAsRedeclaration(PrevMethod);
4064 Method->getLocation()))
4065 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
4066 << Method->getDeclName();
4067 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
4068 }
4069 ClsMap[Method->getSelector()] = Method;
4071 }
4072 }
4073 }
4074 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
4075 // Nothing to do here.
4076 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
4077 // Categories are used to extend the class by declaring new methods.
4078 // By the same token, they are also used to add new properties. No
4079 // need to compare the added property to those in the class.
4080
4081 if (C->IsClassExtension()) {
4082 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
4084 }
4085
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())
4132 DiagnoseWeakIvars(*this, IC);
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(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.
4147 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4148 DeclLoc, 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 }
4210 DiagnoseVariableSizedIvars(*this, OCD);
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 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())
4258 return Sema::RTC_Compatible;
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))
4265 return Sema::RTC_Compatible;
4266
4267 // - it is a superclass of the method's class type
4268 if (ResultClass->isSuperClassOf(CurrentClass))
4269 return Sema::RTC_Compatible;
4270 }
4271 } else {
4272 // Any Objective-C pointer type might be acceptable for a protocol
4273 // method; we just don't know.
4274 return Sema::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 if (it == S.MethodPool.end()) {
4298 if (!S.getExternalSource()) return;
4299 S.ReadMethodPool(selector);
4300
4301 it = S.MethodPool.find(selector);
4302 if (it == S.MethodPool.end())
4303 return;
4304 }
4305 const ObjCMethodList &list =
4306 method->isInstanceMethod() ? it->second.first : it->second.second;
4307 if (!list.getMethod()) return;
4308
4309 const ObjCContainerDecl *container
4310 = cast<ObjCContainerDecl>(method->getDeclContext());
4311
4312 // Prevent the search from reaching this container again. This is
4313 // important with categories, which override methods from the
4314 // interface and each other.
4315 if (const ObjCCategoryDecl *Category =
4316 dyn_cast<ObjCCategoryDecl>(container)) {
4317 searchFromContainer(container);
4318 if (const ObjCInterfaceDecl *Interface = Category->getClassInterface())
4319 searchFromContainer(Interface);
4320 } else {
4321 searchFromContainer(container);
4322 }
4323 }
4324
4325 typedef decltype(Overridden)::iterator iterator;
4326 iterator begin() const { return Overridden.begin(); }
4327 iterator end() const { return Overridden.end(); }
4328
4329private:
4330 void searchFromContainer(const ObjCContainerDecl *container) {
4331 if (container->isInvalidDecl()) return;
4332
4333 switch (container->getDeclKind()) {
4334#define OBJCCONTAINER(type, base) \
4335 case Decl::type: \
4336 searchFrom(cast<type##Decl>(container)); \
4337 break;
4338#define ABSTRACT_DECL(expansion)
4339#define DECL(type, base) \
4340 case Decl::type:
4341#include "clang/AST/DeclNodes.inc"
4342 llvm_unreachable("not an ObjC container!");
4343 }
4344 }
4345
4346 void searchFrom(const ObjCProtocolDecl *protocol) {
4347 if (!protocol->hasDefinition())
4348 return;
4349
4350 // A method in a protocol declaration overrides declarations from
4351 // referenced ("parent") protocols.
4352 search(protocol->getReferencedProtocols());
4353 }
4354
4355 void searchFrom(const ObjCCategoryDecl *category) {
4356 // A method in a category declaration overrides declarations from
4357 // the main class and from protocols the category references.
4358 // The main class is handled in the constructor.
4359 search(category->getReferencedProtocols());
4360 }
4361
4362 void searchFrom(const ObjCCategoryImplDecl *impl) {
4363 // A method in a category definition that has a category
4364 // declaration overrides declarations from the category
4365 // declaration.
4366 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4367 search(category);
4368 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4369 search(Interface);
4370
4371 // Otherwise it overrides declarations from the class.
4372 } else if (const auto *Interface = impl->getClassInterface()) {
4373 search(Interface);
4374 }
4375 }
4376
4377 void searchFrom(const ObjCInterfaceDecl *iface) {
4378 // A method in a class declaration overrides declarations from
4379 if (!iface->hasDefinition())
4380 return;
4381
4382 // - categories,
4383 for (auto *Cat : iface->known_categories())
4384 search(Cat);
4385
4386 // - the super class, and
4387 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4388 search(super);
4389
4390 // - any referenced protocols.
4391 search(iface->getReferencedProtocols());
4392 }
4393
4394 void searchFrom(const ObjCImplementationDecl *impl) {
4395 // A method in a class implementation overrides declarations from
4396 // the class interface.
4397 if (const auto *Interface = impl->getClassInterface())
4398 search(Interface);
4399 }
4400
4401 void search(const ObjCProtocolList &protocols) {
4402 for (const auto *Proto : protocols)
4403 search(Proto);
4404 }
4405
4406 void search(const ObjCContainerDecl *container) {
4407 // Check for a method in this container which matches this selector.
4408 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
4409 Method->isInstanceMethod(),
4410 /*AllowHidden=*/true);
4411
4412 // If we find one, record it and bail out.
4413 if (meth) {
4414 Overridden.insert(meth);
4415 return;
4416 }
4417
4418 // Otherwise, search for methods that a hypothetical method here
4419 // would have overridden.
4420
4421 // Note that we're now in a recursive case.
4422 Recursive = true;
4423
4424 searchFromContainer(container);
4425 }
4426};
4427} // end anonymous namespace
4428
4430 ObjCMethodDecl *overridden) {
4431 if (overridden->isDirectMethod()) {
4432 const auto *attr = overridden->getAttr<ObjCDirectAttr>();
4433 Diag(method->getLocation(), diag::err_objc_override_direct_method);
4434 Diag(attr->getLocation(), diag::note_previous_declaration);
4435 } else if (method->isDirectMethod()) {
4436 const auto *attr = method->getAttr<ObjCDirectAttr>();
4437 Diag(attr->getLocation(), diag::err_objc_direct_on_override)
4438 << isa<ObjCProtocolDecl>(overridden->getDeclContext());
4439 Diag(overridden->getLocation(), diag::note_previous_declaration);
4440 }
4441}
4442
4444 ObjCInterfaceDecl *CurrentClass,
4446 if (!ObjCMethod)
4447 return;
4448 auto IsMethodInCurrentClass = [CurrentClass](const ObjCMethodDecl *M) {
4449 // Checking canonical decl works across modules.
4450 return M->getClassInterface()->getCanonicalDecl() ==
4451 CurrentClass->getCanonicalDecl();
4452 };
4453 // Search for overridden methods and merge information down from them.
4454 OverrideSearch overrides(*this, ObjCMethod);
4455 // Keep track if the method overrides any method in the class's base classes,
4456 // its protocols, or its categories' protocols; we will keep that info
4457 // in the ObjCMethodDecl.
4458 // For this info, a method in an implementation is not considered as
4459 // overriding the same method in the interface or its categories.
4460 bool hasOverriddenMethodsInBaseOrProtocol = false;
4461 for (ObjCMethodDecl *overridden : overrides) {
4462 if (!hasOverriddenMethodsInBaseOrProtocol) {
4463 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4464 !IsMethodInCurrentClass(overridden) || overridden->isOverriding()) {
4465 CheckObjCMethodDirectOverrides(ObjCMethod, overridden);
4466 hasOverriddenMethodsInBaseOrProtocol = true;
4467 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4468 // OverrideSearch will return as "overridden" the same method in the
4469 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4470 // check whether a category of a base class introduced a method with the
4471 // same selector, after the interface method declaration.
4472 // To avoid unnecessary lookups in the majority of cases, we use the
4473 // extra info bits in GlobalMethodPool to check whether there were any
4474 // category methods with this selector.
4476 MethodPool.find(ObjCMethod->getSelector());
4477 if (It != MethodPool.end()) {
4478 ObjCMethodList &List =
4479 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4480 unsigned CategCount = List.getBits();
4481 if (CategCount > 0) {
4482 // If the method is in a category we'll do lookup if there were at
4483 // least 2 category methods recorded, otherwise only one will do.
4484 if (CategCount > 1 ||
4485 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4486 OverrideSearch overrides(*this, overridden);
4487 for (ObjCMethodDecl *SuperOverridden : overrides) {
4488 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4489 !IsMethodInCurrentClass(SuperOverridden)) {
4490 CheckObjCMethodDirectOverrides(ObjCMethod, SuperOverridden);
4491 hasOverriddenMethodsInBaseOrProtocol = true;
4492 overridden->setOverriding(true);
4493 break;
4494 }
4495 }
4496 }
4497 }
4498 }
4499 }
4500 }
4501
4502 // Propagate down the 'related result type' bit from overridden methods.
4503 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4504 ObjCMethod->setRelatedResultType();
4505
4506 // Then merge the declarations.
4507 mergeObjCMethodDecls(ObjCMethod, overridden);
4508
4509 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4510 continue; // Conflicting properties are detected elsewhere.
4511
4512 // Check for overriding methods
4513 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4514 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4515 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4516 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4517
4518 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
4519 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4520 !overridden->isImplicit() /* not meant for properties */) {
4521 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4522 E = ObjCMethod->param_end();
4523 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4524 PrevE = overridden->param_end();
4525 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
4526 assert(PrevI != overridden->param_end() && "Param mismatch");
4527 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4528 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4529 // If type of argument of method in this class does not match its
4530 // respective argument type in the super class method, issue warning;
4531 if (!Context.typesAreCompatible(T1, T2)) {
4532 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4533 << T1 << T2;
4534 Diag(overridden->getLocation(), diag::note_previous_declaration);
4535 break;
4536 }
4537 }
4538 }
4539 }
4540
4541 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4542}
4543
4544/// Merge type nullability from for a redeclaration of the same entity,
4545/// producing the updated type of the redeclared entity.
4547 QualType type,
4548 bool usesCSKeyword,
4549 SourceLocation prevLoc,
4550 QualType prevType,
4551 bool prevUsesCSKeyword) {
4552 // Determine the nullability of both types.
4553 auto nullability = type->getNullability();
4554 auto prevNullability = prevType->getNullability();
4555
4556 // Easy case: both have nullability.
4557 if (nullability.has_value() == prevNullability.has_value()) {
4558 // Neither has nullability; continue.
4559 if (!nullability)
4560 return type;
4561
4562 // The nullabilities are equivalent; do nothing.
4563 if (*nullability == *prevNullability)
4564 return type;
4565
4566 // Complain about mismatched nullability.
4567 S.Diag(loc, diag::err_nullability_conflicting)
4568 << DiagNullabilityKind(*nullability, usesCSKeyword)
4569 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
4570 return type;
4571 }
4572
4573 // If it's the redeclaration that has nullability, don't change anything.
4574 if (nullability)
4575 return type;
4576
4577 // Otherwise, provide the result with the same nullability.
4578 return S.Context.getAttributedType(
4580 type, type);
4581}
4582
4583/// Merge information from the declaration of a method in the \@interface
4584/// (or a category/extension) into the corresponding method in the
4585/// @implementation (for a class or category).
4587 ObjCMethodDecl *method,
4588 ObjCMethodDecl *prevMethod) {
4589 // Merge the objc_requires_super attribute.
4590 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4591 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4592 // merge the attribute into implementation.
4593 method->addAttr(
4594 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4595 method->getLocation()));
4596 }
4597
4598 // Merge nullability of the result type.
4599 QualType newReturnType
4601 S, method->getReturnTypeSourceRange().getBegin(),
4602 method->getReturnType(),
4604 prevMethod->getReturnTypeSourceRange().getBegin(),
4605 prevMethod->getReturnType(),
4607 method->setReturnType(newReturnType);
4608
4609 // Handle each of the parameters.
4610 unsigned numParams = method->param_size();
4611 unsigned numPrevParams = prevMethod->param_size();
4612 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4613 ParmVarDecl *param = method->param_begin()[i];
4614 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4615
4616 // Merge nullability.
4617 QualType newParamType
4619 S, param->getLocation(), param->getType(),
4621 prevParam->getLocation(), prevParam->getType(),
4623 param->setType(newParamType);
4624 }
4625}
4626
4627/// Verify that the method parameters/return value have types that are supported
4628/// by the x86 target.
4630 const ObjCMethodDecl *Method) {
4631 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4632 llvm::Triple::x86 &&
4633 "x86-specific check invoked for a different target");
4634 SourceLocation Loc;
4635 QualType T;
4636 for (const ParmVarDecl *P : Method->parameters()) {
4637 if (P->getType()->isVectorType()) {
4638 Loc = P->getBeginLoc();
4639 T = P->getType();
4640 break;
4641 }
4642 }
4643 if (Loc.isInvalid()) {
4644 if (Method->getReturnType()->isVectorType()) {
4645 Loc = Method->getReturnTypeSourceRange().getBegin();
4646 T = Method->getReturnType();
4647 } else
4648 return;
4649 }
4650
4651 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4652 // iOS < 9 and macOS < 10.11.
4653 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4654 VersionTuple AcceptedInVersion;
4655 if (Triple.getOS() == llvm::Triple::IOS)
4656 AcceptedInVersion = VersionTuple(/*Major=*/9);
4657 else if (Triple.isMacOSX())
4658 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4659 else
4660 return;
4662 AcceptedInVersion)
4663 return;
4664 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4665 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4666 : /*parameter*/ 0)
4667 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4668}
4669
4670static void mergeObjCDirectMembers(Sema &S, Decl *CD, ObjCMethodDecl *Method) {
4671 if (!Method->isDirectMethod() && !Method->hasAttr<UnavailableAttr>() &&
4672 CD->hasAttr<ObjCDirectMembersAttr>()) {
4673 Method->addAttr(
4674 ObjCDirectAttr::CreateImplicit(S.Context, Method->getLocation()));
4675 }
4676}
4677
4679 ObjCMethodDecl *Method,
4680 ObjCImplDecl *ImpDecl = nullptr) {
4681 auto Sel = Method->getSelector();
4682 bool isInstance = Method->isInstanceMethod();
4683 bool diagnosed = false;
4684
4685 auto diagClash = [&](const ObjCMethodDecl *IMD) {
4686 if (diagnosed || IMD->isImplicit())
4687 return;
4688 if (Method->isDirectMethod() || IMD->isDirectMethod()) {
4689 S.Diag(Method->getLocation(), diag::err_objc_direct_duplicate_decl)
4690 << Method->isDirectMethod() << /* method */ 0 << IMD->isDirectMethod()
4691 << Method->getDeclName();
4692 S.Diag(IMD->getLocation(), diag::note_previous_declaration);
4693 diagnosed = true;
4694 }
4695 };
4696
4697 // Look for any other declaration of this method anywhere we can see in this
4698 // compilation unit.
4699 //
4700 // We do not use IDecl->lookupMethod() because we have specific needs:
4701 //
4702 // - we absolutely do not need to walk protocols, because
4703 // diag::err_objc_direct_on_protocol has already been emitted
4704 // during parsing if there's a conflict,
4705 //
4706 // - when we do not find a match in a given @interface container,
4707 // we need to attempt looking it up in the @implementation block if the
4708 // translation unit sees it to find more clashes.
4709
4710 if (auto *IMD = IDecl->getMethod(Sel, isInstance))
4711 diagClash(IMD);
4712 else if (auto *Impl = IDecl->getImplementation())
4713 if (Impl != ImpDecl)
4714 if (auto *IMD = IDecl->getImplementation()->getMethod(Sel, isInstance))
4715 diagClash(IMD);
4716
4717 for (const auto *Cat : IDecl->visible_categories())
4718 if (auto *IMD = Cat->getMethod(Sel, isInstance))
4719 diagClash(IMD);
4720 else if (auto CatImpl = Cat->getImplementation())
4721 if (CatImpl != ImpDecl)
4722 if (auto *IMD = Cat->getMethod(Sel, isInstance))
4723 diagClash(IMD);
4724}
4725
4727 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4728 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4729 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
4730 // optional arguments. The number of types/arguments is obtained
4731 // from the Sel.getNumArgs().
4732 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4733 unsigned CNumArgs, // c-style args
4734 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
4735 bool isVariadic, bool MethodDefinition) {
4736 // Make sure we can establish a context for the method.
4737 if (!CurContext->isObjCContainer()) {
4738 Diag(MethodLoc, diag::err_missing_method_context);
4739 return nullptr;
4740 }
4741
4742 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
4743 QualType resultDeclType;
4744
4745 bool HasRelatedResultType = false;
4746 TypeSourceInfo *ReturnTInfo = nullptr;
4747 if (ReturnType) {
4748 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
4749
4750 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
4751 return nullptr;
4752
4753 QualType bareResultType = resultDeclType;
4754 (void)AttributedType::stripOuterNullability(bareResultType);
4755 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
4756 } else { // get the type for "id".
4757 resultDeclType = Context.getObjCIdType();
4758 Diag(MethodLoc, diag::warn_missing_method_return_type)
4759 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
4760 }
4761
4763 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4764 MethodType == tok::minus, isVariadic,
4765 /*isPropertyAccessor=*/false, /*isSynthesizedAccessorStub=*/false,
4766 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4767 MethodDeclKind == tok::objc_optional
4770 HasRelatedResultType);
4771
4773
4774 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
4775 QualType ArgType;
4776 TypeSourceInfo *DI;
4777
4778 if (!ArgInfo[i].Type) {
4779 ArgType = Context.getObjCIdType();
4780 DI = nullptr;
4781 } else {
4782 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
4783 }
4784
4785 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
4787 LookupName(R, S);
4788 if (R.isSingleResult()) {
4789 NamedDecl *PrevDecl = R.getFoundDecl();
4790 if (S->isDeclScope(PrevDecl)) {
4791 Diag(ArgInfo[i].NameLoc,
4792 (MethodDefinition ? diag::warn_method_param_redefinition
4793 : diag::warn_method_param_declaration))
4794 << ArgInfo[i].Name;
4795 Diag(PrevDecl->getLocation(),
4796 diag::note_previous_declaration);
4797 }
4798 }
4799
4800 SourceLocation StartLoc = DI
4801 ? DI->getTypeLoc().getBeginLoc()
4802 : ArgInfo[i].NameLoc;
4803
4804 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4805 ArgInfo[i].NameLoc, ArgInfo[i].Name,
4806 ArgType, DI, SC_None);
4807
4808 Param->setObjCMethodScopeInfo(i);
4809
4810 Param->setObjCDeclQualifier(
4811 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
4812
4813 // Apply the attributes to the parameter.
4814 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
4816 ProcessAPINotes(Param);
4817
4818 if (Param->hasAttr<BlocksAttr>()) {
4819 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4820 Param->setInvalidDecl();
4821 }
4822 S->AddDecl(Param);
4823 IdResolver.AddDecl(Param);
4824
4825 Params.push_back(Param);
4826 }
4827
4828 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
4829 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
4830 QualType ArgType = Param->getType();
4831 if (ArgType.isNull())
4832 ArgType = Context.getObjCIdType();
4833 else
4834 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
4835 ArgType = Context.getAdjustedParameterType(ArgType);
4836
4837 Param->setDeclContext(ObjCMethod);
4838 Params.push_back(Param);
4839 }
4840
4841 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
4842 ObjCMethod->setObjCDeclQualifier(
4844
4845 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
4846 AddPragmaAttributes(TUScope, ObjCMethod);
4847 ProcessAPINotes(ObjCMethod);
4848
4849 // Add the method now.
4850 const ObjCMethodDecl *PrevMethod = nullptr;
4851 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
4852 if (MethodType == tok::minus) {
4853 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4854 ImpDecl->addInstanceMethod(ObjCMethod);
4855 } else {
4856 PrevMethod = ImpDecl->getClassMethod(Sel);
4857 ImpDecl->addClassMethod(ObjCMethod);
4858 }
4859
4860 // If this method overrides a previous @synthesize declaration,
4861 // register it with the property. Linear search through all
4862 // properties here, because the autosynthesized stub hasn't been
4863 // made visible yet, so it can be overridden by a later
4864 // user-specified implementation.
4865 for (ObjCPropertyImplDecl *PropertyImpl : ImpDecl->property_impls()) {
4866 if (auto *Setter = PropertyImpl->getSetterMethodDecl())
4867 if (Setter->getSelector() == Sel &&
4868 Setter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4869 assert(Setter->isSynthesizedAccessorStub() && "autosynth stub expected");
4870 PropertyImpl->setSetterMethodDecl(ObjCMethod);
4871 }
4872 if (auto *Getter = PropertyImpl->getGetterMethodDecl())
4873 if (Getter->getSelector() == Sel &&
4874 Getter->isInstanceMethod() == ObjCMethod->isInstanceMethod()) {
4875 assert(Getter->isSynthesizedAccessorStub() && "autosynth stub expected");
4876 PropertyImpl->setGetterMethodDecl(ObjCMethod);
4877 break;
4878 }
4879 }
4880
4881 // A method is either tagged direct explicitly, or inherits it from its
4882 // canonical declaration.
4883 //
4884 // We have to do the merge upfront and not in mergeInterfaceMethodToImpl()
4885 // because IDecl->lookupMethod() returns more possible matches than just
4886 // the canonical declaration.
4887 if (!ObjCMethod->isDirectMethod()) {
4888 const ObjCMethodDecl *CanonicalMD = ObjCMethod->getCanonicalDecl();
4889 if (CanonicalMD->isDirectMethod()) {
4890 const auto *attr = CanonicalMD->getAttr<ObjCDirectAttr>();
4891 ObjCMethod->addAttr(
4892 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4893 }
4894 }
4895
4896 // Merge information from the @interface declaration into the
4897 // @implementation.
4898 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4899 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4900 ObjCMethod->isInstanceMethod())) {
4901 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4902
4903 // The Idecl->lookupMethod() above will find declarations for ObjCMethod
4904 // in one of these places:
4905 //
4906 // (1) the canonical declaration in an @interface container paired
4907 // with the ImplDecl,
4908 // (2) non canonical declarations in @interface not paired with the
4909 // ImplDecl for the same Class,
4910 // (3) any superclass container.
4911 //
4912 // Direct methods only allow for canonical declarations in the matching
4913 // container (case 1).
4914 //
4915 // Direct methods overriding a superclass declaration (case 3) is
4916 // handled during overrides checks in CheckObjCMethodOverrides().
4917 //
4918 // We deal with same-class container mismatches (Case 2) here.
4919 if (IDecl == IMD->getClassInterface()) {
4920 auto diagContainerMismatch = [&] {
4921 int decl = 0, impl = 0;
4922
4923 if (auto *Cat = dyn_cast<ObjCCategoryDecl>(IMD->getDeclContext()))
4924 decl = Cat->IsClassExtension() ? 1 : 2;
4925
4926 if (isa<ObjCCategoryImplDecl>(ImpDecl))
4927 impl = 1 + (decl != 0);
4928
4929 Diag(ObjCMethod->getLocation(),
4930 diag::err_objc_direct_impl_decl_mismatch)
4931 << decl << impl;
4932 Diag(IMD->getLocation(), diag::note_previous_declaration);
4933 };
4934
4935 if (ObjCMethod->isDirectMethod()) {
4936 const auto *attr = ObjCMethod->getAttr<ObjCDirectAttr>();
4937 if (ObjCMethod->getCanonicalDecl() != IMD) {
4938 diagContainerMismatch();
4939 } else if (!IMD->isDirectMethod()) {
4940 Diag(attr->getLocation(), diag::err_objc_direct_missing_on_decl);
4941 Diag(IMD->getLocation(), diag::note_previous_declaration);
4942 }
4943 } else if (IMD->isDirectMethod()) {
4944 const auto *attr = IMD->getAttr<ObjCDirectAttr>();
4945 if (ObjCMethod->getCanonicalDecl() != IMD) {
4946 diagContainerMismatch();
4947 } else {
4948 ObjCMethod->addAttr(
4949 ObjCDirectAttr::CreateImplicit(Context, attr->getLocation()));
4950 }
4951 }
4952 }
4953
4954 // Warn about defining -dealloc in a category.
4955 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4956 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4957 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4958 << ObjCMethod->getDeclName();
4959 }
4960 } else {
4961 mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4962 checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod, ImpDecl);
4963 }
4964
4965 // Warn if a method declared in a protocol to which a category or
4966 // extension conforms is non-escaping and the implementation's method is
4967 // escaping.
4968 for (auto *C : IDecl->visible_categories())
4969 for (auto &P : C->protocols())
4970 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4971 ObjCMethod->isInstanceMethod())) {
4972 assert(ObjCMethod->parameters().size() ==
4973 IMD->parameters().size() &&
4974 "Methods have different number of parameters");
4975 auto OI = IMD->param_begin(), OE = IMD->param_end();
4976 auto NI = ObjCMethod->param_begin();
4977 for (; OI != OE; ++OI, ++NI)
4978 diagnoseNoescape(*NI, *OI, C, P, *this);
4979 }
4980 }
4981 } else {
4982 if (!isa<ObjCProtocolDecl>(ClassDecl)) {
4983 mergeObjCDirectMembers(*this, ClassDecl, ObjCMethod);
4984
4985 ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4986 if (!IDecl)
4987 IDecl = cast<ObjCCategoryDecl>(ClassDecl)->getClassInterface();
4988 // For valid code, we should always know the primary interface
4989 // declaration by now, however for invalid code we'll keep parsing
4990 // but we won't find the primary interface and IDecl will be nil.
4991 if (IDecl)
4992 checkObjCDirectMethodClashes(*this, IDecl, ObjCMethod);
4993 }
4994
4995 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
4996 }
4997
4998 if (PrevMethod) {
4999 // You can never have two method definitions with the same name.
5000 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
5001 << ObjCMethod->getDeclName();
5002 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
5003 ObjCMethod->setInvalidDecl();
5004 return ObjCMethod;
5005 }
5006
5007 // If this Objective-C method does not have a related result type, but we
5008 // are allowed to infer related result types, try to do so based on the
5009 // method family.
5010 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
5011 if (!CurrentClass) {
5012 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
5013 CurrentClass = Cat->getClassInterface();
5014 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
5015 CurrentClass = Impl->getClassInterface();
5016 else if (ObjCCategoryImplDecl *CatImpl
5017 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
5018 CurrentClass = CatImpl->getClassInterface();
5019 }
5020
5022 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
5023
5024 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
5025
5026 bool ARCError = false;
5027 if (getLangOpts().ObjCAutoRefCount)
5028 ARCError = CheckARCMethodDecl(ObjCMethod);
5029
5030 // Infer the related result type when possible.
5031 if (!ARCError && RTC == Sema::RTC_Compatible &&
5032 !ObjCMethod->hasRelatedResultType() &&
5033 LangOpts.ObjCInferRelatedResultType) {
5034 bool InferRelatedResultType = false;
5035 switch (ObjCMethod->getMethodFamily()) {
5036 case OMF_None:
5037 case OMF_copy:
5038 case OMF_dealloc:
5039 case OMF_finalize:
5040 case OMF_mutableCopy:
5041 case OMF_release:
5042 case OMF_retainCount:
5043 case OMF_initialize:
5045 break;
5046
5047 case OMF_alloc:
5048 case OMF_new:
5049 InferRelatedResultType = ObjCMethod->isClassMethod();
5050 break;
5051
5052 case OMF_init:
5053 case OMF_autorelease:
5054 case OMF_retain:
5055 case OMF_self:
5056 InferRelatedResultType = ObjCMethod->isInstanceMethod();
5057 break;
5058 }
5059
5060 if (InferRelatedResultType &&
5061 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
5062 ObjCMethod->setRelatedResultType();
5063 }
5064
5065 if (MethodDefinition &&
5066 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
5067 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
5068
5069 // + load method cannot have availability attributes. It get called on
5070 // startup, so it has to have the availability of the deployment target.
5071 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
5072 if (ObjCMethod->isClassMethod() &&
5073 ObjCMethod->getSelector().getAsString() == "load") {
5074 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
5075 << 0;
5076 ObjCMethod->dropAttr<AvailabilityAttr>();
5077 }
5078 }
5079
5080 // Insert the invisible arguments, self and _cmd!
5081 ObjCMethod->createImplicitParams(Context, ObjCMethod->getClassInterface());
5082
5083 ActOnDocumentableDecl(ObjCMethod);
5084
5085 return ObjCMethod;
5086}
5087
5089 // Following is also an error. But it is caused by a missing @end
5090 // and diagnostic is issued elsewhere.
5091 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
5092 return false;
5093
5094 // If we switched context to translation unit while we are still lexically in
5095 // an objc container, it means the parser missed emitting an error.
5096 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
5097 return false;
5098
5099 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
5100 D->setInvalidDecl();
5101
5102 return true;
5103}
5104
5105/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
5106/// instance variables of ClassName into Decls.
5107void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
5108 IdentifierInfo *ClassName,
5109 SmallVectorImpl<Decl*> &Decls) {
5110 // Check that ClassName is a valid class
5111 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
5112 if (!Class) {
5113 Diag(DeclStart, diag::err_undef_interface) << ClassName;
5114 return;
5115 }
5117 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
5118 return;
5119 }
5120
5121 // Collect the instance variables
5123 Context.DeepCollectObjCIvars(Class, true, Ivars);
5124 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
5125 for (unsigned i = 0; i < Ivars.size(); i++) {
5126 const FieldDecl* ID = Ivars[i];
5127 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
5129 /*FIXME: StartL=*/ID->getLocation(),
5130 ID->getLocation(),
5131 ID->getIdentifier(), ID->getType(),
5132 ID->getBitWidth());
5133 Decls.push_back(FD);
5134 }
5135
5136 // Introduce all of these fields into the appropriate scope.
5137 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
5138 D != Decls.end(); ++D) {
5139 FieldDecl *FD = cast<FieldDecl>(*D);
5140 if (getLangOpts().CPlusPlus)
5141 PushOnScopeChains(FD, S);
5142 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
5143 Record->addDecl(FD);
5144 }
5145}
5146
5147/// Build a type-check a new Objective-C exception variable declaration.
5149 SourceLocation StartLoc,
5150 SourceLocation IdLoc,
5152 bool Invalid) {
5153 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
5154 // duration shall not be qualified by an address-space qualifier."
5155 // Since all parameters have automatic store duration, they can not have
5156 // an address space.
5157 if (T.getAddressSpace() != LangAS::Default) {
5158 Diag(IdLoc, diag::err_arg_with_address_space);
5159 Invalid = true;
5160 }
5161
5162 // An @catch parameter must be an unqualified object pointer type;
5163 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
5164 if (Invalid) {
5165 // Don't do any further checking.
5166 } else if (T->isDependentType()) {
5167 // Okay: we don't know what this type will instantiate to.
5168 } else if (T->isObjCQualifiedIdType()) {
5169 Invalid = true;
5170 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
5171 } else if (T->isObjCIdType()) {
5172 // Okay: we don't know what this type will instantiate to.
5173 } else if (!T->isObjCObjectPointerType()) {
5174 Invalid = true;
5175 Diag(IdLoc, diag::err_catch_param_not_objc_type);
5176 } else if (!T->castAs<ObjCObjectPointerType>()->getInterfaceType()) {
5177 Invalid = true;
5178 Diag(IdLoc, diag::err_catch_param_not_objc_type);
5179 }
5180
5181 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
5182 T, TInfo, SC_None);
5183 New->setExceptionVariable(true);
5184
5185 // In ARC, infer 'retaining' for variables of retainable type.
5186 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
5187 Invalid = true;
5188
5189 if (Invalid)
5190 New->setInvalidDecl();
5191 return New;
5192}
5193
5195 const DeclSpec &DS = D.getDeclSpec();
5196
5197 // We allow the "register" storage class on exception variables because
5198 // GCC did, but we drop it completely. Any other storage class is an error.
5200 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
5202 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
5203 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
5205 }
5206 if (DS.isInlineSpecified())
5207 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
5208 << getLangOpts().CPlusPlus17;
5211 diag::err_invalid_thread)
5214
5216
5217 // Check that there are no default arguments inside the type of this
5218 // exception object (C++ only).
5219 if (getLangOpts().CPlusPlus)
5221
5223 QualType ExceptionType = TInfo->getType();
5224
5225 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
5227 D.getIdentifierLoc(),
5228 D.getIdentifier(),
5229 D.isInvalidType());
5230
5231 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
5232 if (D.getCXXScopeSpec().isSet()) {
5233 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
5234 << D.getCXXScopeSpec().getRange();
5235 New->setInvalidDecl();
5236 }
5237
5238 // Add the parameter declaration into this scope.
5239 S->AddDecl(New);
5240 if (D.getIdentifier())
5241 IdResolver.AddDecl(New);
5242
5243 ProcessDeclAttributes(S, New, D);
5244
5245 if (New->hasAttr<BlocksAttr>())
5246 Diag(New->getLocation(), diag::err_block_on_nonlocal);
5247 return New;
5248}
5249
5250/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
5251/// initialization.
5254 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
5255 Iv= Iv->getNextIvar()) {
5256 QualType QT = Context.getBaseElementType(Iv->getType());
5257 if (QT->isRecordType())
5258 Ivars.push_back(Iv);
5259 }
5260}
5261
5263 // Load referenced selectors from the external source.
5264 if (ExternalSource) {
5266 ExternalSource->ReadReferencedSelectors(Sels);
5267 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
5268 ReferencedSelectors[Sels[I].first] = Sels[I].second;
5269 }
5270
5271 // Warning will be issued only when selector table is
5272 // generated (which means there is at lease one implementation
5273 // in the TU). This is to match gcc's behavior.
5274 if (ReferencedSelectors.empty() ||
5276 return;
5277 for (auto &SelectorAndLocation : ReferencedSelectors) {
5278 Selector Sel = SelectorAndLocation.first;
5279 SourceLocation Loc = SelectorAndLocation.second;
5281 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
5282 }
5283}
5284
5287 const ObjCPropertyDecl *&PDecl) const {
5288 if (Method->isClassMethod())
5289 return nullptr;
5290 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
5291 if (!IDecl)
5292 return nullptr;
5293 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
5294 /*shallowCategoryLookup=*/false,
5295 /*followSuper=*/false);
5296 if (!Method || !Method->isPropertyAccessor())
5297 return nullptr;
5298 if ((PDecl = Method->findPropertyDecl()))
5299 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
5300 // property backing ivar must belong to property's class
5301 // or be a private ivar in class's implementation.
5302 // FIXME. fix the const-ness issue.
5303 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
5304 IV->getIdentifier());
5305 return IV;
5306 }
5307 return nullptr;
5308}
5309
5310namespace {
5311 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
5312 /// accessor references the backing ivar.
5313 class UnusedBackingIvarChecker :
5314 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
5315 public:
5316 Sema &S;
5317 const ObjCMethodDecl *Method;
5318 const ObjCIvarDecl *IvarD;
5319 bool AccessedIvar;
5320 bool InvokedSelfMethod;
5321
5322 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5323 const ObjCIvarDecl *IvarD)
5324 : S(S), Method(Method), IvarD(IvarD),
5325 AccessedIvar(false), InvokedSelfMethod(false) {
5326 assert(IvarD);
5327 }
5328
5329 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5330 if (E->getDecl() == IvarD) {
5331 AccessedIvar = true;
5332 return false;
5333 }
5334 return true;
5335 }
5336
5337 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5339 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5340 InvokedSelfMethod = true;
5341 }
5342 return true;
5343 }
5344 };
5345} // end anonymous namespace
5346
5348 const ObjCImplementationDecl *ImplD) {
5349 if (S->hasUnrecoverableErrorOccurred())
5350 return;
5351
5352 for (const auto *CurMethod : ImplD->instance_methods()) {
5353 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5354 SourceLocation Loc = CurMethod->getLocation();
5355 if (Diags.isIgnored(DIAG, Loc))
5356 continue;
5357
5358 const ObjCPropertyDecl *PDecl;
5359 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5360 if (!IV)
5361 continue;
5362
5363 if (CurMethod->isSynthesizedAccessorStub())
5364 continue;
5365
5366 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5367 Checker.TraverseStmt(CurMethod->getBody());
5368 if (Checker.AccessedIvar)
5369 continue;
5370
5371 // Do not issue this warning if backing ivar is used somewhere and accessor
5372 // implementation makes a self call. This is to prevent false positive in
5373 // cases where the ivar is accessed by another method that the accessor
5374 // delegates to.
5375 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
5376 Diag(Loc, DIAG) << IV;
5377 Diag(PDecl->getLocation(), diag::note_property_declare);
5378 }
5379 }
5380}
Defines the clang::ASTContext interface.
int Id
Definition: ASTDiff.cpp:190
StringRef P
static char ID
Definition: Arena.cpp:183
#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:2955
llvm::MachO::Record Record
Definition: MachO.h:28
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 bool tryMatchRecordTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy, const Type *left, const Type *right)
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, Sema::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 void CheckProtocolMethodDefs(Sema &S, ObjCImplDecl *Impl, ObjCProtocolDecl *PDecl, bool &IncompleteImpl, const Sema::SelectorSet &InsMap, const Sema::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 Sema::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 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)
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:182
SourceManager & getSourceManager()
Definition: ASTContext.h:700
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:3022
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:2549
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2565
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:1575
IdentifierTable & Idents
Definition: ASTContext.h:639
const LangOptions & getLangOpts() const
Definition: ASTContext.h:770
SelectorTable & Selectors
Definition: ASTContext.h:640
QualType getObjCInstanceType()
Retrieve the Objective-C "instancetype" type, if already known; otherwise, returns a NULL type;.
Definition: ASTContext.h:1929
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:692
QualType getObjCIdType() const
Represents the Objective-CC id type.
Definition: ASTContext.h:2048
bool hasSameUnqualifiedType(QualType T1, QualType T2) const
Determine whether the given types are equivalent after cvr-qualifiers have been removed.
Definition: ASTContext.h:2592
CanQualType VoidTy
Definition: ASTContext.h:1086
QualType getAdjustedParameterType(QualType T) const
Perform adjustment on the parameter type of a function.
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:752
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:2597
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 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:629
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:5202
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:4673
SourceRange getRange() const
Definition: DeclSpec.h:79
bool isSet() const
Deprecated.
Definition: DeclSpec.h:227
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:2352
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1446
bool isFileContext() const
Definition: DeclBase.h:2147
void makeDeclVisibleInContext(NamedDecl *D)
Makes a declaration visible within this context.
Definition: DeclBase.cpp:1976
bool isObjCContainer() const
Definition: DeclBase.h:2115
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1921
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1699
Decl::Kind getDeclKind() const
Definition: DeclBase.h:2069
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:246
static const TST TST_typename
Definition: DeclSpec.h:305
void ClearStorageClassSpecs()
Definition: DeclSpec.h:511
SourceLocation getStorageClassSpecLoc() const
Definition: DeclSpec.h:506
SCS getStorageClassSpec() const
Definition: DeclSpec.h:497
bool SetTypeSpecType(TST T, SourceLocation Loc, const char *&PrevSpec, unsigned &DiagID, const PrintingPolicy &Policy)
Definition: DeclSpec.cpp:856
void SetRangeEnd(SourceLocation Loc)
Definition: DeclSpec.h:705
void SetRangeStart(SourceLocation Loc)
Definition: DeclSpec.h:704
SCS
storage-class-specifier
Definition: DeclSpec.h:250
TSCS getThreadStorageClassSpec() const
Definition: DeclSpec.h:498
bool isInlineSpecified() const
Definition: DeclSpec.h:633
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:558
SourceLocation getThreadStorageClassSpecLoc() const
Definition: DeclSpec.h:507
SourceLocation getInlineSpecLoc() const
Definition: DeclSpec.h:636
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition: DeclBase.h:440
T * getAttr() const
Definition: DeclBase.h:578
ASTContext & getASTContext() const LLVM_READONLY
Definition: DeclBase.cpp:501
void addAttr(Attr *A)
Definition: DeclBase.cpp:975
bool isImplicit() const
isImplicit - Indicates whether the declaration was implicitly generated by the implementation.
Definition: DeclBase.h:598
bool isUnavailable(std::string *Message=nullptr) const
Determine whether this declaration is marked 'unavailable'.
Definition: DeclBase.h:764
AvailabilityResult getAvailability(std::string *Message=nullptr, VersionTuple EnclosingVersion=VersionTuple(), StringRef *RealizedPlatform=nullptr) const
Determine the availability of the given declaration.
Definition: DeclBase.cpp:709
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
bool isUnconditionallyVisible() const
Determine whether this declaration is definitely visible to name lookup, independent of whether the o...
Definition: DeclBase.h:859
void setTopLevelDeclInObjCContainer(bool V=true)
Definition: DeclBase.h:637
bool isReferenced() const
Whether any declaration of this entity was referenced.
Definition: DeclBase.cpp:555
ObjCDeclQualifier
ObjCDeclQualifier - 'Qualifiers' written next to the return and parameter types in method declaration...
Definition: DeclBase.h:197
@ OBJC_TQ_CSNullability
The nullability qualifier is set when the nullability of the result or parameter was expressed via a ...
Definition: DeclBase.h:209
bool isInvalidDecl() const
Definition: DeclBase.h:593
SourceLocation getLocation() const
Definition: DeclBase.h:444
bool isDeprecated(std::string *Message=nullptr) const
Determine whether this declaration is marked 'deprecated'.
Definition: DeclBase.h:755
void setImplicit(bool I=true)
Definition: DeclBase.h:599
DeclContext * getDeclContext()
Definition: DeclBase.h:453
void dropAttr()
Definition: DeclBase.h:561
void setDeclContext(DeclContext *DC)
setDeclContext - Set both the semantic and lexical DeclContext to DC.
Definition: DeclBase.cpp:336
bool hasAttr() const
Definition: DeclBase.h:582
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:340
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:799
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1899
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2046
SourceLocation getIdentifierLoc() const
Definition: DeclSpec.h:2335
const CXXScopeSpec & getCXXScopeSpec() const
getCXXScopeSpec - Return the C++ scope specifier (global scope or nested-name-specifier) that is part...
Definition: DeclSpec.h:2061
IdentifierInfo * getIdentifier() const
Definition: DeclSpec.h:2329
void AddTypeInfo(const DeclaratorChunk &TI, ParsedAttributes &&attrs, SourceLocation EndLoc)
AddTypeInfo - Add a chunk to this declarator.
Definition: DeclSpec.h:2352
bool isInvalidType() const
Definition: DeclSpec.h:2713
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2081
DeclSpec & getMutableDeclSpec()
getMutableDeclSpec - Return a non-const version of the DeclSpec.
Definition: DeclSpec.h:2053
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition: Diagnostic.h:916
Represents a member of a struct/union/class.
Definition: Decl.h:3025
bool isBitField() const
Determines whether this field is a bitfield.
Definition: Decl.h:3116
unsigned getBitWidthValue(const ASTContext &Ctx) const
Computes the bit width of this field, if this is a bit field.
Definition: Decl.cpp:4559
Expr * getBitWidth() const
Returns the expression that represents the bit width, if this field is a bit field.
Definition: Decl.h:3129
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.
clang::ObjCRuntime ObjCRuntime
Definition: LangOptions.h:453
Represents the results of name lookup.
Definition: Lookup.h:46
NamedDecl * getFoundDecl() const
Fetch the unique decl found by this lookup.
Definition: Lookup.h:563
bool isSingleResult() const
Determines if this names a single result which is not an unresolved value using decl.
Definition: Lookup.h:328
@ 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
static ObjCAtDefsFieldDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, Expr *BW)
Definition: DeclObjC.cpp:1917
ObjCCategoryDecl - Represents a category declaration.
Definition: DeclObjC.h:2323
static ObjCCategoryDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation AtLoc, SourceLocation ClassNameLoc, SourceLocation CategoryNameLoc, IdentifierInfo *Id, ObjCInterfaceDecl *IDecl, ObjCTypeParamList *typeParamList, SourceLocation IvarLBraceLoc=SourceLocation(), SourceLocation IvarRBraceLoc=SourceLocation())
Definition: DeclObjC.cpp:2136
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:2387
ObjCCategoryImplDecl * getImplementation() const
Definition: DeclObjC.cpp:2169
ObjCInterfaceDecl * getClassInterface()
Definition: DeclObjC.h:2368
bool IsClassExtension() const
Definition: DeclObjC.h:2433
const ObjCProtocolList & getReferencedProtocols() const
Definition: DeclObjC.h:2392
void setImplementation(ObjCCategoryImplDecl *ImplD)
Definition: DeclObjC.cpp:2174
ObjCCategoryImplDecl - An object of this class encapsulates a category @implementation declaration.
Definition: DeclObjC.h:2542
static ObjCCategoryImplDecl * Create(ASTContext &C, DeclContext *DC, IdentifierInfo *Id, ObjCInterfaceDecl *classInterface, SourceLocation nameLoc, SourceLocation atStartLoc, SourceLocation CategoryNameLoc)
Definition: DeclObjC.cpp:2194
ObjCCategoryDecl * getCategoryDecl() const
Definition: DeclObjC.cpp:2213
ObjCCompatibleAliasDecl - Represents alias of a class.
Definition: DeclObjC.h:2772
static ObjCCompatibleAliasDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, IdentifierInfo *Id, ObjCInterfaceDecl *aliasedClass)
Definition: DeclObjC.cpp:2349
ObjCContainerDecl - Represents a container for method declarations.
Definition: DeclObjC.h:944
ObjCMethodDecl * getMethod(Selector Sel, bool isInstance, bool AllowHidden=false) const
Definition: DeclObjC.cpp:92
method_range methods() const
Definition: DeclObjC.h:1012
SourceRange getAtEndRange() const
Definition: DeclObjC.h:1099
instmeth_range instance_methods() const
Definition: DeclObjC.h:1029
ObjCIvarDecl * getIvarDecl(IdentifierInfo *Id) const
getIvarDecl - This method looks up an ivar in this ContextDecl.
Definition: DeclObjC.cpp:80
void setAtEndRange(SourceRange atEnd)
Definition: DeclObjC.h:1101
ObjCMethodDecl * getClassMethod(Selector Sel, bool AllowHidden=false) const
Definition: DeclObjC.h:1067
prop_range properties() const
Definition: DeclObjC.h:963
classmeth_range class_methods() const
Definition: DeclObjC.h:1046
ObjCMethodDecl * getInstanceMethod(Selector Sel, bool AllowHidden=false) const
Definition: DeclObjC.h:1062
Captures information about "declaration specifiers" specific to Objective-C.
Definition: DeclSpec.h:896
ObjCDeclQualifier
ObjCDeclQualifier - Qualifier used on types in method declarations.
Definition: DeclSpec.h:904
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: DeclSpec.h:920
propimpl_range property_impls() const
Definition: DeclObjC.h:2510
const ObjCInterfaceDecl * getClassInterface() const
Definition: DeclObjC.h:2483
ObjCImplementationDecl - Represents a class definition - this is where method definitions are specifi...
Definition: DeclObjC.h:2595
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:2298
const ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.h:2732
Represents an ObjC class declaration.
Definition: DeclObjC.h:1150
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:443
ObjCTypeParamList * getTypeParamList() const
Retrieve the type parameters of this class.
Definition: DeclObjC.cpp:321
ObjCInterfaceDecl * lookupInheritedClass(const IdentifierInfo *ICName)
lookupInheritedClass - This method returns ObjCInterfaceDecl * of the super class whose name is passe...
Definition: DeclObjC.cpp:669
ivar_iterator ivar_end() const
Definition: DeclObjC.h:1457
static ObjCInterfaceDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation atLoc, IdentifierInfo *Id, ObjCTypeParamList *typeParamList, ObjCInterfaceDecl *PrevDecl, SourceLocation ClassLoc=SourceLocation(), bool isInternal=false)
Definition: DeclObjC.cpp:1542
llvm::iterator_range< specific_decl_iterator< ObjCIvarDecl > > ivar_range
Definition: DeclObjC.h:1445
unsigned ivar_size() const
Definition: DeclObjC.h:1465
ObjCIvarDecl * lookupInstanceVariable(IdentifierInfo *IVarName, ObjCInterfaceDecl *&ClassDeclared)
Definition: DeclObjC.cpp:638
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:1481
bool hasDefinition() const
Determine whether this class has been defined.
Definition: DeclObjC.h:1524
ivar_range ivars() const
Definition: DeclObjC.h:1447
all_protocol_range all_referenced_protocols() const
Definition: DeclObjC.h:1413
visible_extensions_range visible_extensions() const
Definition: DeclObjC.h:1719
bool isImplicitInterfaceDecl() const
isImplicitInterfaceDecl - check that this is an implicitly declared ObjCInterfaceDecl node.
Definition: DeclObjC.h:1888
ObjCIvarDecl * all_declared_ivar_begin()
all_declared_ivar_begin - return first ivar declared in this class, its extensions and its implementa...
Definition: DeclObjC.cpp:1678
ivar_iterator ivar_begin() const
Definition: DeclObjC.h:1449
bool ivar_empty() const
Definition: DeclObjC.h:1469
void setImplementation(ObjCImplementationDecl *ImplD)
Definition: DeclObjC.cpp:1648
known_categories_range known_categories() const
Definition: DeclObjC.h:1683
void setSuperClass(TypeSourceInfo *superClass)
Definition: DeclObjC.h:1584
ObjCCategoryDecl * FindCategoryDeclaration(IdentifierInfo *CategoryId) const
FindCategoryDeclaration - Finds category declaration in the list of categories for this class and ret...
Definition: DeclObjC.cpp:1755
const ObjCProtocolList & getReferencedProtocols() const
Definition: DeclObjC.h:1330
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:700
ObjCImplementationDecl * getImplementation() const
Definition: DeclObjC.cpp:1635
void setEndOfDefinitionLoc(SourceLocation LE)
Definition: DeclObjC.h:1880
void startDefinition()
Starts the definition of this Objective-C class, taking it from a forward declaration (@class) to a d...
Definition: DeclObjC.cpp:617
visible_categories_range visible_categories() const
Definition: DeclObjC.h:1649
ObjCInterfaceDecl * getCanonicalDecl() override
Retrieves the canonical declaration of this Objective-C class.
Definition: DeclObjC.h:1910
ObjCInterfaceDecl * getSuperClass() const
Definition: DeclObjC.cpp:351
ObjCInterfaceDecl * getDefinition()
Retrieve the definition of this class, or NULL if this class has been forward-declared (with @class) ...
Definition: DeclObjC.h:1538
void startDuplicateDefinitionForComparison()
Starts the definition without sharing it with other redeclarations.
Definition: DeclObjC.cpp:627
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:1805
Interfaces are the core concept in Objective-C for object oriented design.
Definition: Type.h:6495
ObjCIvarDecl - Represents an ObjC instance variable.
Definition: DeclObjC.h:1947
ObjCIvarDecl * getNextIvar()
Definition: DeclObjC.h:1983
ObjCIvarRefExpr - A reference to an ObjC instance variable.
Definition: ExprObjC.h:549
ObjCIvarDecl * getDecl()
Definition: ExprObjC.h:579
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
Expr * getInstanceReceiver()
Returns the object expression (receiver) for an instance message, or null for a message that is not a...
Definition: ExprObjC.h:1260
@ Instance
The receiver is an object instance.
Definition: ExprObjC.h:953
ReceiverKind getReceiverKind() const
Determine the kind of receiver that this message is being sent to.
Definition: ExprObjC.h:1234
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:853
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:1344
void setStarLoc(SourceLocation Loc)
Definition: TypeLoc.h:1350
Represents a pointer to an Objective C object.
Definition: Type.h:6551
bool isObjCQualifiedIdType() const
True if this is equivalent to 'id.
Definition: Type.h:6626
bool isObjCIdType() const
True if this is equivalent to the 'id' type, i.e.
Definition: Type.h:6609
const ObjCInterfaceType * getInterfaceType() const
If this pointer points to an Objective C @interface type, gets the type for that interface.
Definition: Type.cpp:1736
Represents a class type in Objective C.
Definition: Type.h:6297
bool isObjCClass() const
Definition: Type.h:6365
ObjCInterfaceDecl * getInterface() const
Gets the interface declaration for this object type, if the base type really is an interface.
Definition: Type.h:6530
bool isObjCId() const
Definition: Type.h:6361
Represents one property declaration in an Objective-C interface.
Definition: DeclObjC.h:729
ObjCIvarDecl * getPropertyIvarDecl() const
Definition: DeclObjC.h:920
ObjCPropertyImplDecl - Represents implementation declaration of a property in a class or category imp...
Definition: DeclObjC.h:2802
Represents an Objective-C protocol declaration.
Definition: DeclObjC.h:2079
void startDuplicateDefinitionForComparison()
Starts the definition without sharing it with other redeclarations.
Definition: DeclObjC.cpp:2037
bool hasDefinition() const
Determine whether this protocol has a definition.
Definition: DeclObjC.h:2232
bool isThisDeclarationADefinition() const
Determine whether this particular declaration is also the definition.
Definition: DeclObjC.h:2255
static ObjCProtocolDecl * Create(ASTContext &C, DeclContext *DC, IdentifierInfo *Id, SourceLocation nameLoc, SourceLocation atStartLoc, ObjCProtocolDecl *PrevDecl)
Definition: DeclObjC.cpp:1947
const ObjCProtocolList & getReferencedProtocols() const
Definition: DeclObjC.h:2147
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:2203
ObjCProtocolDecl * getDefinition()
Retrieve the definition of this protocol, if any.
Definition: DeclObjC.h:2244
void startDefinition()
Starts the definition of this Objective-C protocol.
Definition: DeclObjC.cpp:2029
protocol_range protocols() const
Definition: DeclObjC.h:2155
A list of Objective-C protocols, along with the source locations at which they were referenced.
Definition: DeclObjC.h:101
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:639
ObjCTypeParamVariance getVariance() const
Determine the variance of this type parameter.
Definition: DeclObjC.h:622
void setVariance(ObjCTypeParamVariance variance)
Set the variance of this type parameter.
Definition: DeclObjC.h:627
SourceLocation getVarianceLoc() const
Retrieve the location of the variance keyword.
Definition: DeclObjC.h:632
Stores a list of Objective-C type parameters for a parameterized class or a category/extension thereo...
Definition: DeclObjC.h:658
SourceRange getSourceRange() const
Definition: DeclObjC.h:710
unsigned size() const
Determine the number of type parameters in this list.
Definition: DeclObjC.h:685
ObjCTypeParamDecl * back() const
Definition: DeclObjC.h:703
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:708
Represents a parameter to a function.
Definition: Decl.h:1749
void setObjCDeclQualifier(ObjCDeclQualifier QTVal)
Definition: Decl.h:1817
ObjCDeclQualifier getObjCDeclQualifier() const
Definition: Decl.h:1813
void setObjCMethodScopeInfo(unsigned parameterIndex)
Definition: Decl.h:1777
static const ParsedAttributesView & none()
Definition: ParsedAttr.h:831
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:2898
A (possibly-)qualified type.
Definition: Type.h:737
bool hasQualifiers() const
Determine whether this type has any qualifiers.
Definition: Type.h:6990
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:804
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7027
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition: Type.h:6942
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition: Type.h:1229
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:6995
static std::string getAsString(SplitQualType split, const PrintingPolicy &Policy)
Definition: Type.h:1124
Qualifiers getLocalQualifiers() const
Retrieve the set of qualifiers local to this particular QualType instance, not including any qualifie...
Definition: Type.h:6934
The collection of all-type qualifiers we support.
Definition: Type.h:147
void removeCVRQualifiers(unsigned mask)
Definition: Type.h:302
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition: Type.h:168
@ OCL_Weak
Reading or writing from this object requires a barrier call.
Definition: Type.h:178
bool hasObjCLifetime() const
Definition: Type.h:351
bool empty() const
Definition: Type.h:440
std::string getAsString() const
Represents a struct/union/class.
Definition: Decl.h:4133
field_iterator field_end() const
Definition: Decl.h:4342
field_iterator field_begin() const
Definition: Decl.cpp:5035
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5092
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:3009
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
Selector getSelector(unsigned NumArgs, 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 RAII object to temporarily push a declaration context.
Definition: Sema.h:2671
llvm::DenseMap< Selector, Lists >::iterator iterator
Definition: Sema.h:12056
iterator find(Selector Sel)
Definition: Sema.h:12059
std::pair< ObjCMethodList, ObjCMethodList > Lists
Definition: Sema.h:12055
std::pair< iterator, bool > insert(std::pair< Selector, Lists > &&Val)
Definition: Sema.h:12060
A generic diagnostic builder for errors which may or may not be deferred.
Definition: Sema.h:598
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:426
ObjCMethodDecl * LookupMethodInObjectType(Selector Sel, QualType Ty, bool IsInstance)
LookupMethodInType - Look up a method in an ObjCObjectType.
void CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI, SmallVectorImpl< ObjCIvarDecl * > &Ivars)
CollectIvarsToConstructOrDestruct - Collect those ivars which require initialization.
ParsedType CreateParsedType(QualType T, TypeSourceInfo *TInfo)
Package the given type and TSI into a ParsedType.
Definition: SemaType.cpp:6768
void ActOnObjCContainerStartDefinition(ObjCContainerDecl *IDecl)
Definition: SemaDecl.cpp:18305
llvm::MapVector< Selector, SourceLocation > ReferencedSelectors
Method selectors used in a @selector expression.
Definition: Sema.h:12051
void CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, const ObjCMethodDecl *Overridden)
Check whether the given new method is a valid override of the given overridden method,...
bool CheckARCMethodDecl(ObjCMethodDecl *method)
Check a method declaration for compatibility with the Objective-C ARC conventions.
void ActOnStartOfObjCMethodDef(Scope *S, Decl *D)
ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible and user declared,...
DeclGroupPtrTy ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef< Decl * > Decls)
LookupNameKind
Describes the kind of name lookup to perform.
Definition: Sema.h:7603
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:7607
@ LookupObjCProtocolName
Look up the name of an Objective-C protocol.
Definition: Sema.h:7644
@ LookupAnyName
Look up any declaration with any name.
Definition: Sema.h:7652
void DiagnoseFunctionSpecifiers(const DeclSpec &DS)
Diagnose function specifiers on a declaration of an identifier that does not identify a function.
Definition: SemaDecl.cpp:6746
ObjCCategoryDecl * ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, ObjCTypeParamList *typeParamList, IdentifierInfo *CategoryName, SourceLocation CategoryLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList)
bool isSelfExpr(Expr *RExpr)
Private Helper predicate to check for 'self'.
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: Sema.cpp:1911
DeclGroupPtrTy ActOnForwardClassDeclaration(SourceLocation Loc, IdentifierInfo **IdentList, SourceLocation *IdentLocs, ArrayRef< ObjCTypeParamList * > TypeParamLists, unsigned NumElts)
void CheckConflictingOverridingMethod(ObjCMethodDecl *Method, ObjCMethodDecl *Overridden, bool IsProtocolMethodDecl)
ObjCImplementationDecl * ActOnStartClassImplementation(SourceLocation AtClassImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperClassname, SourceLocation SuperClassLoc, const ParsedAttributesView &AttrList)
ObjCContainerKind
Definition: Sema.h:12096
@ OCK_Interface
Definition: Sema.h:12098
@ OCK_ClassExtension
Definition: Sema.h:12101
@ OCK_Category
Definition: Sema.h:12100
@ OCK_Implementation
Definition: Sema.h:12102
@ OCK_CategoryImplementation
Definition: Sema.h:12103
@ OCK_None
Definition: Sema.h:12097
@ OCK_Protocol
Definition: Sema.h:12099
std::unique_ptr< NSAPI > NSAPIObj
Caches identifiers/selectors for NSFoundation APIs.
Definition: Sema.h:12421
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:1097
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:18205
ObjCTypeParamList * actOnObjCTypeParamList(Scope *S, SourceLocation lAngleLoc, ArrayRef< Decl * > typeParams, SourceLocation rAngleLoc)
void CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl *CatIMP)
CheckCategoryVsClassMethodMatches - Checks that methods implemented in category matches with those im...
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 WarnExactTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl)
WarnExactTypedMethods - This routine issues a warning if method implementation declaration matches ex...
Decl * ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef< Decl * > allMethods=std::nullopt, ArrayRef< DeclGroupPtrTy > allTUVars=std::nullopt)
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: SemaType.cpp:1150
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...
ASTContext & Context
Definition: Sema.h:1030
void DiagnoseUnusedBackingIvarInAccessor(Scope *S, const ObjCImplementationDecl *ImplD)
DiagnoseUnusedBackingIvarInAccessor - Issue an 'unused' warning if ivar which backs the property is n...
void ActOnSuperClassOfClassInterface(Scope *S, SourceLocation AtInterfaceLoc, ObjCInterfaceDecl *IDecl, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *SuperName, SourceLocation SuperLoc, ArrayRef< ParsedType > SuperTypeArgs, SourceRange SuperTypeArgsRange)
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1517
ASTContext & getASTContext() const
Definition: Sema.h:501
void CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod, ObjCInterfaceDecl *CurrentClass, ResultTypeCompatibilityKind RTC)
NamedDecl * LookupSingleName(Scope *S, DeclarationName Name, SourceLocation Loc, LookupNameKind NameKind, RedeclarationKind Redecl=NotForRedeclaration)
Look up a name, looking for a single declaration.
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 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...
void CheckObjCMethodDirectOverrides(ObjCMethodDecl *method, ObjCMethodDecl *overridden)
ObjCMethodDecl * getCurMethodDecl()
getCurMethodDecl - If inside of a method body, this returns a pointer to the method decl for the meth...
Definition: Sema.cpp:1494
void PushFunctionScope()
Enter a new function scope.
Definition: Sema.cpp:2141
bool CheckFunctionReturnType(QualType T, SourceLocation Loc)
Definition: SemaType.cpp:2972
void CheckImplementationIvars(ObjCImplementationDecl *ImpDecl, ObjCIvarDecl **Fields, unsigned nIvars, SourceLocation Loc)
CheckImplementationIvars - This routine checks if the instance variables listed in the implelementati...
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:58
void AddAnyMethodToGlobalPool(Decl *D)
AddAnyMethodToGlobalPool - Add any method, instance or factory to global pool.
const LangOptions & getLangOpts() const
Definition: Sema.h:494
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...
void DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId, SourceLocation ProtocolLoc, IdentifierInfo *TypeArgId, SourceLocation TypeArgLoc, bool SelectProtocolFirst=false)
ObjCProtocolDecl * ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName, SourceLocation ProtocolLoc, Decl *const *ProtoRefNames, unsigned NumProtoRefs, const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc, const ParsedAttributesView &AttrList, SkipBodyInfo *SkipBody)
void DiagnoseOwningPropertyGetterSynthesis(const ObjCImplementationDecl *D)
void updateOutOfDateSelector(Selector Sel)
void AtomicPropertySetterGetterRules(ObjCImplDecl *IMPDecl, ObjCInterfaceDecl *IDecl)
AtomicPropertySetterGetterRules - This routine enforces the rule (via warning) when atomic property h...
void CheckExtraCXXDefaultArguments(Declarator &D)
CheckExtraCXXDefaultArguments - Check for any extra default arguments in the declarator,...
const LangOptions & LangOpts
Definition: Sema.h:1028
void SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation)
SetIvarInitializers - This routine builds initialization ASTs for the Objective-C implementation whos...
void AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false)
AddInstanceMethodToGlobalPool - All instance methods in a translation unit are added to a global pool...
Definition: Sema.h:12386
void ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart, IdentifierInfo *ClassName, SmallVectorImpl< Decl * > &Decls)
Called whenever @defs(ClassName) is encountered in the source.
void popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList)
ParmVarDecl * CheckParameter(DeclContext *DC, SourceLocation StartLoc, SourceLocation NameLoc, IdentifierInfo *Name, QualType T, TypeSourceInfo *TSInfo, StorageClass SC)
Definition: SemaDecl.cpp:15359
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...
const ObjCMethodDecl * SelectorsForTypoCorrection(Selector Sel, QualType ObjectType=QualType())
DeclContext * getCurLexicalContext() const
Definition: Sema.h:873
sema::FunctionScopeInfo * getCurFunction() const
Definition: Sema.h:1064
DeclGroupPtrTy BuildDeclaratorGroup(MutableArrayRef< Decl * > Group)
BuildDeclaratorGroup - convert a list of declarations into a declaration group, performing any necess...
Definition: SemaDecl.cpp:15025
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)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1163
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.
DeclResult actOnObjCTypeParam(Scope *S, ObjCTypeParamVariance variance, SourceLocation varianceLoc, unsigned index, IdentifierInfo *paramName, SourceLocation paramLoc, SourceLocation colonLoc, ParsedType typeBound)
void ActOnDocumentableDecl(Decl *D)
Should be called on all declarations that might have attached documentation comments.
Definition: SemaDecl.cpp:15065
bool AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R, bool receiverIdOrClass, SmallVectorImpl< ObjCMethodDecl * > &Methods)
MethodMatchStrategy
Definition: Sema.h:12094
@ MMS_strict
Definition: Sema.h:12094
@ MMS_loose
Definition: Sema.h:12094
ObjCProtocolDecl * LookupProtocol(IdentifierInfo *II, SourceLocation IdLoc, RedeclarationKind Redecl=NotForRedeclaration)
Find the protocol with the given name, if any.
VarDecl * BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType ExceptionType, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, bool Invalid=false)
Build a type-check a new Objective-C exception variable declaration.
ObjCMethodDecl * LookupImplementedMethodInGlobalPool(Selector Sel)
LookupImplementedMethodInGlobalPool - Returns the method which has an implementation.
bool hasVisibleDefinition(NamedDecl *D, NamedDecl **Suggested, bool OnlyNeedComplete=false)
Determine if D has a visible definition.
Definition: SemaType.cpp:9371
GlobalMethodPool MethodPool
Method Pool - allows efficient lookup when typechecking messages to "id".
Definition: Sema.h:12076
void ActOnObjCContainerFinishDefinition()
Definition: SemaDecl.cpp:18412
SourceManager & getSourceManager() const
Definition: Sema.h:499
void DiagnoseMissingDesignatedInitOverrides(const ObjCImplementationDecl *ImplD, const ObjCInterfaceDecl *IFD)
void DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT, ObjCInterfaceDecl *ID)
DiagnoseClassExtensionDupMethods - Check for duplicate declaration of a class method in its extension...
RedeclarationKind forRedeclarationInCurContext() const
Definition: Sema.h:7701
void WarnConflictingTypedMethods(ObjCMethodDecl *Method, ObjCMethodDecl *MethodDecl, bool IsProtocolMethodDecl)
TypeResult ActOnTypeName(Declarator &D)
Definition: SemaType.cpp:6787
void AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method, bool impl=false)
AddFactoryMethodToGlobalPool - Same as above, but for factory methods.
Definition: Sema.h:12392
ExternalSemaSource * getExternalSource() const
Definition: Sema.h:504
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:224
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void ProcessPropertyDecl(ObjCPropertyDecl *property)
Process the specified property declaration and create decls for the setters and getters as needed.
ObjCInterfaceDecl * getObjCInterfaceDecl(IdentifierInfo *&Id, SourceLocation IdLoc, bool TypoCorrection=false)
Look for an Objective-C class in the translation unit.
Definition: SemaDecl.cpp:2310
@ CTK_NonError
Definition: Sema.h:7858
@ CTK_ErrorRecovery
Definition: Sema.h:7859
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 mergeDeclAttributes(NamedDecl *New, Decl *Old, AvailabilityMergeKind AMK=AMK_Redeclaration)
mergeDeclAttributes - Copy attributes from the Old decl to the New one.
Definition: SemaDecl.cpp:3179
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...
ASTConsumer & Consumer
Definition: Sema.h:1031
void DiagnoseUnimplementedProperties(Scope *S, ObjCImplDecl *IMPDecl, ObjCContainerDecl *CDecl, bool SynthesizeProperties)
DiagnoseUnimplementedProperties - This routine warns on those properties which must be implemented by...
bool MatchTwoMethodDeclarations(const ObjCMethodDecl *Method, const ObjCMethodDecl *PrevMethod, MethodMatchStrategy strategy=MMS_strict)
MatchTwoMethodDeclarations - Checks if two methods' type match and returns true, or false,...
ObjCIvarDecl * GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method, const ObjCPropertyDecl *&PDecl) const
GetIvarBackingPropertyAccessor - If method is a property setter/getter and it property has a backing ...
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...
bool inferObjCARCLifetime(ValueDecl *decl)
Definition: SemaDecl.cpp:6964
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:6102
void diagnoseTypo(const TypoCorrection &Correction, const PartialDiagnostic &TypoDiag, bool ErrorRecovery=true)
void addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method)
Add the given method to the list of globally-known methods.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:9249
void DiagnoseUseOfUnimplementedSelectors()
Scope * TUScope
Translation Unit Scope - useful to Objective-C actions that need to lookup file scope declarations in...
Definition: Sema.h:1002
PartialDiagnostic PDiag(unsigned DiagID=0)
Build a partial diagnostic.
Definition: SemaInternal.h:24
ResultTypeCompatibilityKind
Describes the compatibility of a result type with its method.
Definition: Sema.h:12245
@ RTC_Incompatible
Definition: Sema.h:12247
@ RTC_Compatible
Definition: Sema.h:12246
@ RTC_Unknown
Definition: Sema.h:12248
void ReadMethodPool(Selector Sel)
Read the contents of the method pool for a given selector from external storage.
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:6669
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1324
DiagnosticsEngine & Diags
Definition: Sema.h:1032
DeclGroupPtrTy ActOnForwardProtocolDeclaration(SourceLocation AtProtoclLoc, ArrayRef< IdentifierLocPair > IdentList, const ParsedAttributesView &attrList)
ActOnForwardProtocolDeclaration - Handle @protocol foo;.
void DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, ObjCInterfaceDecl *SID)
DiagnoseDuplicateIvars - Check for duplicate ivars in the entire class at the start of @implementatio...
bool CheckObjCDeclScope(Decl *D)
Checks that the Objective-C declaration is declared in the global scope.
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:988
void mergeObjCMethodDecls(ObjCMethodDecl *New, ObjCMethodDecl *Old)
Definition: SemaDecl.cpp:4382
void ProcessAPINotes(Decl *D)
Map any API notes provided for this declaration to attributes on the declaration.
Decl * ActOnObjCExceptionDecl(Scope *S, Declarator &D)
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:3213
bool CheckForwardProtocolDeclarationForCircularDependency(IdentifierInfo *PName, SourceLocation &PLoc, SourceLocation PrevLoc, const ObjCList< ObjCProtocolDecl > &PList)
IdentifierResolver IdResolver
Definition: Sema.h:2664
llvm::SmallVector< std::pair< SourceLocation, const BlockDecl * >, 1 > ImplicitlyRetainedSelfLocs
List of SourceLocations where 'self' is implicitly retained inside a block.
Definition: Sema.h:6677
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...
ObjCContainerKind getObjCContainerKind() const
void diagnoseNullResettableSynthesizedSetters(const ObjCImplDecl *impDecl)
Diagnose any null-resettable synthesized setters.
void DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl< ObjCMethodDecl * > &Methods, Selector Sel, SourceRange R, bool receiverIdOrClass)
ObjCCategoryImplDecl * ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc, IdentifierInfo *ClassName, SourceLocation ClassLoc, IdentifierInfo *CatName, SourceLocation CatLoc, const ParsedAttributesView &AttrList)
ActOnStartCategoryImplementation - Perform semantic checks on the category implementation declaration...
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:3755
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
Definition: TargetInfo.h:1220
StringRef getPlatformName() const
Retrieve the name of the platform as it is used in the availability attribute.
Definition: TargetInfo.h:1608
VersionTuple getPlatformMinVersion() const
Retrieve the minimum desired version of the platform, to which the program should be compiled.
Definition: TargetInfo.h:1612
Represents a declaration of a type.
Definition: Decl.h:3357
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:3384
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:458
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:6873
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:6884
The base class of the type hierarchy.
Definition: Type.h:1606
bool isVoidType() const
Definition: Type.h:7443
bool isIncompleteArrayType() const
Definition: Type.h:7228
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:7479
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:7724
const ObjCObjectPointerType * getAsObjCInterfacePointerType() const
Definition: Type.cpp:1796
bool isScalarType() const
Definition: Type.h:7538
bool isObjCQualifiedIdType() const
Definition: Type.h:7303
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:651
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2420
ScalarTypeKind getScalarTypeKind() const
Given that this is a scalar type, classify it.
Definition: Type.cpp:2233
bool isObjCIdType() const
Definition: Type.h:7315
bool isObjCObjectType() const
Definition: Type.h:7286
bool isObjCLifetimeType() const
Returns true if objects of this type have lifetime semantics under ARC.
Definition: Type.cpp:4778
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2299
bool isObjCObjectPointerType() const
Definition: Type.h:7282
bool isVectorType() const
Definition: Type.h:7256
bool isObjCQualifiedClassType() const
Definition: Type.h:7309
bool isObjCClassType() const
Definition: Type.h:7321
ScalarTypeKind
Definition: Type.h:2393
@ STK_BlockPointer
Definition: Type.h:2395
@ STK_Bool
Definition: Type.h:2398
@ STK_ObjCObjectPointer
Definition: Type.h:2396
@ STK_CPointer
Definition: Type.h:2394
@ STK_Integral
Definition: Type.h:2399
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7657
bool isRecordType() const
Definition: Type.h:7244
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4516
bool isObjCIndependentClassType() const
Definition: Type.cpp:4752
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3399
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:3449
QualType getUnderlyingType() const
Definition: Decl.h:3454
Simple class containing the result of Sema::CorrectTypo.
DeclClass * getCorrectionDeclAs() const
void setType(QualType newType)
Definition: Decl.h:718
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2148
void setExceptionVariable(bool EV)
Definition: Decl.h:1474
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:54
@ SC_None
Definition: Specifiers.h:247
ThreadStorageClassSpecifier
Thread storage-class-specifier.
Definition: Specifiers.h:232
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:3399
@ Class
The "class" keyword.
AvailabilityResult
Captures the result of checking the availability of a declaration.
Definition: DeclBase.h:71
@ AR_Deprecated
Definition: DeclBase.h:74
@ AR_Unavailable
Definition: DeclBase.h:75
std::pair< NullabilityKind, bool > DiagNullabilityKind
A nullability kind paired with a bit indicating whether it used a context-sensitive keyword.
Definition: Diagnostic.h:1542
bool declaresSameEntity(const Decl *D1, const Decl *D2)
Determine whether two declarations declare the same entity.
Definition: DeclBase.h:1285
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.
#define false
Definition: stdbool.h:22
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:1329
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:1664
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
IdentifierInfo * Name
Definition: Sema.h:12211
SourceLocation NameLoc
Definition: Sema.h:12212
NamedDecl * Previous
Definition: Sema.h:2784
uint64_t Width
Definition: ASTContext.h:153
unsigned Align
Definition: ASTContext.h:154