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