blob: 595cc76cd4a314ce8c996424ebaeef03ae8355b1 [file] [log] [blame]
Chris Lattnerda463fe2007-12-12 07:09:47 +00001//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattnerda463fe2007-12-12 07:09:47 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for Objective C declarations.
11//
12//===----------------------------------------------------------------------===//
13
Mehdi Amini9670f842016-07-18 19:02:11 +000014#include "TypeLocBuilder.h"
John McCall31168b02011-06-15 23:02:42 +000015#include "clang/AST/ASTConsumer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "clang/AST/ASTContext.h"
17#include "clang/AST/ASTMutationListener.h"
18#include "clang/AST/DeclObjC.h"
Steve Naroff157599f2009-03-03 14:49:36 +000019#include "clang/AST/Expr.h"
John McCall31168b02011-06-15 23:02:42 +000020#include "clang/AST/ExprObjC.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000021#include "clang/AST/RecursiveASTVisitor.h"
John McCall31168b02011-06-15 23:02:42 +000022#include "clang/Basic/SourceManager.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/Sema/DeclSpec.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/Sema/Lookup.h"
25#include "clang/Sema/Scope.h"
26#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000027#include "clang/Sema/SemaInternal.h"
Douglas Gregor85f3f952015-07-07 03:57:15 +000028#include "llvm/ADT/DenseMap.h"
John McCalla1e130b2010-08-25 07:03:20 +000029#include "llvm/ADT/DenseSet.h"
30
Chris Lattnerda463fe2007-12-12 07:09:47 +000031using namespace clang;
32
John McCall31168b02011-06-15 23:02:42 +000033/// Check whether the given method, which must be in the 'init'
34/// family, is a valid member of that family.
35///
36/// \param receiverTypeIfCall - if null, check this as if declaring it;
37/// if non-null, check this as if making a call to it with the given
38/// receiver type
39///
40/// \return true to indicate that there was an error and appropriate
41/// actions were taken
42bool Sema::checkInitMethod(ObjCMethodDecl *method,
43 QualType receiverTypeIfCall) {
44 if (method->isInvalidDecl()) return true;
45
46 // This castAs is safe: methods that don't return an object
47 // pointer won't be inferred as inits and will reject an explicit
48 // objc_method_family(init).
49
50 // We ignore protocols here. Should we? What about Class?
51
Alp Toker314cc812014-01-25 16:55:45 +000052 const ObjCObjectType *result =
53 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
John McCall31168b02011-06-15 23:02:42 +000054
55 if (result->isObjCId()) {
56 return false;
57 } else if (result->isObjCClass()) {
58 // fall through: always an error
59 } else {
60 ObjCInterfaceDecl *resultClass = result->getInterface();
61 assert(resultClass && "unexpected object type!");
62
63 // It's okay for the result type to still be a forward declaration
64 // if we're checking an interface declaration.
Douglas Gregordc9166c2011-12-15 20:29:51 +000065 if (!resultClass->hasDefinition()) {
John McCall31168b02011-06-15 23:02:42 +000066 if (receiverTypeIfCall.isNull() &&
67 !isa<ObjCImplementationDecl>(method->getDeclContext()))
68 return false;
69
70 // Otherwise, we try to compare class types.
71 } else {
72 // If this method was declared in a protocol, we can't check
73 // anything unless we have a receiver type that's an interface.
Craig Topperc3ec1492014-05-26 06:22:03 +000074 const ObjCInterfaceDecl *receiverClass = nullptr;
John McCall31168b02011-06-15 23:02:42 +000075 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
76 if (receiverTypeIfCall.isNull())
77 return false;
78
79 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
80 ->getInterfaceDecl();
81
82 // This can be null for calls to e.g. id<Foo>.
83 if (!receiverClass) return false;
84 } else {
85 receiverClass = method->getClassInterface();
86 assert(receiverClass && "method not associated with a class!");
87 }
88
89 // If either class is a subclass of the other, it's fine.
90 if (receiverClass->isSuperClassOf(resultClass) ||
91 resultClass->isSuperClassOf(receiverClass))
92 return false;
93 }
94 }
95
96 SourceLocation loc = method->getLocation();
97
98 // If we're in a system header, and this is not a call, just make
99 // the method unusable.
100 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
John McCallc6af8c62015-10-28 05:03:19 +0000101 method->addAttr(UnavailableAttr::CreateImplicit(Context, "",
102 UnavailableAttr::IR_ARCInitReturnsUnrelated, loc));
John McCall31168b02011-06-15 23:02:42 +0000103 return true;
104 }
105
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
109 return true;
110}
111
Akira Hatanakaa6b5e002018-07-28 04:06:13 +0000112/// Issue a warning if the parameter of the overridden method is non-escaping
113/// but the parameter of the overriding method is not.
114static bool diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
115 Sema &S) {
116 if (OldD->hasAttr<NoEscapeAttr>() && !NewD->hasAttr<NoEscapeAttr>()) {
117 S.Diag(NewD->getLocation(), diag::warn_overriding_method_missing_noescape);
118 S.Diag(OldD->getLocation(), diag::note_overridden_marked_noescape);
119 return false;
120 }
121
122 return true;
123}
124
125/// Produce additional diagnostics if a category conforms to a protocol that
126/// defines a method taking a non-escaping parameter.
127static void diagnoseNoescape(const ParmVarDecl *NewD, const ParmVarDecl *OldD,
128 const ObjCCategoryDecl *CD,
129 const ObjCProtocolDecl *PD, Sema &S) {
130 if (!diagnoseNoescape(NewD, OldD, S))
131 S.Diag(CD->getLocation(), diag::note_cat_conform_to_noescape_prot)
132 << CD->IsClassExtension() << PD
133 << cast<ObjCMethodDecl>(NewD->getDeclContext());
134}
135
Fangrui Song6907ce22018-07-30 19:24:48 +0000136void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000137 const ObjCMethodDecl *Overridden) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000138 if (Overridden->hasRelatedResultType() &&
Douglas Gregor33823722011-06-11 01:09:30 +0000139 !NewMethod->hasRelatedResultType()) {
140 // This can only happen when the method follows a naming convention that
141 // implies a related result type, and the original (overridden) method has
142 // a suitable return type, but the new (overriding) method does not have
143 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000144 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000145 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Fangrui Song6907ce22018-07-30 19:24:48 +0000146
Douglas Gregor33823722011-06-11 01:09:30 +0000147 // Figure out which class this method is part of, if any.
Fangrui Song6907ce22018-07-30 19:24:48 +0000148 ObjCInterfaceDecl *CurrentClass
Douglas Gregor33823722011-06-11 01:09:30 +0000149 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
150 if (!CurrentClass) {
151 DeclContext *DC = NewMethod->getDeclContext();
152 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
153 CurrentClass = Cat->getClassInterface();
154 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
155 CurrentClass = Impl->getClassInterface();
156 else if (ObjCCategoryImplDecl *CatImpl
157 = dyn_cast<ObjCCategoryImplDecl>(DC))
158 CurrentClass = CatImpl->getClassInterface();
159 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000160
Douglas Gregor33823722011-06-11 01:09:30 +0000161 if (CurrentClass) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000162 Diag(NewMethod->getLocation(),
Douglas Gregor33823722011-06-11 01:09:30 +0000163 diag::warn_related_result_type_compatibility_class)
164 << Context.getObjCInterfaceType(CurrentClass)
165 << ResultType
166 << ResultTypeRange;
167 } else {
Fangrui Song6907ce22018-07-30 19:24:48 +0000168 Diag(NewMethod->getLocation(),
Douglas Gregor33823722011-06-11 01:09:30 +0000169 diag::warn_related_result_type_compatibility_protocol)
170 << ResultType
171 << ResultTypeRange;
172 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000173
Douglas Gregorbab8a962011-09-08 01:46:34 +0000174 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
Fangrui Song6907ce22018-07-30 19:24:48 +0000175 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000176 diag::note_related_result_type_family)
177 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000178 << Family;
179 else
Fangrui Song6907ce22018-07-30 19:24:48 +0000180 Diag(Overridden->getLocation(),
Douglas Gregorbab8a962011-09-08 01:46:34 +0000181 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000182 }
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000183
184 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
185 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
186 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000187 getLangOpts().ObjCAutoRefCount
188 ? diag::err_nsreturns_retained_attribute_mismatch
189 : diag::warn_nsreturns_retained_attribute_mismatch)
190 << 1;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000191 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
192 }
193 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
194 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
195 Diag(NewMethod->getLocation(),
Alex Lorenz26d282f2018-01-03 23:52:42 +0000196 getLangOpts().ObjCAutoRefCount
197 ? diag::err_nsreturns_retained_attribute_mismatch
198 : diag::warn_nsreturns_retained_attribute_mismatch)
199 << 0;
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000200 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
201 }
202
203 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
204 oe = Overridden->param_end();
205 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
206 ne = NewMethod->param_end();
207 ni != ne && oi != oe; ++ni, ++oi) {
208 const ParmVarDecl *oldDecl = (*oi);
209 ParmVarDecl *newDecl = (*ni);
210 if (newDecl->hasAttr<NSConsumedAttr>() !=
211 oldDecl->hasAttr<NSConsumedAttr>()) {
Alex Lorenz26d282f2018-01-03 23:52:42 +0000212 Diag(newDecl->getLocation(),
213 getLangOpts().ObjCAutoRefCount
214 ? diag::err_nsconsumed_attribute_mismatch
215 : diag::warn_nsconsumed_attribute_mismatch);
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000216 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000217 }
Akira Hatanaka98a49332017-09-22 00:41:05 +0000218
Akira Hatanakaa6b5e002018-07-28 04:06:13 +0000219 diagnoseNoescape(newDecl, oldDecl, *this);
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000220 }
Douglas Gregor33823722011-06-11 01:09:30 +0000221}
222
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000223/// Check a method declaration for compatibility with the Objective-C
John McCall31168b02011-06-15 23:02:42 +0000224/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000225bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000226 ObjCMethodFamily family = method->getMethodFamily();
227 switch (family) {
228 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000229 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000230 case OMF_retain:
231 case OMF_release:
232 case OMF_autorelease:
233 case OMF_retainCount:
234 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000235 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000236 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000237 return false;
238
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000239 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000240 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000241 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000242 if (ResultTypeRange.isInvalid())
Richard Smithf8812672016-12-02 22:38:31 +0000243 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000244 << method->getReturnType()
245 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000246 else
Richard Smithf8812672016-12-02 22:38:31 +0000247 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000248 << method->getReturnType()
249 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000250 return true;
251 }
252 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000253
John McCall31168b02011-06-15 23:02:42 +0000254 case OMF_init:
255 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000256 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000257 return true;
258
Aaron Ballman36a53502014-01-16 13:03:14 +0000259 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000260
261 // Don't add a second copy of this attribute, but otherwise don't
262 // let it be suppressed.
263 if (method->hasAttr<NSReturnsRetainedAttr>())
264 return false;
265 break;
266
267 case OMF_alloc:
268 case OMF_copy:
269 case OMF_mutableCopy:
270 case OMF_new:
271 if (method->hasAttr<NSReturnsRetainedAttr>() ||
272 method->hasAttr<NSReturnsNotRetainedAttr>() ||
273 method->hasAttr<NSReturnsAutoreleasedAttr>())
274 return false;
275 break;
276 }
277
Aaron Ballman36a53502014-01-16 13:03:14 +0000278 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000279 return false;
280}
281
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000282static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
283 SourceLocation ImplLoc) {
284 if (!ND)
285 return;
286 bool IsCategory = false;
Alex Lorenzf4d4cfb2018-05-03 01:12:06 +0000287 StringRef RealizedPlatform;
288 AvailabilityResult Availability = ND->getAvailability(
289 /*Message=*/nullptr, /*EnclosingVersion=*/VersionTuple(),
290 &RealizedPlatform);
Alex Lorenze1088dc2017-07-13 16:37:11 +0000291 if (Availability != AR_Deprecated) {
Eric Christopher7aba9782017-07-14 01:42:57 +0000292 if (isa<ObjCMethodDecl>(ND)) {
Alex Lorenze1088dc2017-07-13 16:37:11 +0000293 if (Availability != AR_Unavailable)
294 return;
Alex Lorenzf4d4cfb2018-05-03 01:12:06 +0000295 if (RealizedPlatform.empty())
296 RealizedPlatform = S.Context.getTargetInfo().getPlatformName();
297 // Warn about implementing unavailable methods, unless the unavailable
298 // is for an app extension.
299 if (RealizedPlatform.endswith("_app_extension"))
300 return;
Alex Lorenze1088dc2017-07-13 16:37:11 +0000301 S.Diag(ImplLoc, diag::warn_unavailable_def);
302 S.Diag(ND->getLocation(), diag::note_method_declared_at)
303 << ND->getDeclName();
304 return;
305 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000306 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
307 if (!CD->getClassInterface()->isDeprecated())
308 return;
309 ND = CD->getClassInterface();
310 IsCategory = true;
311 } else
312 return;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000313 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000314 S.Diag(ImplLoc, diag::warn_deprecated_def)
315 << (isa<ObjCMethodDecl>(ND)
316 ? /*Method*/ 0
317 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
318 : /*Class*/ 1);
319 if (isa<ObjCMethodDecl>(ND))
320 S.Diag(ND->getLocation(), diag::note_method_declared_at)
321 << ND->getDeclName();
322 else
323 S.Diag(ND->getLocation(), diag::note_previous_decl)
324 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000325}
326
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000327/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
328/// pool.
329void Sema::AddAnyMethodToGlobalPool(Decl *D) {
330 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000331
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000332 // If we don't have a valid method decl, simply return.
333 if (!MDecl)
334 return;
335 if (MDecl->isInstanceMethod())
336 AddInstanceMethodToGlobalPool(MDecl, true);
337 else
338 AddFactoryMethodToGlobalPool(MDecl, true);
339}
340
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000341/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
342/// has explicit ownership attribute; false otherwise.
343static bool
344HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
345 QualType T = Param->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000346
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000347 if (const PointerType *PT = T->getAs<PointerType>()) {
348 T = PT->getPointeeType();
349 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
350 T = RT->getPointeeType();
351 } else {
352 return true;
353 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000354
355 // If we have a lifetime qualifier, but it's local, we must have
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000356 // inferred it. So, it is implicit.
357 return !T.getLocalQualifiers().hasObjCLifetime();
358}
359
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000360/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
361/// and user declared, in the method definition's AST.
362void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000363 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000364 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fangrui Song6907ce22018-07-30 19:24:48 +0000365
Steve Naroff542cd5d2008-07-25 17:57:26 +0000366 // If we don't have a valid method decl, simply return.
367 if (!MDecl)
368 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000369
Akira Hatanakaff6c4f32018-04-12 06:01:41 +0000370 QualType ResultType = MDecl->getReturnType();
371 if (!ResultType->isDependentType() && !ResultType->isVoidType() &&
372 !MDecl->isInvalidDecl() &&
373 RequireCompleteType(MDecl->getLocation(), ResultType,
374 diag::err_func_def_incomplete_result))
375 MDecl->setInvalidDecl();
376
Chris Lattnerda463fe2007-12-12 07:09:47 +0000377 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000378 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000379 PushFunctionScope();
Fangrui Song6907ce22018-07-30 19:24:48 +0000380
Chris Lattnerda463fe2007-12-12 07:09:47 +0000381 // Create Decl objects for each parameter, entrring them in the scope for
382 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000383
384 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000385 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000386
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000387 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
388 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000389
Reid Kleckner5a115802013-06-24 14:38:26 +0000390 // The ObjC parser requires parameter names so there's no need to check.
David Majnemer59f77922016-06-24 04:05:48 +0000391 CheckParmsForFunctionDef(MDecl->parameters(),
Reid Kleckner5a115802013-06-24 14:38:26 +0000392 /*CheckParameterNames=*/false);
393
Chris Lattner58258242008-04-10 02:22:51 +0000394 // Introduce all of the other parameters into this scope.
David Majnemer59f77922016-06-24 04:05:48 +0000395 for (auto *Param : MDecl->parameters()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000396 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000397 getLangOpts().ObjCAutoRefCount &&
398 !HasExplicitOwnershipAttr(*this, Param))
399 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
400 Param->getType();
Fangrui Song6907ce22018-07-30 19:24:48 +0000401
Aaron Ballman43b68be2014-03-07 17:50:17 +0000402 if (Param->getIdentifier())
403 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000404 }
John McCall31168b02011-06-15 23:02:42 +0000405
406 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000407 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000408 switch (MDecl->getMethodFamily()) {
409 case OMF_retain:
410 case OMF_retainCount:
411 case OMF_release:
412 case OMF_autorelease:
413 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000414 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000415 break;
416
417 case OMF_None:
418 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000419 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000420 case OMF_alloc:
421 case OMF_init:
422 case OMF_mutableCopy:
423 case OMF_copy:
424 case OMF_new:
425 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000426 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000427 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000428 break;
429 }
430 }
431
Nico Weber715abaf2011-08-22 17:25:57 +0000432 // Warn on deprecated methods under -Wdeprecated-implementations,
433 // and prepare for warning on missing super calls.
434 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000435 ObjCMethodDecl *IMD =
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000436 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
Fangrui Song6907ce22018-07-30 19:24:48 +0000437
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000438 if (IMD) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000439 ObjCImplDecl *ImplDeclOfMethodDef =
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000440 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
Fangrui Song6907ce22018-07-30 19:24:48 +0000441 ObjCContainerDecl *ContDeclOfMethodDecl =
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000442 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000443 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000444 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
445 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000446 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
447 if (CD->IsClassExtension()) {
448 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
449 ImplDeclOfMethodDecl = OID->getImplementation();
450 } else
451 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000452 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000453 // No need to issue deprecated warning if deprecated mehod in class/category
454 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000455 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000456 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000457 }
Nico Weber715abaf2011-08-22 17:25:57 +0000458
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000459 if (MDecl->getMethodFamily() == OMF_init) {
460 if (MDecl->isDesignatedInitializerForTheInterface()) {
461 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000462 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000463 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000464 } else if (IC->hasDesignatedInitializers()) {
465 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000466 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000467 }
468 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000469
Nico Weber1fb82662011-08-28 22:35:17 +0000470 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000471 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
472 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
473 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000474 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000475 ObjCMethodFamily Family = MDecl->getMethodFamily();
476 if (Family == OMF_dealloc) {
477 if (!(getLangOpts().ObjCAutoRefCount ||
478 getLangOpts().getGC() == LangOptions::GCOnly))
479 getCurFunction()->ObjCShouldCallSuper = true;
480
481 } else if (Family == OMF_finalize) {
482 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
483 getCurFunction()->ObjCShouldCallSuper = true;
Fangrui Song6907ce22018-07-30 19:24:48 +0000484
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000485 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000486 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000487 SuperClass->lookupMethod(MDecl->getSelector(),
488 MDecl->isInstanceMethod());
Fangrui Song6907ce22018-07-30 19:24:48 +0000489 getCurFunction()->ObjCShouldCallSuper =
Jordan Rose2afd6612012-10-19 16:05:26 +0000490 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000491 }
Nico Weber1fb82662011-08-28 22:35:17 +0000492 }
Nico Weber715abaf2011-08-22 17:25:57 +0000493 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000494}
495
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000496namespace {
497
498// Callback to only accept typo corrections that are Objective-C classes.
499// If an ObjCInterfaceDecl* is given to the constructor, then the validation
500// function will reject corrections to that class.
501class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
502 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000503 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000504 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
505 : CurrentIDecl(IDecl) {}
506
Craig Toppere14c0f82014-03-12 04:55:44 +0000507 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000508 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
509 return ID && !declaresSameEntity(ID, CurrentIDecl);
510 }
511
512 private:
513 ObjCInterfaceDecl *CurrentIDecl;
514};
515
Hans Wennborgdcfba332015-10-06 23:40:43 +0000516} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000517
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000518static void diagnoseUseOfProtocols(Sema &TheSema,
519 ObjCContainerDecl *CD,
520 ObjCProtocolDecl *const *ProtoRefs,
521 unsigned NumProtoRefs,
522 const SourceLocation *ProtoLocs) {
523 assert(ProtoRefs);
524 // Diagnose availability in the context of the ObjC container.
525 Sema::ContextRAII SavedContext(TheSema, CD);
526 for (unsigned i = 0; i < NumProtoRefs; ++i) {
Alex Lorenzcdd596f2017-07-07 09:15:29 +0000527 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
528 /*UnknownObjCClass=*/nullptr,
529 /*ObjCPropertyAccess=*/false,
530 /*AvoidPartialAvailabilityChecks=*/true);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000531 }
532}
533
Douglas Gregore9d95f12015-07-07 03:57:35 +0000534void Sema::
535ActOnSuperClassOfClassInterface(Scope *S,
536 SourceLocation AtInterfaceLoc,
537 ObjCInterfaceDecl *IDecl,
538 IdentifierInfo *ClassName,
539 SourceLocation ClassLoc,
540 IdentifierInfo *SuperName,
541 SourceLocation SuperLoc,
542 ArrayRef<ParsedType> SuperTypeArgs,
543 SourceRange SuperTypeArgsRange) {
544 // Check if a different kind of symbol declared in this scope.
545 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
546 LookupOrdinaryName);
547
548 if (!PrevDecl) {
549 // Try to correct for a typo in the superclass name without correcting
550 // to the class we're defining.
551 if (TypoCorrection Corrected = CorrectTypo(
552 DeclarationNameInfo(SuperName, SuperLoc),
553 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000554 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000555 CTK_ErrorRecovery)) {
556 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
557 << SuperName << ClassName);
558 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
559 }
560 }
561
562 if (declaresSameEntity(PrevDecl, IDecl)) {
563 Diag(SuperLoc, diag::err_recursive_superclass)
564 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
565 IDecl->setEndOfDefinitionLoc(ClassLoc);
566 } else {
567 ObjCInterfaceDecl *SuperClassDecl =
568 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
569 QualType SuperClassType;
570
571 // Diagnose classes that inherit from deprecated classes.
572 if (SuperClassDecl) {
573 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
574 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
575 }
576
Hans Wennborgdcfba332015-10-06 23:40:43 +0000577 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000578 // The previous declaration was not a class decl. Check if we have a
579 // typedef. If we do, get the underlying class type.
580 if (const TypedefNameDecl *TDecl =
581 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
582 QualType T = TDecl->getUnderlyingType();
583 if (T->isObjCObjectType()) {
584 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
585 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
586 SuperClassType = Context.getTypeDeclType(TDecl);
587
588 // This handles the following case:
589 // @interface NewI @end
590 // typedef NewI DeprI __attribute__((deprecated("blah")))
591 // @interface SI : DeprI /* warn here */ @end
592 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
593 }
594 }
595 }
596
597 // This handles the following case:
598 //
599 // typedef int SuperClass;
600 // @interface MyClass : SuperClass {} @end
601 //
602 if (!SuperClassDecl) {
603 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
604 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
605 }
606 }
607
608 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
609 if (!SuperClassDecl)
610 Diag(SuperLoc, diag::err_undef_superclass)
611 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
612 else if (RequireCompleteType(SuperLoc,
613 SuperClassType,
614 diag::err_forward_superclass,
615 SuperClassDecl->getDeclName(),
616 ClassName,
617 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000618 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000619 SuperClassType = QualType();
620 }
621 }
622
623 if (SuperClassType.isNull()) {
624 assert(!SuperClassDecl && "Failed to set SuperClassType?");
625 return;
626 }
627
628 // Handle type arguments on the superclass.
629 TypeSourceInfo *SuperClassTInfo = nullptr;
Fangrui Song6907ce22018-07-30 19:24:48 +0000630 if (!SuperTypeArgs.empty()) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000631 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
632 S,
633 SuperLoc,
Fangrui Song6907ce22018-07-30 19:24:48 +0000634 CreateParsedType(SuperClassType,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000635 nullptr),
636 SuperTypeArgsRange.getBegin(),
637 SuperTypeArgs,
638 SuperTypeArgsRange.getEnd(),
639 SourceLocation(),
640 { },
641 { },
642 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000643 if (!fullSuperClassType.isUsable())
644 return;
645
Fangrui Song6907ce22018-07-30 19:24:48 +0000646 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000647 &SuperClassTInfo);
648 }
649
650 if (!SuperClassTInfo) {
Fangrui Song6907ce22018-07-30 19:24:48 +0000651 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000652 SuperLoc);
653 }
654
655 IDecl->setSuperClass(SuperClassTInfo);
656 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
657 }
658}
659
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000660DeclResult Sema::actOnObjCTypeParam(Scope *S,
661 ObjCTypeParamVariance variance,
662 SourceLocation varianceLoc,
663 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000664 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000665 SourceLocation paramLoc,
666 SourceLocation colonLoc,
667 ParsedType parsedTypeBound) {
668 // If there was an explicitly-provided type bound, check it.
669 TypeSourceInfo *typeBoundInfo = nullptr;
670 if (parsedTypeBound) {
671 // The type bound can be any Objective-C pointer type.
672 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
673 if (typeBound->isObjCObjectPointerType()) {
674 // okay
675 } else if (typeBound->isObjCObjectType()) {
676 // The user forgot the * on an Objective-C pointer type, e.g.,
677 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000678 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000679 typeBoundInfo->getTypeLoc().getEndLoc());
680 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
681 diag::err_objc_type_param_bound_missing_pointer)
682 << typeBound << paramName
683 << FixItHint::CreateInsertion(starLoc, " *");
684
685 // Create a new type location builder so we can update the type
686 // location information we have.
687 TypeLocBuilder builder;
688 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
689
690 // Create the Objective-C pointer type.
691 typeBound = Context.getObjCObjectPointerType(typeBound);
692 ObjCObjectPointerTypeLoc newT
693 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
694 newT.setStarLoc(starLoc);
695
696 // Form the new type source information.
697 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
698 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000699 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000700 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
701 diag::err_objc_type_param_bound_nonobject)
702 << typeBound << paramName;
703
704 // Forget the bound; we'll default to id later.
705 typeBoundInfo = nullptr;
706 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000707
John McCall69975252015-09-23 22:14:21 +0000708 // Type bounds cannot have qualifiers (even indirectly) or explicit
709 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000710 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000711 QualType typeBound = typeBoundInfo->getType();
712 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
713 if (qual || typeBound.hasQualifiers()) {
714 bool diagnosed = false;
715 SourceRange rangeToRemove;
716 if (qual) {
717 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
718 rangeToRemove = attr.getLocalSourceRange();
719 if (attr.getTypePtr()->getImmediateNullability()) {
720 Diag(attr.getLocStart(),
721 diag::err_objc_type_param_bound_explicit_nullability)
722 << paramName << typeBound
723 << FixItHint::CreateRemoval(rangeToRemove);
724 diagnosed = true;
725 }
726 }
727 }
728
729 if (!diagnosed) {
730 Diag(qual ? qual.getLocStart()
731 : typeBoundInfo->getTypeLoc().getLocStart(),
732 diag::err_objc_type_param_bound_qualified)
733 << paramName << typeBound << typeBound.getQualifiers().getAsString()
734 << FixItHint::CreateRemoval(rangeToRemove);
735 }
736
737 // If the type bound has qualifiers other than CVR, we need to strip
738 // them or we'll probably assert later when trying to apply new
739 // qualifiers.
740 Qualifiers quals = typeBound.getQualifiers();
741 quals.removeCVRQualifiers();
742 if (!quals.empty()) {
743 typeBoundInfo =
744 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
745 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000746 }
747 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000748 }
749
750 // If there was no explicit type bound (or we removed it due to an error),
751 // use 'id' instead.
752 if (!typeBoundInfo) {
753 colonLoc = SourceLocation();
754 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
755 }
756
757 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000758 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
759 index, paramLoc, paramName, colonLoc,
760 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000761}
762
763ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
764 SourceLocation lAngleLoc,
765 ArrayRef<Decl *> typeParamsIn,
766 SourceLocation rAngleLoc) {
767 // We know that the array only contains Objective-C type parameters.
768 ArrayRef<ObjCTypeParamDecl *>
769 typeParams(
770 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
771 typeParamsIn.size());
772
773 // Diagnose redeclarations of type parameters.
774 // We do this now because Objective-C type parameters aren't pushed into
775 // scope until later (after the instance variable block), but we want the
776 // diagnostics to occur right after we parse the type parameter list.
777 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
778 for (auto typeParam : typeParams) {
779 auto known = knownParams.find(typeParam->getIdentifier());
780 if (known != knownParams.end()) {
781 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
782 << typeParam->getIdentifier()
783 << SourceRange(known->second->getLocation());
784
785 typeParam->setInvalidDecl();
786 } else {
787 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
788
789 // Push the type parameter into scope.
790 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
791 }
792 }
793
794 // Create the parameter list.
795 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
796}
797
798void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
799 for (auto typeParam : *typeParamList) {
800 if (!typeParam->isInvalidDecl()) {
801 S->RemoveDecl(typeParam);
802 IdResolver.RemoveDecl(typeParam);
803 }
804 }
805}
806
807namespace {
808 /// The context in which an Objective-C type parameter list occurs, for use
809 /// in diagnostics.
810 enum class TypeParamListContext {
811 ForwardDeclaration,
812 Definition,
813 Category,
814 Extension
815 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000816} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000817
818/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000819/// between a category/extension and an \@interface or between an \@class and an
820/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000821static bool checkTypeParamListConsistency(Sema &S,
822 ObjCTypeParamList *prevTypeParams,
823 ObjCTypeParamList *newTypeParams,
824 TypeParamListContext newContext) {
825 // If the sizes don't match, complain about that.
826 if (prevTypeParams->size() != newTypeParams->size()) {
827 SourceLocation diagLoc;
828 if (newTypeParams->size() > prevTypeParams->size()) {
829 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
830 } else {
Craig Topper07fa1762015-11-15 02:31:46 +0000831 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000832 }
833
834 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
835 << static_cast<unsigned>(newContext)
836 << (newTypeParams->size() > prevTypeParams->size())
837 << prevTypeParams->size()
838 << newTypeParams->size();
839
840 return true;
841 }
842
843 // Match up the type parameters.
844 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
845 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
846 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
847
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000848 // Check for consistency of the variance.
849 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
850 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
851 newContext != TypeParamListContext::Definition) {
852 // When the new type parameter is invariant and is not part
853 // of the definition, just propagate the variance.
854 newTypeParam->setVariance(prevTypeParam->getVariance());
Fangrui Song6907ce22018-07-30 19:24:48 +0000855 } else if (prevTypeParam->getVariance()
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000856 == ObjCTypeParamVariance::Invariant &&
857 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
858 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
859 ->getDefinition() == prevTypeParam->getDeclContext())) {
860 // When the old parameter is invariant and was not part of the
861 // definition, just ignore the difference because it doesn't
862 // matter.
863 } else {
864 {
865 // Diagnose the conflict and update the second declaration.
866 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
867 if (diagLoc.isInvalid())
868 diagLoc = newTypeParam->getLocStart();
869
870 auto diag = S.Diag(diagLoc,
871 diag::err_objc_type_param_variance_conflict)
872 << static_cast<unsigned>(newTypeParam->getVariance())
873 << newTypeParam->getDeclName()
874 << static_cast<unsigned>(prevTypeParam->getVariance())
875 << prevTypeParam->getDeclName();
876 switch (prevTypeParam->getVariance()) {
877 case ObjCTypeParamVariance::Invariant:
878 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
879 break;
880
881 case ObjCTypeParamVariance::Covariant:
882 case ObjCTypeParamVariance::Contravariant: {
883 StringRef newVarianceStr
884 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
885 ? "__covariant"
886 : "__contravariant";
887 if (newTypeParam->getVariance()
888 == ObjCTypeParamVariance::Invariant) {
889 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
890 (newVarianceStr + " ").str());
891 } else {
892 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
893 newVarianceStr);
894 }
895 }
896 }
897 }
898
899 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
900 << prevTypeParam->getDeclName();
901
902 // Override the variance.
903 newTypeParam->setVariance(prevTypeParam->getVariance());
904 }
905 }
906
Douglas Gregor85f3f952015-07-07 03:57:15 +0000907 // If the bound types match, there's nothing to do.
908 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
909 newTypeParam->getUnderlyingType()))
910 continue;
911
912 // If the new type parameter's bound was explicit, complain about it being
913 // different from the original.
914 if (newTypeParam->hasExplicitBound()) {
915 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
916 ->getTypeLoc().getSourceRange();
917 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
918 << newTypeParam->getUnderlyingType()
919 << newTypeParam->getDeclName()
920 << prevTypeParam->hasExplicitBound()
921 << prevTypeParam->getUnderlyingType()
922 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
923 << prevTypeParam->getDeclName()
924 << FixItHint::CreateReplacement(
925 newBoundRange,
926 prevTypeParam->getUnderlyingType().getAsString(
927 S.Context.getPrintingPolicy()));
928
929 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
930 << prevTypeParam->getDeclName();
931
932 // Override the new type parameter's bound type with the previous type,
933 // so that it's consistent.
934 newTypeParam->setTypeSourceInfo(
935 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
936 continue;
937 }
938
939 // The new type parameter got the implicit bound of 'id'. That's okay for
940 // categories and extensions (overwrite it later), but not for forward
941 // declarations and @interfaces, because those must be standalone.
942 if (newContext == TypeParamListContext::ForwardDeclaration ||
943 newContext == TypeParamListContext::Definition) {
944 // Diagnose this problem for forward declarations and definitions.
945 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000946 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000947 std::string newCode
948 = " : " + prevTypeParam->getUnderlyingType().getAsString(
949 S.Context.getPrintingPolicy());
950 S.Diag(newTypeParam->getLocation(),
951 diag::err_objc_type_param_bound_missing)
952 << prevTypeParam->getUnderlyingType()
953 << newTypeParam->getDeclName()
954 << (newContext == TypeParamListContext::ForwardDeclaration)
955 << FixItHint::CreateInsertion(insertionLoc, newCode);
956
957 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
958 << prevTypeParam->getDeclName();
959 }
960
961 // Update the new type parameter's bound to match the previous one.
962 newTypeParam->setTypeSourceInfo(
963 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
964 }
965
966 return false;
967}
968
Erich Keanec480f302018-07-12 21:09:05 +0000969Decl *Sema::ActOnStartClassInterface(
970 Scope *S, SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
971 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
972 IdentifierInfo *SuperName, SourceLocation SuperLoc,
973 ArrayRef<ParsedType> SuperTypeArgs, SourceRange SuperTypeArgsRange,
974 Decl *const *ProtoRefs, unsigned NumProtoRefs,
975 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
976 const ParsedAttributesView &AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000977 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000978
Chris Lattnerda463fe2007-12-12 07:09:47 +0000979 // Check for another declaration kind with the same name.
Richard Smithbecb92d2017-10-10 22:33:17 +0000980 NamedDecl *PrevDecl =
981 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
982 forRedeclarationInCurContext());
Douglas Gregor5101c242008-12-05 18:15:24 +0000983
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000984 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000985 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000986 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000987 }
Mike Stump11289f42009-09-09 15:08:12 +0000988
Douglas Gregordc9166c2011-12-15 20:29:51 +0000989 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000990 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000991
992 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
993 // A previous decl with a different name is because of
994 // @compatibility_alias, for example:
995 // \code
996 // @class NewImage;
997 // @compatibility_alias OldImage NewImage;
998 // \endcode
999 // A lookup for 'OldImage' will return the 'NewImage' decl.
1000 //
1001 // In such a case use the real declaration name, instead of the alias one,
1002 // otherwise we will break IdentifierResolver and redecls-chain invariants.
1003 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
1004 // has been aliased.
1005 ClassName = PrevIDecl->getIdentifier();
1006 }
1007
Douglas Gregor85f3f952015-07-07 03:57:15 +00001008 // If there was a forward declaration with type parameters, check
1009 // for consistency.
1010 if (PrevIDecl) {
1011 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
1012 if (typeParamList) {
1013 // Both have type parameter lists; check for consistency.
Fangrui Song6907ce22018-07-30 19:24:48 +00001014 if (checkTypeParamListConsistency(*this, prevTypeParamList,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001015 typeParamList,
1016 TypeParamListContext::Definition)) {
1017 typeParamList = nullptr;
1018 }
1019 } else {
1020 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
1021 << ClassName;
1022 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
1023 << ClassName;
1024
1025 // Clone the type parameter list.
1026 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
1027 for (auto typeParam : *prevTypeParamList) {
1028 clonedTypeParams.push_back(
1029 ObjCTypeParamDecl::Create(
1030 Context,
1031 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +00001032 typeParam->getVariance(),
1033 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001034 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +00001035 SourceLocation(),
1036 typeParam->getIdentifier(),
1037 SourceLocation(),
1038 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1039 }
1040
Fangrui Song6907ce22018-07-30 19:24:48 +00001041 typeParamList = ObjCTypeParamList::create(Context,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001042 SourceLocation(),
1043 clonedTypeParams,
1044 SourceLocation());
1045 }
1046 }
1047 }
1048
Douglas Gregordc9166c2011-12-15 20:29:51 +00001049 ObjCInterfaceDecl *IDecl
1050 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001051 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001052 if (PrevIDecl) {
1053 // Class already seen. Was it a definition?
1054 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1055 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1056 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001057 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001058 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001059 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001060 }
Erich Keanec480f302018-07-12 21:09:05 +00001061
1062 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001063 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001064 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +00001065
Fangrui Song6907ce22018-07-30 19:24:48 +00001066 // Start the definition of this class. If we're in a redefinition case, there
Douglas Gregordc9166c2011-12-15 20:29:51 +00001067 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001068 if (!IDecl->hasDefinition())
1069 IDecl->startDefinition();
Fangrui Song6907ce22018-07-30 19:24:48 +00001070
Chris Lattnerda463fe2007-12-12 07:09:47 +00001071 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001072 // Diagnose availability in the context of the @interface.
1073 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001074
Fangrui Song6907ce22018-07-30 19:24:48 +00001075 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1076 ClassName, ClassLoc,
1077 SuperName, SuperLoc, SuperTypeArgs,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001078 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001079 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001080 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001081 }
Mike Stump11289f42009-09-09 15:08:12 +00001082
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001083 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001084 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001085 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1086 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001087 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001088 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001089 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001090 }
Mike Stump11289f42009-09-09 15:08:12 +00001091
Anders Carlssona6b508a2008-11-04 16:57:32 +00001092 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001093 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001094}
1095
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001096/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1097/// typedef'ed use for a qualified super class and adds them to the list
1098/// of the protocols.
1099void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001100 SmallVectorImpl<SourceLocation> &ProtocolLocs,
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001101 IdentifierInfo *SuperName,
1102 SourceLocation SuperLoc) {
1103 if (!SuperName)
1104 return;
1105 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1106 LookupOrdinaryName);
1107 if (!IDecl)
1108 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001109
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001110 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1111 QualType T = TDecl->getUnderlyingType();
1112 if (T->isObjCObjectType())
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001113 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
Benjamin Kramerf9890422015-02-17 16:48:30 +00001114 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001115 // FIXME: Consider whether this should be an invalid loc since the loc
1116 // is not actually pointing to a protocol name reference but to the
1117 // typedef reference. Note that the base class name loc is also pointing
1118 // at the typedef.
1119 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1120 }
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001121 }
1122}
1123
Richard Smithac4e36d2012-08-08 23:32:13 +00001124/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001125/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001126Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1127 IdentifierInfo *AliasName,
1128 SourceLocation AliasLocation,
1129 IdentifierInfo *ClassName,
1130 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001131 // Look for previous declaration of alias name
Richard Smithbecb92d2017-10-10 22:33:17 +00001132 NamedDecl *ADecl =
1133 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1134 forRedeclarationInCurContext());
Chris Lattnerda463fe2007-12-12 07:09:47 +00001135 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001136 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001137 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001138 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001139 }
1140 // Check for class declaration
Richard Smithbecb92d2017-10-10 22:33:17 +00001141 NamedDecl *CDeclU =
1142 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1143 forRedeclarationInCurContext());
Richard Smithdda56e42011-04-15 14:24:37 +00001144 if (const TypedefNameDecl *TDecl =
1145 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001146 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001147 if (T->isObjCObjectType()) {
1148 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001149 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001150 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Richard Smithbecb92d2017-10-10 22:33:17 +00001151 LookupOrdinaryName,
1152 forRedeclarationInCurContext());
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001153 }
1154 }
1155 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001156 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001157 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001158 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001159 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001160 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001161 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001162 }
Mike Stump11289f42009-09-09 15:08:12 +00001163
Chris Lattner219b3e92008-03-16 21:17:37 +00001164 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001165 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001166 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001167
Anders Carlssona6b508a2008-11-04 16:57:32 +00001168 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001169 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001170
John McCall48871652010-08-21 09:40:31 +00001171 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001172}
1173
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001174bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001175 IdentifierInfo *PName,
1176 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001177 const ObjCList<ObjCProtocolDecl> &PList) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001178
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001179 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001180 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1181 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001182 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1183 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001184 if (PDecl->getIdentifier() == PName) {
1185 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1186 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001187 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001188 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001189
Douglas Gregore6e48b12012-01-01 19:29:29 +00001190 if (!PDecl->hasDefinition())
1191 continue;
Fangrui Song6907ce22018-07-30 19:24:48 +00001192
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001193 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1194 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1195 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001196 }
1197 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001198 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001199}
1200
Erich Keanec480f302018-07-12 21:09:05 +00001201Decl *Sema::ActOnStartProtocolInterface(
1202 SourceLocation AtProtoInterfaceLoc, IdentifierInfo *ProtocolName,
1203 SourceLocation ProtocolLoc, Decl *const *ProtoRefs, unsigned NumProtoRefs,
1204 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1205 const ParsedAttributesView &AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001206 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001207 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001208 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001209 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00001210 forRedeclarationInCurContext());
Craig Topperc3ec1492014-05-26 06:22:03 +00001211 ObjCProtocolDecl *PDecl = nullptr;
1212 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001213 // If we already have a definition, complain.
1214 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1215 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001216
Douglas Gregor32c17572012-01-01 20:30:41 +00001217 // Create a new protocol that is completely distinct from previous
1218 // declarations, and do not make this protocol available for name lookup.
1219 // That way, we'll end up completely ignoring the duplicate.
1220 // FIXME: Can we turn this into an error?
1221 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1222 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001223 /*PrevDecl=*/nullptr);
Bruno Cardoso Lopes7dcf23e2018-06-30 00:49:27 +00001224
1225 // If we are using modules, add the decl to the context in order to
1226 // serialize something meaningful.
1227 if (getLangOpts().Modules)
1228 PushOnScopeChains(PDecl, TUScope);
Douglas Gregor32c17572012-01-01 20:30:41 +00001229 PDecl->startDefinition();
1230 } else {
1231 if (PrevDecl) {
1232 // Check for circular dependencies among protocol declarations. This can
1233 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001234 ObjCList<ObjCProtocolDecl> PList;
1235 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1236 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001237 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001238 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001239
1240 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001241 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001242 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001243 /*PrevDecl=*/PrevDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001244
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001245 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001246 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001247 }
Erich Keanec480f302018-07-12 21:09:05 +00001248
1249 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001250 AddPragmaAttributes(TUScope, PDecl);
1251
Douglas Gregor32c17572012-01-01 20:30:41 +00001252 // Merge attributes from previous declarations.
1253 if (PrevDecl)
1254 mergeDeclAttributes(PDecl, PrevDecl);
1255
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001256 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001257 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001258 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1259 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001260 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001261 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001262 }
Mike Stump11289f42009-09-09 15:08:12 +00001263
1264 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001265 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001266}
1267
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001268static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1269 ObjCProtocolDecl *&UndefinedProtocol) {
1270 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1271 UndefinedProtocol = PDecl;
1272 return true;
1273 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001274
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001275 for (auto *PI : PDecl->protocols())
1276 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1277 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001278 return true;
1279 }
1280 return false;
1281}
1282
Chris Lattnerda463fe2007-12-12 07:09:47 +00001283/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001284/// issues an error if they are not declared. It returns list of
1285/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001286void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001287Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001288 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001289 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001290 for (const IdentifierLocPair &Pair : ProtocolId) {
1291 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001292 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001293 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001294 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001295 LookupObjCProtocolName, TUScope, nullptr,
1296 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001297 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001298 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1299 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001300 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001301 }
1302
1303 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001304 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001305 continue;
1306 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001307 // If this is a forward protocol declaration, get its definition.
1308 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1309 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001310
1311 // For an objc container, delay protocol reference checking until after we
1312 // can set the objc decl as the availability context, otherwise check now.
1313 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001314 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001315 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001316
1317 // If this is a forward declaration and we are supposed to warn in this
1318 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001319 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001320 ObjCProtocolDecl *UndefinedProtocol;
Fangrui Song6907ce22018-07-30 19:24:48 +00001321
Douglas Gregoreed49792013-01-17 00:38:46 +00001322 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001323 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001324 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001325 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1326 << UndefinedProtocol;
1327 }
John McCall48871652010-08-21 09:40:31 +00001328 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001329 }
1330}
1331
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001332namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001333// Callback to only accept typo corrections that are either
1334// Objective-C protocols or valid Objective-C type arguments.
1335class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1336 ASTContext &Context;
1337 Sema::LookupNameKind LookupKind;
1338 public:
1339 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1340 Sema::LookupNameKind lookupKind)
1341 : Context(context), LookupKind(lookupKind) { }
1342
1343 bool ValidateCandidate(const TypoCorrection &candidate) override {
1344 // If we're allowed to find protocols and we have a protocol, accept it.
1345 if (LookupKind != Sema::LookupOrdinaryName) {
1346 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1347 return true;
1348 }
1349
1350 // If we're allowed to find type names and we have one, accept it.
1351 if (LookupKind != Sema::LookupObjCProtocolName) {
1352 // If we have a type declaration, we might accept this result.
1353 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1354 // If we found a tag declaration outside of C++, skip it. This
1355 // can happy because we look for any name when there is no
1356 // bias to protocol or type names.
1357 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1358 return false;
1359
1360 // Make sure the type is something we would accept as a type
1361 // argument.
1362 auto type = Context.getTypeDeclType(typeDecl);
1363 if (type->isObjCObjectPointerType() ||
1364 type->isBlockPointerType() ||
1365 type->isDependentType() ||
1366 type->isObjCObjectType())
1367 return true;
1368
1369 return false;
1370 }
1371
1372 // If we have an Objective-C class type, accept it; there will
1373 // be another fix to add the '*'.
1374 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1375 return true;
1376
1377 return false;
1378 }
1379
1380 return false;
1381 }
1382};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001383} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001384
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001385void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1386 SourceLocation ProtocolLoc,
1387 IdentifierInfo *TypeArgId,
1388 SourceLocation TypeArgLoc,
1389 bool SelectProtocolFirst) {
1390 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1391 << SelectProtocolFirst << TypeArgId << ProtocolId
1392 << SourceRange(ProtocolLoc);
1393}
1394
Douglas Gregore9d95f12015-07-07 03:57:35 +00001395void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1396 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001397 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001398 SourceLocation lAngleLoc,
1399 ArrayRef<IdentifierInfo *> identifiers,
1400 ArrayRef<SourceLocation> identifierLocs,
1401 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001402 SourceLocation &typeArgsLAngleLoc,
1403 SmallVectorImpl<ParsedType> &typeArgs,
1404 SourceLocation &typeArgsRAngleLoc,
1405 SourceLocation &protocolLAngleLoc,
1406 SmallVectorImpl<Decl *> &protocols,
1407 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001408 bool warnOnIncompleteProtocols) {
1409 // Local function that updates the declaration specifiers with
1410 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001411 unsigned numProtocolsResolved = 0;
1412 auto resolvedAsProtocols = [&] {
1413 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
Fangrui Song6907ce22018-07-30 19:24:48 +00001414
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001415 // Determine whether the base type is a parameterized class, in
1416 // which case we want to warn about typos such as
1417 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1418 ObjCInterfaceDecl *baseClass = nullptr;
1419 QualType base = GetTypeFromParser(baseType, nullptr);
1420 bool allAreTypeNames = false;
1421 SourceLocation firstClassNameLoc;
1422 if (!base.isNull()) {
1423 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1424 baseClass = objcObjectType->getInterface();
1425 if (baseClass) {
1426 if (auto typeParams = baseClass->getTypeParamList()) {
1427 if (typeParams->size() == numProtocolsResolved) {
1428 // Note that we should be looking for type names, too.
1429 allAreTypeNames = true;
1430 }
1431 }
1432 }
1433 }
1434 }
1435
Douglas Gregore9d95f12015-07-07 03:57:35 +00001436 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Fangrui Song6907ce22018-07-30 19:24:48 +00001437 ObjCProtocolDecl *&proto
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001438 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001439 // For an objc container, delay protocol reference checking until after we
1440 // can set the objc decl as the availability context, otherwise check now.
1441 if (!warnOnIncompleteProtocols) {
1442 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1443 }
1444
1445 // If this is a forward protocol declaration, get its definition.
1446 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1447 proto = proto->getDefinition();
1448
1449 // If this is a forward declaration and we are supposed to warn in this
1450 // case, do it.
1451 // FIXME: Recover nicely in the hidden case.
1452 ObjCProtocolDecl *forwardDecl = nullptr;
1453 if (warnOnIncompleteProtocols &&
1454 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1455 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1456 << proto->getDeclName();
1457 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1458 << forwardDecl;
1459 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001460
1461 // If everything this far has been a type name (and we care
1462 // about such things), check whether this name refers to a type
1463 // as well.
1464 if (allAreTypeNames) {
1465 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1466 LookupOrdinaryName)) {
1467 if (isa<ObjCInterfaceDecl>(decl)) {
1468 if (firstClassNameLoc.isInvalid())
1469 firstClassNameLoc = identifierLocs[i];
1470 } else if (!isa<TypeDecl>(decl)) {
1471 // Not a type.
1472 allAreTypeNames = false;
1473 }
1474 } else {
1475 allAreTypeNames = false;
1476 }
1477 }
1478 }
Fangrui Song6907ce22018-07-30 19:24:48 +00001479
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001480 // All of the protocols listed also have type names, and at least
1481 // one is an Objective-C class name. Check whether all of the
1482 // protocol conformances are declared by the base class itself, in
1483 // which case we warn.
1484 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1485 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1486 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1487 bool allProtocolsDeclared = true;
1488 for (auto proto : protocols) {
1489 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1490 allProtocolsDeclared = false;
1491 break;
1492 }
1493 }
1494
1495 if (allProtocolsDeclared) {
1496 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1497 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001498 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1499 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001500 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001501 }
1502
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001503 protocolLAngleLoc = lAngleLoc;
1504 protocolRAngleLoc = rAngleLoc;
1505 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001506 };
1507
1508 // Attempt to resolve all of the identifiers as protocols.
1509 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1510 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1511 protocols.push_back(proto);
1512 if (proto)
1513 ++numProtocolsResolved;
1514 }
1515
1516 // If all of the names were protocols, these were protocol qualifiers.
1517 if (numProtocolsResolved == identifiers.size())
1518 return resolvedAsProtocols();
1519
1520 // Attempt to resolve all of the identifiers as type names or
1521 // Objective-C class names. The latter is technically ill-formed,
1522 // but is probably something like \c NSArray<NSView *> missing the
1523 // \c*.
1524 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1525 SmallVector<TypeOrClassDecl, 4> typeDecls;
1526 unsigned numTypeDeclsResolved = 0;
1527 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1528 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1529 LookupOrdinaryName);
1530 if (!decl) {
1531 typeDecls.push_back(TypeOrClassDecl());
1532 continue;
1533 }
1534
1535 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1536 typeDecls.push_back(typeDecl);
1537 ++numTypeDeclsResolved;
1538 continue;
1539 }
1540
1541 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1542 typeDecls.push_back(objcClass);
1543 ++numTypeDeclsResolved;
1544 continue;
1545 }
1546
1547 typeDecls.push_back(TypeOrClassDecl());
1548 }
1549
1550 AttributeFactory attrFactory;
1551
1552 // Local function that forms a reference to the given type or
1553 // Objective-C class declaration.
Fangrui Song6907ce22018-07-30 19:24:48 +00001554 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
Douglas Gregore9d95f12015-07-07 03:57:35 +00001555 -> TypeResult {
1556 // Form declaration specifiers. They simply refer to the type.
1557 DeclSpec DS(attrFactory);
1558 const char* prevSpec; // unused
1559 unsigned diagID; // unused
1560 QualType type;
1561 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1562 type = Context.getTypeDeclType(actualTypeDecl);
1563 else
1564 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1565 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1566 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1567 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1568 parsedType, Context.getPrintingPolicy());
1569 // Use the identifier location for the type source range.
1570 DS.SetRangeStart(loc);
1571 DS.SetRangeEnd(loc);
1572
1573 // Form the declarator.
Faisal Vali421b2d12017-12-29 05:41:00 +00001574 Declarator D(DS, DeclaratorContext::TypeNameContext);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001575
1576 // If we have a typedef of an Objective-C class type that is missing a '*',
1577 // add the '*'.
1578 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001579 SourceLocation starLoc = getLocForEndOfToken(loc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001580 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1581 SourceLocation(),
1582 SourceLocation(),
1583 SourceLocation(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00001584 SourceLocation(),
Douglas Gregore9d95f12015-07-07 03:57:35 +00001585 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001586 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001587
1588 // Diagnose the missing '*'.
1589 Diag(loc, diag::err_objc_type_arg_missing_star)
1590 << type
1591 << FixItHint::CreateInsertion(starLoc, " *");
1592 }
1593
1594 // Convert this to a type.
1595 return ActOnTypeName(S, D);
1596 };
1597
1598 // Local function that updates the declaration specifiers with
1599 // type argument information.
1600 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001601 // We did not resolve these as protocols.
1602 protocols.clear();
1603
Douglas Gregore9d95f12015-07-07 03:57:35 +00001604 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1605 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001606 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1607 // Map type reference to a type.
1608 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001609 if (!type.isUsable()) {
1610 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001611 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001612 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001613
1614 typeArgs.push_back(type.get());
1615 }
1616
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001617 typeArgsLAngleLoc = lAngleLoc;
1618 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001619 };
1620
1621 // If all of the identifiers can be resolved as type names or
1622 // Objective-C class names, we have type arguments.
1623 if (numTypeDeclsResolved == identifiers.size())
1624 return resolvedAsTypeDecls();
1625
1626 // Error recovery: some names weren't found, or we have a mix of
1627 // type and protocol names. Go resolve all of the unresolved names
1628 // and complain if we can't find a consistent answer.
1629 LookupNameKind lookupKind = LookupAnyName;
1630 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1631 // If we already have a protocol or type. Check whether it is the
1632 // right thing.
1633 if (protocols[i] || typeDecls[i]) {
1634 // If we haven't figured out whether we want types or protocols
1635 // yet, try to figure it out from this name.
1636 if (lookupKind == LookupAnyName) {
1637 // If this name refers to both a protocol and a type (e.g., \c
1638 // NSObject), don't conclude anything yet.
1639 if (protocols[i] && typeDecls[i])
1640 continue;
1641
1642 // Otherwise, let this name decide whether we'll be correcting
1643 // toward types or protocols.
1644 lookupKind = protocols[i] ? LookupObjCProtocolName
1645 : LookupOrdinaryName;
1646 continue;
1647 }
1648
1649 // If we want protocols and we have a protocol, there's nothing
1650 // more to do.
1651 if (lookupKind == LookupObjCProtocolName && protocols[i])
1652 continue;
1653
1654 // If we want types and we have a type declaration, there's
1655 // nothing more to do.
1656 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1657 continue;
1658
1659 // We have a conflict: some names refer to protocols and others
1660 // refer to types.
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001661 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1662 identifiers[i], identifierLocs[i],
1663 protocols[i] != nullptr);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001664
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001665 protocols.clear();
1666 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001667 return;
1668 }
1669
1670 // Perform typo correction on the name.
1671 TypoCorrection corrected = CorrectTypo(
1672 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1673 nullptr,
1674 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1675 lookupKind),
1676 CTK_ErrorRecovery);
1677 if (corrected) {
1678 // Did we find a protocol?
1679 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1680 diagnoseTypo(corrected,
1681 PDiag(diag::err_undeclared_protocol_suggest)
1682 << identifiers[i]);
1683 lookupKind = LookupObjCProtocolName;
1684 protocols[i] = proto;
1685 ++numProtocolsResolved;
1686 continue;
1687 }
1688
1689 // Did we find a type?
1690 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1691 diagnoseTypo(corrected,
1692 PDiag(diag::err_unknown_typename_suggest)
1693 << identifiers[i]);
1694 lookupKind = LookupOrdinaryName;
1695 typeDecls[i] = typeDecl;
1696 ++numTypeDeclsResolved;
1697 continue;
1698 }
1699
1700 // Did we find an Objective-C class?
1701 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1702 diagnoseTypo(corrected,
1703 PDiag(diag::err_unknown_type_or_class_name_suggest)
1704 << identifiers[i] << true);
1705 lookupKind = LookupOrdinaryName;
1706 typeDecls[i] = objcClass;
1707 ++numTypeDeclsResolved;
1708 continue;
1709 }
1710 }
1711
1712 // We couldn't find anything.
1713 Diag(identifierLocs[i],
1714 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1715 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1716 : diag::err_unknown_typename))
1717 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001718 protocols.clear();
1719 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001720 return;
1721 }
1722
1723 // If all of the names were (corrected to) protocols, these were
1724 // protocol qualifiers.
1725 if (numProtocolsResolved == identifiers.size())
1726 return resolvedAsProtocols();
1727
1728 // Otherwise, all of the names were (corrected to) types.
1729 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1730 return resolvedAsTypeDecls();
1731}
1732
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001733/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001734/// a class method in its extension.
1735///
Mike Stump11289f42009-09-09 15:08:12 +00001736void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001737 ObjCInterfaceDecl *ID) {
1738 if (!ID)
1739 return; // Possibly due to previous error
1740
1741 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001742 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001743 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001744
1745 if (MethodMap.empty())
1746 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001747 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001748 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001749 if (PrevMethod &&
1750 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1751 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001752 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1753 << Method->getDeclName();
1754 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1755 }
1756 }
1757}
1758
James Dennett634962f2012-06-14 21:40:34 +00001759/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001760Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001761Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001762 ArrayRef<IdentifierLocPair> IdentList,
Erich Keanec480f302018-07-12 21:09:05 +00001763 const ParsedAttributesView &attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001764 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001765 for (const IdentifierLocPair &IdentPair : IdentList) {
1766 IdentifierInfo *Ident = IdentPair.first;
1767 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Richard Smithbecb92d2017-10-10 22:33:17 +00001768 forRedeclarationInCurContext());
Douglas Gregor32c17572012-01-01 20:30:41 +00001769 ObjCProtocolDecl *PDecl
Fangrui Song6907ce22018-07-30 19:24:48 +00001770 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001771 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001772 PrevDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001773
Douglas Gregor32c17572012-01-01 20:30:41 +00001774 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001775 CheckObjCDeclScope(PDecl);
Erich Keanec480f302018-07-12 21:09:05 +00001776
1777 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001778 AddPragmaAttributes(TUScope, PDecl);
1779
Douglas Gregor32c17572012-01-01 20:30:41 +00001780 if (PrevDecl)
1781 mergeDeclAttributes(PDecl, PrevDecl);
1782
Douglas Gregorf6102672012-01-01 21:23:57 +00001783 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001784 }
Mike Stump11289f42009-09-09 15:08:12 +00001785
Richard Smith3beb7c62017-01-12 02:27:38 +00001786 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001787}
1788
Erich Keanec480f302018-07-12 21:09:05 +00001789Decl *Sema::ActOnStartCategoryInterface(
1790 SourceLocation AtInterfaceLoc, IdentifierInfo *ClassName,
1791 SourceLocation ClassLoc, ObjCTypeParamList *typeParamList,
1792 IdentifierInfo *CategoryName, SourceLocation CategoryLoc,
1793 Decl *const *ProtoRefs, unsigned NumProtoRefs,
1794 const SourceLocation *ProtoLocs, SourceLocation EndProtoLoc,
1795 const ParsedAttributesView &AttrList) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001796 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001797 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001798
1799 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001800
Fangrui Song6907ce22018-07-30 19:24:48 +00001801 if (!IDecl
Douglas Gregor4123a862011-11-14 22:10:01 +00001802 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001803 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001804 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001805 // Create an invalid ObjCCategoryDecl to serve as context for
1806 // the enclosing method declarations. We mark the decl invalid
1807 // to make it clear that this isn't a valid AST.
1808 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001809 ClassLoc, CategoryLoc, CategoryName,
1810 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001811 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001812 CurContext->addDecl(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001813
Douglas Gregor4123a862011-11-14 22:10:01 +00001814 if (!IDecl)
1815 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001816 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001817 }
1818
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001819 if (!CategoryName && IDecl->getImplementation()) {
1820 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
Fangrui Song6907ce22018-07-30 19:24:48 +00001821 Diag(IDecl->getImplementation()->getLocation(),
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001822 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001823 }
1824
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001825 if (CategoryName) {
1826 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001827 if (ObjCCategoryDecl *Previous
1828 = IDecl->FindCategoryDeclaration(CategoryName)) {
1829 // Class extensions can be declared multiple times, categories cannot.
1830 Diag(CategoryLoc, diag::warn_dup_category_def)
1831 << ClassName << CategoryName;
1832 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001833 }
1834 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001835
Douglas Gregor85f3f952015-07-07 03:57:15 +00001836 // If we have a type parameter list, check it.
1837 if (typeParamList) {
1838 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1839 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1840 CategoryName
1841 ? TypeParamListContext::Category
1842 : TypeParamListContext::Extension))
1843 typeParamList = nullptr;
1844 } else {
1845 Diag(typeParamList->getLAngleLoc(),
1846 diag::err_objc_parameterized_category_nonclass)
1847 << (CategoryName != nullptr)
1848 << ClassName
1849 << typeParamList->getSourceRange();
1850
1851 typeParamList = nullptr;
1852 }
1853 }
1854
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001855 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001856 ClassLoc, CategoryLoc, CategoryName, IDecl,
1857 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001858 // FIXME: PushOnScopeChains?
1859 CurContext->addDecl(CDecl);
1860
Alex Lorenza9c966d2018-02-23 23:49:43 +00001861 // Process the attributes before looking at protocols to ensure that the
1862 // availability attribute is attached to the category to provide availability
1863 // checking for protocol uses.
Erich Keanec480f302018-07-12 21:09:05 +00001864 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
Alex Lorenza9c966d2018-02-23 23:49:43 +00001865 AddPragmaAttributes(TUScope, CDecl);
1866
Chris Lattnerda463fe2007-12-12 07:09:47 +00001867 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001868 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1869 NumProtoRefs, ProtoLocs);
1870 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001871 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001872 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001873 if (CDecl->IsClassExtension())
Fangrui Song6907ce22018-07-30 19:24:48 +00001874 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
1875 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001876 }
Mike Stump11289f42009-09-09 15:08:12 +00001877
Anders Carlssona6b508a2008-11-04 16:57:32 +00001878 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001879 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001880}
1881
1882/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001883/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001884/// object.
John McCall48871652010-08-21 09:40:31 +00001885Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001886 SourceLocation AtCatImplLoc,
1887 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1888 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001889 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001890 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001891 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001892 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1893 if (!CatIDecl) {
1894 // Category @implementation with no corresponding @interface.
1895 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001896 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1897 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001898 CatName, IDecl,
1899 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001900 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001901 }
1902 }
1903
Mike Stump11289f42009-09-09 15:08:12 +00001904 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001905 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001906 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001907 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001908 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001909 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001910 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001911 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1912 diag::err_undef_interface)) {
1913 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001914 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001915
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001916 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001917 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001918
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001919 // If the interface has the objc_runtime_visible attribute, we
1920 // cannot implement a category for it.
1921 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1922 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1923 << IDecl->getDeclName();
1924 }
1925
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001926 /// Check that CatName, category name, is not used in another implementation.
1927 if (CatIDecl) {
1928 if (CatIDecl->getImplementation()) {
1929 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1930 << CatName;
1931 Diag(CatIDecl->getImplementation()->getLocation(),
1932 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001933 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001934 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001935 CatIDecl->setImplementation(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00001936 // Warn on implementating category of deprecated class under
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001937 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00001938 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1939 CDecl->getLocation());
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001940 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001941 }
Mike Stump11289f42009-09-09 15:08:12 +00001942
Anders Carlssona6b508a2008-11-04 16:57:32 +00001943 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001944 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001945}
1946
John McCall48871652010-08-21 09:40:31 +00001947Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001948 SourceLocation AtClassImplLoc,
1949 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001950 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001951 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001952 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001953 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001954 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001955 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001956 forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001957 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001958 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001959 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001960 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001961 // FIXME: This will produce an error if the definition of the interface has
1962 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001963 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1964 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001965 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001966 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001967 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001968 TypoCorrection Corrected = CorrectTypo(
1969 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1970 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001971 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1972 // Suggest the (potentially) correct interface name. Don't provide a
1973 // code-modification hint or use the typo name for recovery, because
1974 // this is just a warning. The program may actually be correct.
1975 diagnoseTypo(Corrected,
1976 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1977 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001978 } else {
1979 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1980 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001981 }
Mike Stump11289f42009-09-09 15:08:12 +00001982
Chris Lattnerda463fe2007-12-12 07:09:47 +00001983 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001984 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001985 if (SuperClassname) {
1986 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001987 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1988 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001989 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001990 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1991 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001992 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001993 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001994 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001995 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001996 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001997 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001998 Diag(SuperClassLoc, diag::err_undef_superclass)
1999 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00002000 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00002001 // This implementation and its interface do not have the same
2002 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002003 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002004 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002005 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002006 }
2007 }
2008 }
Mike Stump11289f42009-09-09 15:08:12 +00002009
Chris Lattnerda463fe2007-12-12 07:09:47 +00002010 if (!IDecl) {
2011 // Legacy case of @implementation with no corresponding @interface.
2012 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00002013
Mike Stump87c57ac2009-05-16 07:39:55 +00002014 // FIXME: Do we support attributes on the @implementation? If so we should
2015 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00002016 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002017 ClassName, /*typeParamList=*/nullptr,
2018 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00002019 true);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00002020 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002021 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00002022 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00002023 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
2024 Context.getObjCInterfaceType(SDecl),
2025 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00002026 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
2027 } else {
2028 IDecl->setEndOfDefinitionLoc(ClassLoc);
2029 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002030
Douglas Gregorac345a32009-04-24 00:16:12 +00002031 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00002032 } else {
2033 // Mark the interface as being completed, even if it was just as
2034 // @class ....;
2035 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002036 if (!IDecl->hasDefinition())
2037 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002038 }
Mike Stump11289f42009-09-09 15:08:12 +00002039
2040 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00002041 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00002042 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002043
Anders Carlssona6b508a2008-11-04 16:57:32 +00002044 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002045 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002046
Chris Lattnerda463fe2007-12-12 07:09:47 +00002047 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00002048 if (IDecl->getImplementation()) {
2049 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002050 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00002051 Diag(IDecl->getImplementation()->getLocation(),
2052 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00002053 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00002054 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002055 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00002056 PushOnScopeChains(IMPDecl, TUScope);
Fangrui Song6907ce22018-07-30 19:24:48 +00002057 // Warn on implementating deprecated class under
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00002058 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00002059 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002060 }
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002061
2062 // If the superclass has the objc_runtime_visible attribute, we
2063 // cannot implement a subclass of it.
2064 if (IDecl->getSuperClass() &&
2065 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2066 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2067 << IDecl->getDeclName()
2068 << IDecl->getSuperClass()->getDeclName();
2069 }
2070
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002071 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002072}
2073
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002074Sema::DeclGroupPtrTy
2075Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2076 SmallVector<Decl *, 64> DeclsInGroup;
2077 DeclsInGroup.reserve(Decls.size() + 1);
2078
2079 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2080 Decl *Dcl = Decls[i];
2081 if (!Dcl)
2082 continue;
2083 if (Dcl->getDeclContext()->isFileContext())
2084 Dcl->setTopLevelDeclInObjCContainer();
2085 DeclsInGroup.push_back(Dcl);
2086 }
2087
2088 DeclsInGroup.push_back(ObjCImpDecl);
2089
Richard Smith3beb7c62017-01-12 02:27:38 +00002090 return BuildDeclaratorGroup(DeclsInGroup);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002091}
2092
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002093void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2094 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002095 SourceLocation RBrace) {
2096 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002097 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002098 if (!IDecl)
2099 return;
James Dennett634962f2012-06-14 21:40:34 +00002100 /// Check case of non-existing \@interface decl.
2101 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002102 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002103 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002104 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002105 // Add ivar's to class's DeclContext.
2106 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002107 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002108 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002109 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002110 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002111
Chris Lattnerda463fe2007-12-12 07:09:47 +00002112 return;
2113 }
2114 // If implementation has empty ivar list, just return.
2115 if (numIvars == 0)
2116 return;
Mike Stump11289f42009-09-09 15:08:12 +00002117
Chris Lattnerda463fe2007-12-12 07:09:47 +00002118 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002119 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002120 if (ImpDecl->getSuperClass())
2121 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2122 for (unsigned i = 0; i < numIvars; i++) {
2123 ObjCIvarDecl* ImplIvar = ivars[i];
Fangrui Song6907ce22018-07-30 19:24:48 +00002124 if (const ObjCIvarDecl *ClsIvar =
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002125 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002126 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002127 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2128 continue;
2129 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002130 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002131 for (const auto *CDecl : IDecl->visible_extensions()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002132 if (const ObjCIvarDecl *ClsExtIvar =
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002133 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002134 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002135 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2136 continue;
2137 }
2138 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002139 // Instance ivar to Implementation's DeclContext.
2140 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002141 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002142 ImpDecl->addDecl(ImplIvar);
2143 }
2144 return;
2145 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002146 // Check interface's Ivar list against those in the implementation.
2147 // names and types must match.
2148 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002149 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002150 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002151 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2152 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002153 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002154 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002155 assert (ImplIvar && "missing implementation ivar");
2156 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002157
Steve Naroff157599f2009-03-03 14:49:36 +00002158 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002159 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002160 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002161 << ImplIvar->getIdentifier()
2162 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002163 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002164 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2165 ImplIvar->getBitWidthValue(Context) !=
2166 ClsIvar->getBitWidthValue(Context)) {
2167 Diag(ImplIvar->getBitWidth()->getLocStart(),
2168 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2169 Diag(ClsIvar->getBitWidth()->getLocStart(),
2170 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002171 }
Steve Naroff157599f2009-03-03 14:49:36 +00002172 // Make sure the names are identical.
2173 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002174 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002175 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002176 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002177 }
2178 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002179 }
Mike Stump11289f42009-09-09 15:08:12 +00002180
Chris Lattner0f29d982007-12-12 18:11:49 +00002181 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002182 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002183 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002184 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002185}
2186
Ted Kremenekf87decd2013-12-13 05:58:44 +00002187static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2188 ObjCMethodDecl *method,
2189 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002190 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002191 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002192 // No point warning no definition of method which is 'unavailable'.
Erik Pilkingtonecce5c92018-07-07 01:50:20 +00002193 if (method->getAvailability() == AR_Unavailable)
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002194 return;
Erik Pilkingtonecce5c92018-07-07 01:50:20 +00002195
Ted Kremenek65d63572013-03-27 00:02:21 +00002196 // FIXME: For now ignore 'IncompleteImpl'.
2197 // Previously we grouped all unimplemented methods under a single
2198 // warning, but some users strongly voiced that they would prefer
2199 // separate warnings. We will give that approach a try, as that
2200 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002201 {
2202 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2203 B << method;
2204 if (NeededFor)
2205 B << NeededFor;
2206 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002207
2208 // Issue a note to the original declaration.
2209 SourceLocation MethodLoc = method->getLocStart();
2210 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002211 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002212}
2213
David Chisnallb62d15c2010-10-25 17:23:52 +00002214/// Determines if type B can be substituted for type A. Returns true if we can
Fangrui Song6907ce22018-07-30 19:24:48 +00002215/// guarantee that anything that the user will do to an object of type A can
2216/// also be done to an object of type B. This is trivially true if the two
David Chisnallb62d15c2010-10-25 17:23:52 +00002217/// types are the same, or if B is a subclass of A. It becomes more complex
2218/// in cases where protocols are involved.
2219///
2220/// Object types in Objective-C describe the minimum requirements for an
2221/// object, rather than providing a complete description of a type. For
2222/// example, if A is a subclass of B, then B* may refer to an instance of A.
2223/// The principle of substitutability means that we may use an instance of A
2224/// anywhere that we may use an instance of B - it will implement all of the
Fangrui Song6907ce22018-07-30 19:24:48 +00002225/// ivars of B and all of the methods of B.
David Chisnallb62d15c2010-10-25 17:23:52 +00002226///
Fangrui Song6907ce22018-07-30 19:24:48 +00002227/// This substitutability is important when type checking methods, because
David Chisnallb62d15c2010-10-25 17:23:52 +00002228/// the implementation may have stricter type definitions than the interface.
2229/// The interface specifies minimum requirements, but the implementation may
Fangrui Song6907ce22018-07-30 19:24:48 +00002230/// have more accurate ones. For example, a method may privately accept
David Chisnallb62d15c2010-10-25 17:23:52 +00002231/// instances of B, but only publish that it accepts instances of A. Any
2232/// object passed to it will be type checked against B, and so will implicitly
2233/// by a valid A*. Similarly, a method may return a subclass of the class that
2234/// it is declared as returning.
2235///
2236/// This is most important when considering subclassing. A method in a
2237/// subclass must accept any object as an argument that its superclass's
2238/// implementation accepts. It may, however, accept a more general type
2239/// without breaking substitutability (i.e. you can still use the subclass
2240/// anywhere that you can use the superclass, but not vice versa). The
2241/// converse requirement applies to return types: the return type for a
2242/// subclass method must be a valid object of the kind that the superclass
2243/// advertises, but it may be specified more accurately. This avoids the need
2244/// for explicit down-casting by callers.
2245///
Fangrui Song6907ce22018-07-30 19:24:48 +00002246/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002247static bool isObjCTypeSubstitutable(ASTContext &Context,
2248 const ObjCObjectPointerType *A,
2249 const ObjCObjectPointerType *B,
2250 bool rejectId) {
2251 // Reject a protocol-unqualified id.
2252 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002253
2254 // If B is a qualified id, then A must also be a qualified id and it must
2255 // implement all of the protocols in B. It may not be a qualified class.
2256 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2257 // stricter definition so it is not substitutable for id<A>.
2258 if (B->isObjCQualifiedIdType()) {
2259 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002260 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2261 QualType(B,0),
2262 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002263 }
2264
2265 /*
2266 // id is a special type that bypasses type checking completely. We want a
2267 // warning when it is used in one place but not another.
2268 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2269
2270
2271 // If B is a qualified id, then A must also be a qualified id (which it isn't
2272 // if we've got this far)
2273 if (B->isObjCQualifiedIdType()) return false;
2274 */
2275
2276 // Now we know that A and B are (potentially-qualified) class types. The
2277 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002278 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002279}
2280
John McCall071df462010-10-28 02:34:38 +00002281static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2282 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2283}
2284
Douglas Gregor813a0662015-06-19 18:14:38 +00002285/// Determine whether two set of Objective-C declaration qualifiers conflict.
2286static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2287 Decl::ObjCDeclQualifier y) {
2288 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2289 (y & ~Decl::OBJC_TQ_CSNullability);
2290}
2291
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002292static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002293 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002294 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002295 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002296 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002297 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002298 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002299 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2300 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002301 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002302 S.Diag(MethodImpl->getLocation(),
2303 (IsOverridingMode
2304 ? diag::warn_conflicting_overriding_ret_type_modifiers
2305 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002306 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002307 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002308 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002309 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002310 }
2311 else
2312 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002313 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002314 if (Warn && IsOverridingMode &&
2315 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2316 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2317 MethodDecl->getReturnType(),
2318 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002319 auto nullabilityMethodImpl =
2320 *MethodImpl->getReturnType()->getNullability(S.Context);
2321 auto nullabilityMethodDecl =
2322 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002323 S.Diag(MethodImpl->getLocation(),
2324 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002325 << DiagNullabilityKind(
2326 nullabilityMethodImpl,
2327 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2328 != 0))
2329 << DiagNullabilityKind(
2330 nullabilityMethodDecl,
2331 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2332 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002333 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2334 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002335
Alp Toker314cc812014-01-25 16:55:45 +00002336 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2337 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002338 return true;
2339 if (!Warn)
2340 return false;
John McCall071df462010-10-28 02:34:38 +00002341
Fangrui Song6907ce22018-07-30 19:24:48 +00002342 unsigned DiagID =
2343 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002344 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002345
2346 // Mismatches between ObjC pointers go into a different warning
2347 // category, and sometimes they're even completely whitelisted.
2348 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002349 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002350 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002351 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002352 // Allow non-matching return types as long as they don't violate
2353 // the principle of substitutability. Specifically, we permit
2354 // return types that are subclasses of the declared return type,
2355 // or that are more-qualified versions of the declared type.
2356 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002357 return false;
John McCall071df462010-10-28 02:34:38 +00002358
Fangrui Song6907ce22018-07-30 19:24:48 +00002359 DiagID =
2360 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002361 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002362 }
2363 }
2364
2365 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002366 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2367 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002368 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002369 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2370 ? diag::note_previous_declaration
2371 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002372 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002373 return false;
John McCall071df462010-10-28 02:34:38 +00002374}
2375
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002376static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002377 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002378 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002379 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002380 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002381 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002382 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002383 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002384 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002385 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2386 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002387 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002388 if (IsOverridingMode)
Fangrui Song6907ce22018-07-30 19:24:48 +00002389 S.Diag(ImplVar->getLocation(),
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002390 diag::warn_conflicting_overriding_param_modifiers)
2391 << getTypeRange(ImplVar->getTypeSourceInfo())
2392 << MethodImpl->getDeclName();
Fangrui Song6907ce22018-07-30 19:24:48 +00002393 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002394 diag::warn_conflicting_param_modifiers)
2395 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002396 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002397 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
Fangrui Song6907ce22018-07-30 19:24:48 +00002398 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002399 }
2400 else
2401 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002402 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002403
John McCall071df462010-10-28 02:34:38 +00002404 QualType ImplTy = ImplVar->getType();
2405 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002406 if (Warn && IsOverridingMode &&
2407 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2408 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002409 S.Diag(ImplVar->getLocation(),
2410 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002411 << DiagNullabilityKind(
2412 *ImplTy->getNullability(S.Context),
2413 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2414 != 0))
2415 << DiagNullabilityKind(
2416 *IfaceTy->getNullability(S.Context),
2417 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2418 != 0));
2419 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002420 }
John McCall071df462010-10-28 02:34:38 +00002421 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002422 return true;
Manman Renc5705ba2016-09-13 17:41:05 +00002423
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002424 if (!Warn)
2425 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00002426 unsigned DiagID =
2427 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002428 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002429
2430 // Mismatches between ObjC pointers go into a different warning
2431 // category, and sometimes they're even completely whitelisted.
2432 if (const ObjCObjectPointerType *ImplPtrTy =
2433 ImplTy->getAs<ObjCObjectPointerType>()) {
2434 if (const ObjCObjectPointerType *IfacePtrTy =
2435 IfaceTy->getAs<ObjCObjectPointerType>()) {
2436 // Allow non-matching argument types as long as they don't
2437 // violate the principle of substitutability. Specifically, the
2438 // implementation must accept any objects that the superclass
2439 // accepts, however it may also accept others.
2440 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002441 return false;
John McCall071df462010-10-28 02:34:38 +00002442
Fangrui Song6907ce22018-07-30 19:24:48 +00002443 DiagID =
2444 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002445 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002446 }
2447 }
2448
2449 S.Diag(ImplVar->getLocation(), DiagID)
2450 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002451 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
Fangrui Song6907ce22018-07-30 19:24:48 +00002452 S.Diag(IfaceVar->getLocation(),
2453 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002454 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002455 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002456 return false;
John McCall071df462010-10-28 02:34:38 +00002457}
John McCall31168b02011-06-15 23:02:42 +00002458
2459/// In ARC, check whether the conventional meanings of the two methods
2460/// match. If they don't, it's a hard error.
2461static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2462 ObjCMethodDecl *decl) {
2463 ObjCMethodFamily implFamily = impl->getMethodFamily();
2464 ObjCMethodFamily declFamily = decl->getMethodFamily();
2465 if (implFamily == declFamily) return false;
2466
2467 // Since conventions are sorted by selector, the only possibility is
2468 // that the types differ enough to cause one selector or the other
2469 // to fall out of the family.
2470 assert(implFamily == OMF_None || declFamily == OMF_None);
2471
2472 // No further diagnostics required on invalid declarations.
2473 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2474
2475 const ObjCMethodDecl *unmatched = impl;
2476 ObjCMethodFamily family = declFamily;
2477 unsigned errorID = diag::err_arc_lost_method_convention;
2478 unsigned noteID = diag::note_arc_lost_method_convention;
2479 if (declFamily == OMF_None) {
2480 unmatched = decl;
2481 family = implFamily;
2482 errorID = diag::err_arc_gained_method_convention;
2483 noteID = diag::note_arc_gained_method_convention;
2484 }
2485
2486 // Indexes into a %select clause in the diagnostic.
2487 enum FamilySelector {
2488 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2489 };
2490 FamilySelector familySelector = FamilySelector();
2491
2492 switch (family) {
2493 case OMF_None: llvm_unreachable("logic error, no method convention");
2494 case OMF_retain:
2495 case OMF_release:
2496 case OMF_autorelease:
2497 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002498 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002499 case OMF_retainCount:
2500 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002501 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002502 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002503 // Mismatches for these methods don't change ownership
2504 // conventions, so we don't care.
2505 return false;
2506
2507 case OMF_init: familySelector = F_init; break;
2508 case OMF_alloc: familySelector = F_alloc; break;
2509 case OMF_copy: familySelector = F_copy; break;
2510 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2511 case OMF_new: familySelector = F_new; break;
2512 }
2513
2514 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2515 ReasonSelector reasonSelector;
2516
2517 // The only reason these methods don't fall within their families is
2518 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002519 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002520 reasonSelector = R_UnrelatedReturn;
2521 } else {
2522 reasonSelector = R_NonObjectReturn;
2523 }
2524
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002525 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2526 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002527
2528 return true;
2529}
John McCall071df462010-10-28 02:34:38 +00002530
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002531void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002532 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002533 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002534 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002535 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2536 return;
2537
Fangrui Song6907ce22018-07-30 19:24:48 +00002538 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2539 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002540 true);
Mike Stump11289f42009-09-09 15:08:12 +00002541
Chris Lattner67f35b02009-04-11 19:58:42 +00002542 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002543 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2544 EF = MethodDecl->param_end();
2545 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002546 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002547 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002548 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002549
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002550 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002551 Diag(ImpMethodDecl->getLocation(),
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002552 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002553 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002554 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002555}
2556
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002557void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2558 ObjCMethodDecl *Overridden,
2559 bool IsProtocolMethodDecl) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002560
2561 CheckMethodOverrideReturn(*this, Method, Overridden,
2562 IsProtocolMethodDecl, true,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002563 true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002564
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002565 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002566 IF = Overridden->param_begin(), EM = Method->param_end(),
2567 EF = Overridden->param_end();
2568 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002569 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2570 IsProtocolMethodDecl, true, true);
2571 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002572
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002573 if (Method->isVariadic() != Overridden->isVariadic()) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002574 Diag(Method->getLocation(),
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002575 diag::warn_conflicting_overriding_variadic);
2576 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2577 }
2578}
2579
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002580/// WarnExactTypedMethods - This routine issues a warning if method
2581/// implementation declaration matches exactly that of its declaration.
2582void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2583 ObjCMethodDecl *MethodDecl,
2584 bool IsProtocolMethodDecl) {
2585 // don't issue warning when protocol method is optional because primary
2586 // class is not required to implement it and it is safe for protocol
2587 // to implement it.
2588 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2589 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002590 // don't issue warning when primary class's method is
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002591 // depecated/unavailable.
2592 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2593 MethodDecl->hasAttr<DeprecatedAttr>())
2594 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002595
2596 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002597 IsProtocolMethodDecl, false, false);
2598 if (match)
2599 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002600 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2601 EF = MethodDecl->param_end();
2602 IM != EM && IF != EF; ++IM, ++IF) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002603 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002604 *IM, *IF,
2605 IsProtocolMethodDecl, false, false);
2606 if (!match)
2607 break;
2608 }
2609 if (match)
2610 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002611 if (match)
2612 match = !(MethodDecl->isClassMethod() &&
2613 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fangrui Song6907ce22018-07-30 19:24:48 +00002614
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002615 if (match) {
Fangrui Song6907ce22018-07-30 19:24:48 +00002616 Diag(ImpMethodDecl->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002617 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002618 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2619 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002620 }
2621}
2622
Mike Stump87c57ac2009-05-16 07:39:55 +00002623/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2624/// improve the efficiency of selector lookups and type checking by associating
2625/// with each protocol / interface / category the flattened instance tables. If
2626/// we used an immutable set to keep the table then it wouldn't add significant
2627/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002628
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002629typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002630typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002631
2632static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2633 ProtocolNameSet &PNS) {
2634 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2635 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002636 for (const auto *PI : PDecl->protocols())
2637 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002638}
2639
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002640/// Recursively populates a set with all conformed protocols in a class
2641/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2642/// attribute.
2643static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2644 ProtocolNameSet &PNS) {
2645 if (!Super)
2646 return;
2647
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002648 for (const auto *I : Super->all_referenced_protocols())
2649 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002650
2651 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002652}
2653
Steve Naroffa36992242008-02-08 22:06:17 +00002654/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002655/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002656static void CheckProtocolMethodDefs(Sema &S,
2657 SourceLocation ImpLoc,
2658 ObjCProtocolDecl *PDecl,
2659 bool& IncompleteImpl,
2660 const Sema::SelectorSet &InsMap,
2661 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002662 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002663 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002664 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
Fangrui Song6907ce22018-07-30 19:24:48 +00002665 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002666 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002667 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
Fangrui Song6907ce22018-07-30 19:24:48 +00002668
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002669 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002670 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002671
2672 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2673 // then we should check if any class in the super class hierarchy also
2674 // conforms to this protocol, either directly or via protocol inheritance.
2675 // If so, we can skip checking this protocol completely because we
2676 // know that a parent class already satisfies this protocol.
2677 //
2678 // Note: we could generalize this logic for all protocols, and merely
2679 // add the limit on looking at the super class chain for just
2680 // specially marked protocols. This may be a good optimization. This
2681 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2682 // protocols for now for controlled evaluation.
2683 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002684 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002685 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2686 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2687 }
2688 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2689 ProtocolsExplictImpl->end())
2690 return;
2691
2692 // If no super class conforms to the protocol, we should not search
2693 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002694 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002695 }
2696
Ted Kremenek285ee852013-12-13 06:26:10 +00002697 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002698 // check to see if class implements forwardInvocation method and objects
2699 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002700 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002701 // Under such conditions, which means that every method possible is
2702 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002703 // found" warnings.
2704 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002705 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2706 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002707 if (InsMap.count(fISelector))
2708 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2709 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002710 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002711 }
Mike Stump11289f42009-09-09 15:08:12 +00002712
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002713 // If this is a forward protocol declaration, get its definition.
2714 if (!PDecl->isThisDeclarationADefinition() &&
2715 PDecl->getDefinition())
2716 PDecl = PDecl->getDefinition();
Fangrui Song6907ce22018-07-30 19:24:48 +00002717
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002718 // If a method lookup fails locally we still need to look and see if
2719 // the method was implemented by a base class or an inherited
2720 // protocol. This lookup is slow, but occurs rarely in correct code
2721 // and otherwise would terminate in a warning.
2722
Chris Lattnerda463fe2007-12-12 07:09:47 +00002723 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002724 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002725 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002726 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002727 !method->isPropertyAccessor() &&
2728 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002729 (!Super || !Super->lookupMethod(method->getSelector(),
2730 true /* instance */,
2731 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002732 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002733 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002734 // If a method is not implemented in the category implementation but
2735 // has been declared in its primary class, superclass,
Fangrui Song6907ce22018-07-30 19:24:48 +00002736 // or in one of their protocols, no need to issue the warning.
2737 // This is because method will be implemented in the primary class
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002738 // or one of its super class implementation.
Fangrui Song6907ce22018-07-30 19:24:48 +00002739
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00002740 // Ugly, but necessary. Method declared in protocol might have
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002741 // have been synthesized due to a property declared in the class which
2742 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002743 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002744 IDecl->lookupMethod(method->getSelector(),
2745 true /* instance */,
2746 true /* shallowCategoryLookup */,
2747 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002748 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002749 continue;
2750 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002751 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002752 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002753 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002754 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002755 }
2756 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002757 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002758 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002759 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2760 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002761 (!Super || !Super->lookupMethod(method->getSelector(),
2762 false /* class method */,
2763 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002764 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002765 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002766 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002767 if (C && IDecl->lookupMethod(method->getSelector(),
2768 false /* class */,
2769 true /* shallowCategoryLookup */,
2770 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002771 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002772
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002773 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002774 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002775 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002776 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002777 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002778 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002779 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002780 for (auto *PI : PDecl->protocols())
2781 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002782 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002783}
2784
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002785/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002786/// or protocol against those declared in their implementations.
2787///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002788void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2789 const SelectorSet &ClsMap,
2790 SelectorSet &InsMapSeen,
2791 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002792 ObjCImplDecl* IMPDecl,
2793 ObjCContainerDecl* CDecl,
2794 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002795 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002796 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002797 // Check and see if instance methods in class interface have been
2798 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002799 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002800 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002801 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002802 if (!I->isPropertyAccessor() &&
2803 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002804 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002805 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002806 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002807 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002808 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002809 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002810 IMPDecl->getInstanceMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002811 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002812 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002813 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002814 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002815 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002816 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002817 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002818 else if (!I->isPropertyAccessor())
2819 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002820 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002821 }
2822 }
Mike Stump11289f42009-09-09 15:08:12 +00002823
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002824 // Check and see if class methods in class interface have been
2825 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002826 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002827 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002828 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002829 if (!I->isPropertyAccessor() &&
2830 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002831 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002832 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002833 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002834 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002835 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002836 IMPDecl->getClassMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002837 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002838 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002839 // ImpMethodDecl may be null as in a @dynamic property.
2840 if (ImpMethodDecl) {
2841 if (!WarnCategoryMethodImpl)
2842 WarnConflictingTypedMethods(ImpMethodDecl, I,
2843 isa<ObjCProtocolDecl>(CDecl));
2844 else if (!I->isPropertyAccessor())
2845 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2846 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002847 }
2848 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002849
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002850 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2851 // Also, check for methods declared in protocols inherited by
2852 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002853 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002854 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002855 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002856 WarnCategoryMethodImpl);
2857 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002858
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002859 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002860 // when checking that methods in implementation match their declaration,
2861 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2862 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002863 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002864 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002865 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002866 IMPDecl, Cat, IncompleteImpl,
2867 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002868 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002869 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002870 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002871 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002872 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002873 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002874 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002875 }
2876
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002877 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002878 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002879 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002880 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002881 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002882
Fangrui Song6907ce22018-07-30 19:24:48 +00002883 // FIXME. For now, we are not checking for extact match of methods
2884 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002885 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002886 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002887 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002888 I->getSuperClass(), IncompleteImpl, false);
2889 }
2890}
2891
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002892/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2893/// category matches with those implemented in its primary class and
Fangrui Song6907ce22018-07-30 19:24:48 +00002894/// warns each time an exact match is found.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002895void Sema::CheckCategoryVsClassMethodMatches(
2896 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002897 // Get category's primary class.
2898 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2899 if (!CatDecl)
2900 return;
2901 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2902 if (!IDecl)
2903 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002904 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2905 SelectorSet InsMap, ClsMap;
Fangrui Song6907ce22018-07-30 19:24:48 +00002906
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002907 for (const auto *I : CatIMPDecl->instance_methods()) {
2908 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002909 // When checking for methods implemented in the category, skip over
2910 // those declared in category class's super class. This is because
2911 // the super class must implement the method.
2912 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2913 continue;
2914 InsMap.insert(Sel);
2915 }
Fangrui Song6907ce22018-07-30 19:24:48 +00002916
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002917 for (const auto *I : CatIMPDecl->class_methods()) {
2918 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002919 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2920 continue;
2921 ClsMap.insert(Sel);
2922 }
2923 if (InsMap.empty() && ClsMap.empty())
2924 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00002925
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002926 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002927 bool IncompleteImpl = false;
2928 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2929 CatIMPDecl, IDecl,
Fangrui Song6907ce22018-07-30 19:24:48 +00002930 IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002931 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002932}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002933
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002934void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002935 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002936 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002937 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002938 // Check and see if instance methods in class interface have been
2939 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002940 for (const auto *I : IMPDecl->instance_methods())
2941 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002942
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002943 // Add the selectors for getters/setters of @dynamic properties.
2944 for (const auto *PImpl : IMPDecl->property_impls()) {
2945 // We only care about @dynamic implementations.
2946 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2947 continue;
2948
2949 const auto *P = PImpl->getPropertyDecl();
2950 if (!P) continue;
2951
2952 InsMap.insert(P->getGetterName());
2953 if (!P->getSetterName().isNull())
2954 InsMap.insert(P->getSetterName());
2955 }
2956
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002957 // Check and see if properties declared in the interface have either 1)
2958 // an implementation or 2) there is a @synthesize/@dynamic implementation
2959 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002960 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2961 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2962 LangOpts.ObjCRuntime.isNonFragile() &&
2963 !IDecl->isObjCRequiresPropertyDefs();
2964 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2965 }
2966
Douglas Gregor849ebc22015-06-19 18:14:46 +00002967 // Diagnose null-resettable synthesized setters.
2968 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2969
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002970 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002971 for (const auto *I : IMPDecl->class_methods())
2972 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002973
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002974 // Check for type conflict of methods declared in a class/protocol and
2975 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002976 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002977 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2978 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002979 IncompleteImpl, true);
Fangrui Song6907ce22018-07-30 19:24:48 +00002980
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002981 // check all methods implemented in category against those declared
2982 // in its primary class.
Fangrui Song6907ce22018-07-30 19:24:48 +00002983 if (ObjCCategoryImplDecl *CatDecl =
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002984 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2985 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002986
Chris Lattnerda463fe2007-12-12 07:09:47 +00002987 // Check the protocol list for unimplemented methods in the @implementation
2988 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002989 // Check and see if class methods in class interface have been
2990 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002991
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002992 LazyProtocolNameSet ExplicitImplProtocols;
2993
Chris Lattner9ef10f42009-03-01 00:56:52 +00002994 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002995 for (auto *PI : I->all_referenced_protocols())
2996 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2997 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002998 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002999 // For extended class, unimplemented methods in its protocols will
3000 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003001 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00003002 for (auto *P : C->protocols())
3003 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00003004 IncompleteImpl, InsMap, ClsMap, CDecl,
3005 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00003006 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00003007 /*SynthesizeProperties=*/false);
Fangrui Song6907ce22018-07-30 19:24:48 +00003008 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00003009 } else
David Blaikie83d382b2011-09-23 05:06:16 +00003010 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00003011}
3012
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003013Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00003014Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00003015 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00003016 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003017 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00003018 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00003019 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003020 for (unsigned i = 0; i != NumElts; ++i) {
3021 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003022 NamedDecl *PrevDecl
Fangrui Song6907ce22018-07-30 19:24:48 +00003023 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Richard Smithbecb92d2017-10-10 22:33:17 +00003024 LookupOrdinaryName, forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003025 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00003026 // GCC apparently allows the following idiom:
3027 //
3028 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3029 // @class XCElementToggler;
3030 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003031 // Here we have chosen to ignore the forward class declaration
3032 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00003033 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00003034 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003035 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00003036 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00003037 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00003038 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003039 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00003040 // as this will force the intended behavior which is to lookup the
3041 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003042 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003043 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3044 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003045 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3046 continue;
3047 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00003048 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003049 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003050
Douglas Gregordc9166c2011-12-15 20:29:51 +00003051 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003052 ObjCInterfaceDecl *PrevIDecl
3053 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00003054
3055 IdentifierInfo *ClassName = IdentList[i];
3056 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3057 // A previous decl with a different name is because of
3058 // @compatibility_alias, for example:
3059 // \code
3060 // @class NewImage;
3061 // @compatibility_alias OldImage NewImage;
3062 // \endcode
3063 // A lookup for 'OldImage' will return the 'NewImage' decl.
3064 //
3065 // In such a case use the real declaration name, instead of the alias one,
3066 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3067 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3068 // has been aliased.
3069 ClassName = PrevIDecl->getIdentifier();
3070 }
3071
Douglas Gregor85f3f952015-07-07 03:57:15 +00003072 // If this forward declaration has type parameters, compare them with the
3073 // type parameters of the previous declaration.
3074 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3075 if (PrevIDecl && TypeParams) {
3076 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3077 // Check for consistency with the previous declaration.
3078 if (checkTypeParamListConsistency(
3079 *this, PrevTypeParams, TypeParams,
3080 TypeParamListContext::ForwardDeclaration)) {
3081 TypeParams = nullptr;
3082 }
3083 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3084 // The @interface does not have type parameters. Complain.
3085 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3086 << ClassName
3087 << TypeParams->getSourceRange();
3088 Diag(Def->getLocation(), diag::note_defined_here)
3089 << ClassName;
3090
3091 TypeParams = nullptr;
3092 }
3093 }
3094
Douglas Gregordc9166c2011-12-15 20:29:51 +00003095 ObjCInterfaceDecl *IDecl
3096 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003097 ClassName, TypeParams, PrevIDecl,
3098 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003099 IDecl->setAtEndRange(IdentLocs[i]);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003100
Douglas Gregordc9166c2011-12-15 20:29:51 +00003101 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003102 CheckObjCDeclScope(IDecl);
3103 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003104 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003105
Richard Smith3beb7c62017-01-12 02:27:38 +00003106 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003107}
3108
John McCall54507ab2011-06-16 01:15:19 +00003109static bool tryMatchRecordTypes(ASTContext &Context,
3110 Sema::MethodMatchStrategy strategy,
3111 const Type *left, const Type *right);
3112
John McCall31168b02011-06-15 23:02:42 +00003113static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3114 QualType leftQT, QualType rightQT) {
3115 const Type *left =
3116 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3117 const Type *right =
3118 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3119
3120 if (left == right) return true;
3121
3122 // If we're doing a strict match, the types have to match exactly.
3123 if (strategy == Sema::MMS_strict) return false;
3124
3125 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3126
3127 // Otherwise, use this absurdly complicated algorithm to try to
3128 // validate the basic, low-level compatibility of the two types.
3129
3130 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003131 TypeInfo LeftTI = Context.getTypeInfo(left);
3132 TypeInfo RightTI = Context.getTypeInfo(right);
3133 if (LeftTI.Width != RightTI.Width)
3134 return false;
3135
3136 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003137 return false;
3138
3139 // Consider all the kinds of non-dependent canonical types:
3140 // - functions and arrays aren't possible as return and parameter types
Fangrui Song6907ce22018-07-30 19:24:48 +00003141
John McCall31168b02011-06-15 23:02:42 +00003142 // - vector types of equal size can be arbitrarily mixed
3143 if (isa<VectorType>(left)) return isa<VectorType>(right);
3144 if (isa<VectorType>(right)) return false;
3145
3146 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003147 // - structs, unions, and Objective-C objects must match more-or-less
3148 // exactly
John McCall31168b02011-06-15 23:02:42 +00003149 // - everything else should be a scalar
3150 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003151 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003152
John McCall9320b872011-09-09 05:25:32 +00003153 // Make scalars agree in kind, except count bools as chars, and group
3154 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003155 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3156 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3157 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3158 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003159 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3160 leftSK = Type::STK_ObjCObjectPointer;
3161 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3162 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003163
3164 // Note that data member pointers and function member pointers don't
3165 // intermix because of the size differences.
3166
3167 return (leftSK == rightSK);
3168}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003169
John McCall54507ab2011-06-16 01:15:19 +00003170static bool tryMatchRecordTypes(ASTContext &Context,
3171 Sema::MethodMatchStrategy strategy,
3172 const Type *lt, const Type *rt) {
3173 assert(lt && rt && lt != rt);
3174
3175 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3176 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3177 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3178
3179 // Require union-hood to match.
3180 if (left->isUnion() != right->isUnion()) return false;
3181
3182 // Require an exact match if either is non-POD.
3183 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3184 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3185 return false;
3186
3187 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003188 TypeInfo LeftTI = Context.getTypeInfo(lt);
3189 TypeInfo RightTI = Context.getTypeInfo(rt);
3190 if (LeftTI.Width != RightTI.Width)
3191 return false;
3192
3193 if (LeftTI.Align != RightTI.Align)
3194 return false;
John McCall54507ab2011-06-16 01:15:19 +00003195
3196 // Require fields to match.
3197 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3198 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3199 for (; li != le && ri != re; ++li, ++ri) {
3200 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3201 return false;
3202 }
3203 return (li == le && ri == re);
3204}
3205
Chris Lattnerda463fe2007-12-12 07:09:47 +00003206/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3207/// returns true, or false, accordingly.
3208/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003209bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3210 const ObjCMethodDecl *right,
3211 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003212 if (!matchTypes(Context, strategy, left->getReturnType(),
3213 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003214 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003215
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003216 // If either is hidden, it is not considered to match.
3217 if (left->isHidden() || right->isHidden())
3218 return false;
3219
David Blaikiebbafb8a2012-03-11 07:00:24 +00003220 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003221 (left->hasAttr<NSReturnsRetainedAttr>()
3222 != right->hasAttr<NSReturnsRetainedAttr>() ||
3223 left->hasAttr<NSConsumesSelfAttr>()
3224 != right->hasAttr<NSConsumesSelfAttr>()))
3225 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003226
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003227 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003228 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3229 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003230
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003231 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003232 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003233 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003234
3235 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3236 return false;
3237
David Blaikiebbafb8a2012-03-11 07:00:24 +00003238 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003239 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3240 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003241 }
3242 return true;
3243}
3244
Manman Ren71224532016-04-09 18:59:48 +00003245static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3246 ObjCMethodDecl *MethodInList) {
3247 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3248 auto *MethodInListProtocol =
3249 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3250 // If this method belongs to a protocol but the method in list does not, or
3251 // vice versa, we say the context is not the same.
3252 if ((MethodProtocol && !MethodInListProtocol) ||
3253 (!MethodProtocol && MethodInListProtocol))
3254 return false;
3255
3256 if (MethodProtocol && MethodInListProtocol)
3257 return true;
3258
3259 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3260 ObjCInterfaceDecl *MethodInListInterface =
3261 MethodInList->getClassInterface();
3262 return MethodInterface == MethodInListInterface;
3263}
3264
Nico Weber2e0c8f72014-12-27 03:58:08 +00003265void Sema::addMethodToGlobalList(ObjCMethodList *List,
3266 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003267 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3268 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003269 if (ObjCCategoryDecl *CD =
3270 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003271 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003272 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003273
Douglas Gregorc454afe2012-01-25 00:19:56 +00003274 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003275 if (List->getMethod() == nullptr) {
3276 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003277 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003278 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003279 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003280
Douglas Gregorc454afe2012-01-25 00:19:56 +00003281 // We've seen a method with this name, see if we have already seen this type
3282 // signature.
3283 ObjCMethodList *Previous = List;
Manman Ren051d0b62016-04-13 23:43:56 +00003284 ObjCMethodList *ListWithSameDeclaration = nullptr;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003285 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003286 // If we are building a module, keep all of the methods.
Richard Smithbbcc9f02016-08-26 00:14:38 +00003287 if (getLangOpts().isCompilingModule())
Douglas Gregor600a2f52013-06-21 00:20:25 +00003288 continue;
3289
Manman Ren051d0b62016-04-13 23:43:56 +00003290 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3291 List->getMethod());
Manman Ren71224532016-04-09 18:59:48 +00003292 // Looking for method with a type bound requires the correct context exists.
Manman Ren051d0b62016-04-13 23:43:56 +00003293 // We need to insert a method into the list if the context is different.
3294 // If the method's declaration matches the list
3295 // a> the method belongs to a different context: we need to insert it, in
3296 // order to emit the availability message, we need to prioritize over
3297 // availability among the methods with the same declaration.
3298 // b> the method belongs to the same context: there is no need to insert a
3299 // new entry.
3300 // If the method's declaration does not match the list, we insert it to the
3301 // end.
3302 if (!SameDeclaration ||
Manman Ren71224532016-04-09 18:59:48 +00003303 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003304 // Even if two method types do not match, we would like to say
3305 // there is more than one declaration so unavailability/deprecated
3306 // warning is not too noisy.
3307 if (!Method->isDefined())
3308 List->setHasMoreThanOneDecl(true);
Manman Ren051d0b62016-04-13 23:43:56 +00003309
3310 // For methods with the same declaration, the one that is deprecated
3311 // should be put in the front for better diagnostics.
3312 if (Method->isDeprecated() && SameDeclaration &&
3313 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3314 ListWithSameDeclaration = List;
3315
3316 if (Method->isUnavailable() && SameDeclaration &&
3317 !ListWithSameDeclaration &&
3318 List->getMethod()->getAvailability() < AR_Deprecated)
3319 ListWithSameDeclaration = List;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003320 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003321 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003322
3323 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003324
3325 // Propagate the 'defined' bit.
3326 if (Method->isDefined())
3327 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003328 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003329 // Objective-C doesn't allow an @interface for a class after its
3330 // @implementation. So if Method is not defined and there already is
3331 // an entry for this type signature, Method has to be for a different
3332 // class than PrevObjCMethod.
3333 List->setHasMoreThanOneDecl(true);
3334 }
3335
Douglas Gregorc454afe2012-01-25 00:19:56 +00003336 // If a method is deprecated, push it in the global pool.
3337 // This is used for better diagnostics.
3338 if (Method->isDeprecated()) {
3339 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003340 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003341 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003342 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003343 // unless previous one is deprecated.
3344 if (Method->isUnavailable()) {
3345 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003346 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003347 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003348
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003349 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003350 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003351
Douglas Gregorc454afe2012-01-25 00:19:56 +00003352 // We have a new signature for an existing method - add it.
3353 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003354 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Manman Ren71224532016-04-09 18:59:48 +00003355
Manman Ren051d0b62016-04-13 23:43:56 +00003356 // We insert it right before ListWithSameDeclaration.
3357 if (ListWithSameDeclaration) {
3358 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3359 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3360 ListWithSameDeclaration->setMethod(Method);
3361 ListWithSameDeclaration->setNext(List);
Manman Ren71224532016-04-09 18:59:48 +00003362 return;
3363 }
3364
Nico Weber2e0c8f72014-12-27 03:58:08 +00003365 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003366}
3367
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00003368/// Read the contents of the method pool for a given selector from
Sebastian Redl75d8a322010-08-02 23:18:59 +00003369/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003370void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003371 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003372 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003373}
3374
Manman Rena0f31a02016-04-29 19:04:05 +00003375void Sema::updateOutOfDateSelector(Selector Sel) {
3376 if (!ExternalSource)
3377 return;
3378 ExternalSource->updateOutOfDateSelector(Sel);
3379}
3380
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003381void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003382 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003383 // Ignore methods of invalid containers.
3384 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003385 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003386
Douglas Gregor70f449b2012-01-25 00:59:09 +00003387 if (ExternalSource)
3388 ReadMethodPool(Method->getSelector());
Fangrui Song6907ce22018-07-30 19:24:48 +00003389
Sebastian Redl75d8a322010-08-02 23:18:59 +00003390 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003391 if (Pos == MethodPool.end())
3392 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3393 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003394
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003395 Method->setDefined(impl);
Fangrui Song6907ce22018-07-30 19:24:48 +00003396
Sebastian Redl75d8a322010-08-02 23:18:59 +00003397 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003398 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003399}
3400
John McCall31168b02011-06-15 23:02:42 +00003401/// Determines if this is an "acceptable" loose mismatch in the global
3402/// method pool. This exists mostly as a hack to get around certain
3403/// global mismatches which we can't afford to make warnings / errors.
3404/// Really, what we want is a way to take a method out of the global
3405/// method pool.
3406static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3407 ObjCMethodDecl *other) {
3408 if (!chosen->isInstanceMethod())
3409 return false;
3410
3411 Selector sel = chosen->getSelector();
3412 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3413 return false;
3414
3415 // Don't complain about mismatches for -length if the method we
3416 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003417 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003418}
3419
Manman Ren7ed4f982016-04-07 19:32:24 +00003420/// Return true if the given method is wthin the type bound.
3421static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3422 const ObjCObjectType *TypeBound) {
3423 if (!TypeBound)
3424 return true;
3425
3426 if (TypeBound->isObjCId())
3427 // FIXME: should we handle the case of bounding to id<A, B> differently?
3428 return true;
3429
3430 auto *BoundInterface = TypeBound->getInterface();
3431 assert(BoundInterface && "unexpected object type!");
3432
3433 // Check if the Method belongs to a protocol. We should allow any method
3434 // defined in any protocol, because any subclass could adopt the protocol.
3435 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3436 if (MethodProtocol) {
3437 return true;
3438 }
3439
3440 // If the Method belongs to a class, check if it belongs to the class
3441 // hierarchy of the class bound.
3442 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3443 // We allow methods declared within classes that are part of the hierarchy
3444 // of the class bound (superclass of, subclass of, or the same as the class
3445 // bound).
3446 return MethodInterface == BoundInterface ||
3447 MethodInterface->isSuperClassOf(BoundInterface) ||
3448 BoundInterface->isSuperClassOf(MethodInterface);
3449 }
Alexander Kornienko2a8c18d2018-04-06 15:14:32 +00003450 llvm_unreachable("unknown method context");
Manman Ren7ed4f982016-04-07 19:32:24 +00003451}
3452
Manman Rend2a3cd72016-04-07 19:30:20 +00003453/// We first select the type of the method: Instance or Factory, then collect
3454/// all methods with that type.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003455bool Sema::CollectMultipleMethodsInGlobalPool(
Manman Rend2a3cd72016-04-07 19:30:20 +00003456 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
Manman Ren7ed4f982016-04-07 19:32:24 +00003457 bool InstanceFirst, bool CheckTheOther,
3458 const ObjCObjectType *TypeBound) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003459 if (ExternalSource)
3460 ReadMethodPool(Sel);
3461
3462 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3463 if (Pos == MethodPool.end())
3464 return false;
Manman Rend2a3cd72016-04-07 19:30:20 +00003465
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003466 // Gather the non-hidden methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00003467 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3468 Pos->second.second;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003469 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003470 if (M->getMethod() && !M->getMethod()->isHidden()) {
3471 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3472 Methods.push_back(M->getMethod());
3473 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003474
3475 // Return if we find any method with the desired kind.
3476 if (!Methods.empty())
3477 return Methods.size() > 1;
3478
3479 if (!CheckTheOther)
3480 return false;
3481
3482 // Gather the other kind.
3483 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3484 Pos->second.first;
3485 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003486 if (M->getMethod() && !M->getMethod()->isHidden()) {
3487 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3488 Methods.push_back(M->getMethod());
3489 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003490
Nico Weber2e0c8f72014-12-27 03:58:08 +00003491 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003492}
3493
Manman Rend2a3cd72016-04-07 19:30:20 +00003494bool Sema::AreMultipleMethodsInGlobalPool(
3495 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3496 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3497 // Diagnose finding more than one method in global pool.
3498 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3499 FilteredMethods.push_back(BestMethod);
3500
3501 for (auto *M : Methods)
3502 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3503 FilteredMethods.push_back(M);
3504
3505 if (FilteredMethods.size() > 1)
3506 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3507 receiverIdOrClass);
3508
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003509 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003510 // Test for no method in the pool which should not trigger any warning by
3511 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003512 if (Pos == MethodPool.end())
3513 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003514 ObjCMethodList &MethList =
3515 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003516 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003517}
3518
Sebastian Redl75d8a322010-08-02 23:18:59 +00003519ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003520 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003521 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003522 if (ExternalSource)
3523 ReadMethodPool(Sel);
Fangrui Song6907ce22018-07-30 19:24:48 +00003524
Sebastian Redl75d8a322010-08-02 23:18:59 +00003525 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003526 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003527 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003528
Douglas Gregor77f49a42013-01-16 18:47:38 +00003529 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003530 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003531 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003532 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003533 if (M->getMethod() && !M->getMethod()->isHidden())
3534 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003535 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003536 return nullptr;
3537}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003538
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003539void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3540 Selector Sel, SourceRange R,
3541 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003542 // We found multiple methods, so we may have to complain.
3543 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003544
Douglas Gregor77f49a42013-01-16 18:47:38 +00003545 // We support a warning which complains about *any* difference in
3546 // method signature.
3547 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003548 receiverIdOrClass &&
3549 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003550 if (strictSelectorMatch) {
3551 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3552 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3553 issueDiagnostic = true;
3554 break;
3555 }
3556 }
3557 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003558
Douglas Gregor77f49a42013-01-16 18:47:38 +00003559 // If we didn't see any strict differences, we won't see any loose
3560 // differences. In ARC, however, we also need to check for loose
3561 // mismatches, because most of them are errors.
3562 if (!strictSelectorMatch ||
3563 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3564 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3565 // This checks if the methods differ in type mismatch.
3566 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3567 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3568 issueDiagnostic = true;
3569 if (getLangOpts().ObjCAutoRefCount)
3570 issueError = true;
3571 break;
3572 }
3573 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003574
Douglas Gregor77f49a42013-01-16 18:47:38 +00003575 if (issueDiagnostic) {
3576 if (issueError)
3577 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3578 else if (strictSelectorMatch)
3579 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3580 else
3581 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fangrui Song6907ce22018-07-30 19:24:48 +00003582
Douglas Gregor77f49a42013-01-16 18:47:38 +00003583 Diag(Methods[0]->getLocStart(),
3584 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003585 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003586 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3587 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003588 << Methods[I]->getSourceRange();
3589 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003590 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003591}
3592
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003593ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003594 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3595 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003596 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003597
3598 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003599 for (const ObjCMethodList *Method = &Methods.first; Method;
3600 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003601 if (Method->getMethod() &&
3602 (Method->getMethod()->isDefined() ||
3603 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003604 return Method->getMethod();
Fangrui Song6907ce22018-07-30 19:24:48 +00003605
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003606 for (const ObjCMethodList *Method = &Methods.second; Method;
3607 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003608 if (Method->getMethod() &&
3609 (Method->getMethod()->isDefined() ||
3610 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003611 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003612 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003613}
3614
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003615static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003616HelperSelectorsForTypoCorrection(
3617 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3618 StringRef Typo, const ObjCMethodDecl * Method) {
3619 const unsigned MaxEditDistance = 1;
3620 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003621 std::string MethodName = Method->getSelector().getAsString();
Fangrui Song6907ce22018-07-30 19:24:48 +00003622
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003623 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3624 if (MinPossibleEditDistance > 0 &&
3625 Typo.size() / MinPossibleEditDistance < 1)
3626 return;
3627 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3628 if (EditDistance > MaxEditDistance)
3629 return;
3630 if (EditDistance == BestEditDistance)
3631 BestMethod.push_back(Method);
3632 else if (EditDistance < BestEditDistance) {
3633 BestMethod.clear();
3634 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003635 }
3636}
3637
Fariborz Jahanian75481672013-06-17 17:10:54 +00003638static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3639 QualType ObjectType) {
3640 if (ObjectType.isNull())
3641 return true;
3642 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3643 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003644 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3645 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003646}
3647
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003648const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003649Sema::SelectorsForTypoCorrection(Selector Sel,
3650 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003651 unsigned NumArgs = Sel.getNumArgs();
3652 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003653 bool ObjectIsId = true, ObjectIsClass = true;
3654 if (ObjectType.isNull())
3655 ObjectIsId = ObjectIsClass = false;
3656 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003657 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003658 else if (const ObjCObjectPointerType *ObjCPtr =
3659 ObjectType->getAsObjCInterfacePointerType()) {
3660 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3661 ObjectIsId = ObjectIsClass = false;
3662 }
3663 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3664 ObjectIsClass = false;
3665 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3666 ObjectIsId = false;
3667 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003668 return nullptr;
3669
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003670 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3671 e = MethodPool.end(); b != e; b++) {
3672 // instance methods
3673 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003674 if (M->getMethod() &&
3675 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3676 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003677 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003678 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003679 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003680 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3681 ObjectType))
3682 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003683 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003684 // class methods
3685 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003686 if (M->getMethod() &&
3687 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3688 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003689 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003690 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003691 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003692 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3693 ObjectType))
3694 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003695 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003696 }
Fangrui Song6907ce22018-07-30 19:24:48 +00003697
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003698 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3699 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3700 HelperSelectorsForTypoCorrection(SelectedMethods,
3701 Sel.getAsString(), Methods[i]);
3702 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003703 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003704}
3705
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003706/// DiagnoseDuplicateIvars -
Fangrui Song6907ce22018-07-30 19:24:48 +00003707/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003708/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003709/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003710/// class's \@implementation is seen.
Fangrui Song6907ce22018-07-30 19:24:48 +00003711void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003712 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003713 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003714 if (Ivar->isInvalidDecl())
3715 continue;
3716 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3717 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3718 if (prevIvar) {
3719 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3720 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3721 Ivar->setInvalidDecl();
3722 }
3723 }
3724 }
3725}
3726
John McCallb61e14e2015-10-27 04:54:50 +00003727/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3728static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3729 if (S.getLangOpts().ObjCWeak) return;
3730
3731 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3732 ivar; ivar = ivar->getNextIvar()) {
3733 if (ivar->isInvalidDecl()) continue;
3734 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3735 if (S.getLangOpts().ObjCWeakRuntime) {
3736 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3737 } else {
3738 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3739 }
3740 }
3741 }
3742}
3743
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003744/// Diagnose attempts to use flexible array member with retainable object type.
3745static void DiagnoseRetainableFlexibleArrayMember(Sema &S,
3746 ObjCInterfaceDecl *ID) {
3747 if (!S.getLangOpts().ObjCAutoRefCount)
3748 return;
3749
3750 for (auto ivar = ID->all_declared_ivar_begin(); ivar;
3751 ivar = ivar->getNextIvar()) {
3752 if (ivar->isInvalidDecl())
3753 continue;
3754 QualType IvarTy = ivar->getType();
3755 if (IvarTy->isIncompleteArrayType() &&
3756 (IvarTy.getObjCLifetime() != Qualifiers::OCL_ExplicitNone) &&
3757 IvarTy->isObjCLifetimeType()) {
3758 S.Diag(ivar->getLocation(), diag::err_flexible_array_arc_retainable);
3759 ivar->setInvalidDecl();
3760 }
3761 }
3762}
3763
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003764Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3765 switch (CurContext->getDeclKind()) {
3766 case Decl::ObjCInterface:
3767 return Sema::OCK_Interface;
3768 case Decl::ObjCProtocol:
3769 return Sema::OCK_Protocol;
3770 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003771 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003772 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003773 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003774 case Decl::ObjCImplementation:
3775 return Sema::OCK_Implementation;
3776 case Decl::ObjCCategoryImpl:
3777 return Sema::OCK_CategoryImplementation;
3778
3779 default:
3780 return Sema::OCK_None;
3781 }
3782}
3783
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00003784static bool IsVariableSizedType(QualType T) {
3785 if (T->isIncompleteArrayType())
3786 return true;
3787 const auto *RecordTy = T->getAs<RecordType>();
3788 return (RecordTy && RecordTy->getDecl()->hasFlexibleArrayMember());
3789}
3790
3791static void DiagnoseVariableSizedIvars(Sema &S, ObjCContainerDecl *OCD) {
3792 ObjCInterfaceDecl *IntfDecl = nullptr;
3793 ObjCInterfaceDecl::ivar_range Ivars = llvm::make_range(
3794 ObjCInterfaceDecl::ivar_iterator(), ObjCInterfaceDecl::ivar_iterator());
3795 if ((IntfDecl = dyn_cast<ObjCInterfaceDecl>(OCD))) {
3796 Ivars = IntfDecl->ivars();
3797 } else if (auto *ImplDecl = dyn_cast<ObjCImplementationDecl>(OCD)) {
3798 IntfDecl = ImplDecl->getClassInterface();
3799 Ivars = ImplDecl->ivars();
3800 } else if (auto *CategoryDecl = dyn_cast<ObjCCategoryDecl>(OCD)) {
3801 if (CategoryDecl->IsClassExtension()) {
3802 IntfDecl = CategoryDecl->getClassInterface();
3803 Ivars = CategoryDecl->ivars();
3804 }
3805 }
3806
3807 // Check if variable sized ivar is in interface and visible to subclasses.
3808 if (!isa<ObjCInterfaceDecl>(OCD)) {
3809 for (auto ivar : Ivars) {
3810 if (!ivar->isInvalidDecl() && IsVariableSizedType(ivar->getType())) {
3811 S.Diag(ivar->getLocation(), diag::warn_variable_sized_ivar_visibility)
3812 << ivar->getDeclName() << ivar->getType();
3813 }
3814 }
3815 }
3816
3817 // Subsequent checks require interface decl.
3818 if (!IntfDecl)
3819 return;
3820
3821 // Check if variable sized ivar is followed by another ivar.
3822 for (ObjCIvarDecl *ivar = IntfDecl->all_declared_ivar_begin(); ivar;
3823 ivar = ivar->getNextIvar()) {
3824 if (ivar->isInvalidDecl() || !ivar->getNextIvar())
3825 continue;
3826 QualType IvarTy = ivar->getType();
3827 bool IsInvalidIvar = false;
3828 if (IvarTy->isIncompleteArrayType()) {
3829 S.Diag(ivar->getLocation(), diag::err_flexible_array_not_at_end)
3830 << ivar->getDeclName() << IvarTy
3831 << TTK_Class; // Use "class" for Obj-C.
3832 IsInvalidIvar = true;
3833 } else if (const RecordType *RecordTy = IvarTy->getAs<RecordType>()) {
3834 if (RecordTy->getDecl()->hasFlexibleArrayMember()) {
3835 S.Diag(ivar->getLocation(),
3836 diag::err_objc_variable_sized_type_not_at_end)
3837 << ivar->getDeclName() << IvarTy;
3838 IsInvalidIvar = true;
3839 }
3840 }
3841 if (IsInvalidIvar) {
3842 S.Diag(ivar->getNextIvar()->getLocation(),
3843 diag::note_next_ivar_declaration)
3844 << ivar->getNextIvar()->getSynthesize();
3845 ivar->setInvalidDecl();
3846 }
3847 }
3848
3849 // Check if ObjC container adds ivars after variable sized ivar in superclass.
3850 // Perform the check only if OCD is the first container to declare ivars to
3851 // avoid multiple warnings for the same ivar.
3852 ObjCIvarDecl *FirstIvar =
3853 (Ivars.begin() == Ivars.end()) ? nullptr : *Ivars.begin();
3854 if (FirstIvar && (FirstIvar == IntfDecl->all_declared_ivar_begin())) {
3855 const ObjCInterfaceDecl *SuperClass = IntfDecl->getSuperClass();
3856 while (SuperClass && SuperClass->ivar_empty())
3857 SuperClass = SuperClass->getSuperClass();
3858 if (SuperClass) {
3859 auto IvarIter = SuperClass->ivar_begin();
3860 std::advance(IvarIter, SuperClass->ivar_size() - 1);
3861 const ObjCIvarDecl *LastIvar = *IvarIter;
3862 if (IsVariableSizedType(LastIvar->getType())) {
3863 S.Diag(FirstIvar->getLocation(),
3864 diag::warn_superclass_variable_sized_type_not_at_end)
3865 << FirstIvar->getDeclName() << LastIvar->getDeclName()
3866 << LastIvar->getType() << SuperClass->getDeclName();
3867 S.Diag(LastIvar->getLocation(), diag::note_entity_declared_at)
3868 << LastIvar->getDeclName();
3869 }
3870 }
3871 }
3872}
3873
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003874// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003875Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003876 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003877 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003878 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003879
3880 assert(AtEnd.isValid() && "Invalid location for '@end'");
3881
George Burgess IV00f70bd2018-03-01 05:43:23 +00003882 auto *OCD = cast<ObjCContainerDecl>(CurContext);
3883 Decl *ClassDecl = OCD;
3884
Mike Stump11289f42009-09-09 15:08:12 +00003885 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003886 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3887 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003888 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003889
Steve Naroff35c62ae2009-01-08 17:28:14 +00003890 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3891 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3892 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3893
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003894 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003895 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003896 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003897
3898 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003899 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003900 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003901 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003902 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003903 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003904 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003905 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003906 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003907 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003908 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003909 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003910 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003911 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003912 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003913 if (!Context.getSourceManager().isInSystemHeader(
3914 Method->getLocation()))
3915 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3916 << Method->getDeclName();
3917 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3918 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003919 InsMap[Method->getSelector()] = Method;
3920 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003921 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003922 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003923 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003924 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003925 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003926 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003927 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003928 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003929 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003930 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003931 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003932 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003933 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003934 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003935 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003936 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003937 if (!Context.getSourceManager().isInSystemHeader(
3938 Method->getLocation()))
3939 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3940 << Method->getDeclName();
3941 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3942 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003943 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003944 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003945 }
3946 }
3947 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003948 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3949 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003950 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003951 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003952 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003953 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003954
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003955 if (C->IsClassExtension()) {
3956 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3957 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003958 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003959 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003960 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003961 if (CDecl->getIdentifier())
3962 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3963 // user-defined setter/getter. It also synthesizes setter/getter methods
3964 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003965 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003966 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003967 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003968 }
3969 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003970 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003971 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003972 // Any property declared in a class extension might have user
3973 // declared setter or getter in current class extension or one
3974 // of the other class extensions. Mark them as synthesized as
3975 // property will be synthesized when property with same name is
3976 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003977 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003978 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003979 // Skip over properties declared @dynamic
3980 if (const ObjCPropertyImplDecl *PIDecl
Manman Ren5b786402016-01-28 18:49:28 +00003981 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3982 Property->getQueryKind()))
Fangrui Song6907ce22018-07-30 19:24:48 +00003983 if (PIDecl->getPropertyImplementation()
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003984 == ObjCPropertyImplDecl::Dynamic)
3985 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003986
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003987 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003988 if (ObjCMethodDecl *GetterMethod
3989 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003990 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003991 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003992 if (ObjCMethodDecl *SetterMethod
3993 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003994 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003995 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003996 }
3997 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003998 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003999 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00004000 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004001 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00004002 if (IDecl->hasDesignatedInitializers())
4003 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00004004 DiagnoseWeakIvars(*this, IC);
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004005 DiagnoseRetainableFlexibleArrayMember(*this, IDecl);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00004006
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004007 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00004008 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004009 // This class has no superclass, so check that it has been marked with
4010 // __attribute((objc_root_class)).
4011 if (!HasRootClassAttr) {
4012 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00004013 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004014 Diag(DeclLoc, diag::warn_objc_root_class_missing)
4015 << IDecl->getIdentifier();
4016 // See if NSObject is in the current scope, and if it is, suggest
4017 // adding " : NSObject " to the class declaration.
4018 NamedDecl *IF = LookupSingleName(TUScope,
4019 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
4020 DeclLoc, LookupOrdinaryName);
4021 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
4022 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
4023 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
4024 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
4025 } else {
4026 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
4027 }
4028 }
4029 } else if (HasRootClassAttr) {
4030 // Complain that only root classes may have this attribute.
4031 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
4032 }
4033
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004034 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
4035 // An interface can subclass another interface with a
4036 // objc_subclassing_restricted attribute when it has that attribute as
4037 // well (because of interfaces imported from Swift). Therefore we have
4038 // to check if we can subclass in the implementation as well.
4039 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4040 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4041 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
4042 Diag(Super->getLocation(), diag::note_class_declared);
4043 }
4044 }
4045
John McCall5fb5df92012-06-20 06:18:46 +00004046 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00004047 while (IDecl->getSuperClass()) {
4048 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
4049 IDecl = IDecl->getSuperClass();
4050 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00004051 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00004052 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004053 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00004054 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00004055 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00004056 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004057
Chris Lattnerda463fe2007-12-12 07:09:47 +00004058 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00004059 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00004060 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00004061 if (ObjCCategoryDecl *Cat
4062 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
4063 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004064 }
4065 }
Alex Lorenza8c44ba2016-10-28 10:25:10 +00004066 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
4067 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
4068 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
4069 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
4070 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
4071 Diag(Super->getLocation(), diag::note_class_declared);
4072 }
4073 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00004074 }
Volodymyr Sapsai30680e92017-10-23 22:01:41 +00004075 DiagnoseVariableSizedIvars(*this, OCD);
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004076 if (isInterfaceDeclKind) {
4077 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004078 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004079 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004080 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4081 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00004082 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00004083 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00004084 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00004085 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00004086 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00004087 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004088
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00004089 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00004090 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00004091 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
4092 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00004093 Consumer.HandleTopLevelDeclInObjCContainer(DG);
4094 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004095
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00004096 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00004097 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004098}
4099
Chris Lattnerda463fe2007-12-12 07:09:47 +00004100/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
4101/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00004102static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004103CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00004104 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004105}
4106
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004107/// Check whether the declared result type of the given Objective-C
Douglas Gregor33823722011-06-11 01:09:30 +00004108/// method declaration is compatible with the method's class.
4109///
Fangrui Song6907ce22018-07-30 19:24:48 +00004110static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00004111CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
4112 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00004113 QualType ResultType = Method->getReturnType();
4114
Fangrui Song6907ce22018-07-30 19:24:48 +00004115 // If an Objective-C method inherits its related result type, then its
Douglas Gregor33823722011-06-11 01:09:30 +00004116 // declared result type must be compatible with its own class type. The
4117 // declared result type is compatible if:
4118 if (const ObjCObjectPointerType *ResultObjectType
4119 = ResultType->getAs<ObjCObjectPointerType>()) {
4120 // - it is id or qualified id, or
4121 if (ResultObjectType->isObjCIdType() ||
4122 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004123 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004124
Douglas Gregor33823722011-06-11 01:09:30 +00004125 if (CurrentClass) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004126 if (ObjCInterfaceDecl *ResultClass
Douglas Gregor33823722011-06-11 01:09:30 +00004127 = ResultObjectType->getInterfaceDecl()) {
4128 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00004129 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004130 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004131
Douglas Gregor33823722011-06-11 01:09:30 +00004132 // - it is a superclass of the method's class type
4133 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004134 return Sema::RTC_Compatible;
Fangrui Song6907ce22018-07-30 19:24:48 +00004135 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00004136 } else {
4137 // Any Objective-C pointer type might be acceptable for a protocol
4138 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004139 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00004140 }
4141 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004142
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004143 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004144}
4145
John McCalld2930c22011-07-22 02:45:48 +00004146namespace {
4147/// A helper class for searching for methods which a particular method
4148/// overrides.
4149class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004150public:
John McCalld2930c22011-07-22 02:45:48 +00004151 Sema &S;
4152 ObjCMethodDecl *Method;
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004153 llvm::SmallSetVector<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00004154 bool Recursive;
4155
4156public:
4157 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
4158 Selector selector = method->getSelector();
4159
4160 // Bypass this search if we've never seen an instance/class method
4161 // with this selector before.
4162 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4163 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00004164 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00004165 S.ReadMethodPool(selector);
Fangrui Song6907ce22018-07-30 19:24:48 +00004166
Douglas Gregore1716012012-01-25 00:49:42 +00004167 it = S.MethodPool.find(selector);
4168 if (it == S.MethodPool.end())
4169 return;
John McCalld2930c22011-07-22 02:45:48 +00004170 }
4171 ObjCMethodList &list =
4172 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00004173 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00004174
4175 ObjCContainerDecl *container
4176 = cast<ObjCContainerDecl>(method->getDeclContext());
4177
4178 // Prevent the search from reaching this container again. This is
4179 // important with categories, which override methods from the
4180 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004181 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4182 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004183 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4184 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004185 } else {
4186 searchFromContainer(container);
4187 }
Douglas Gregor33823722011-06-11 01:09:30 +00004188 }
John McCalld2930c22011-07-22 02:45:48 +00004189
Akira Hatanaka4c687f32018-02-06 23:44:40 +00004190 typedef decltype(Overridden)::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00004191 iterator begin() const { return Overridden.begin(); }
4192 iterator end() const { return Overridden.end(); }
4193
4194private:
4195 void searchFromContainer(ObjCContainerDecl *container) {
4196 if (container->isInvalidDecl()) return;
4197
4198 switch (container->getDeclKind()) {
4199#define OBJCCONTAINER(type, base) \
4200 case Decl::type: \
4201 searchFrom(cast<type##Decl>(container)); \
4202 break;
4203#define ABSTRACT_DECL(expansion)
4204#define DECL(type, base) \
4205 case Decl::type:
4206#include "clang/AST/DeclNodes.inc"
4207 llvm_unreachable("not an ObjC container!");
4208 }
4209 }
4210
4211 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004212 if (!protocol->hasDefinition())
4213 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004214
John McCalld2930c22011-07-22 02:45:48 +00004215 // A method in a protocol declaration overrides declarations from
4216 // referenced ("parent") protocols.
4217 search(protocol->getReferencedProtocols());
4218 }
4219
4220 void searchFrom(ObjCCategoryDecl *category) {
4221 // A method in a category declaration overrides declarations from
4222 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004223 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00004224 search(category->getReferencedProtocols());
4225 }
4226
4227 void searchFrom(ObjCCategoryImplDecl *impl) {
4228 // A method in a category definition that has a category
4229 // declaration overrides declarations from the category
4230 // declaration.
4231 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4232 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004233 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4234 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004235
4236 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004237 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4238 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004239 }
4240 }
4241
4242 void searchFrom(ObjCInterfaceDecl *iface) {
4243 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004244 if (!iface->hasDefinition())
4245 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00004246
John McCalld2930c22011-07-22 02:45:48 +00004247 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00004248 for (auto *Cat : iface->known_categories())
4249 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00004250
4251 // - the super class, and
4252 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4253 search(super);
4254
4255 // - any referenced protocols.
4256 search(iface->getReferencedProtocols());
4257 }
4258
4259 void searchFrom(ObjCImplementationDecl *impl) {
4260 // A method in a class implementation overrides declarations from
4261 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004262 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4263 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004264 }
4265
John McCalld2930c22011-07-22 02:45:48 +00004266 void search(const ObjCProtocolList &protocols) {
4267 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4268 i != e; ++i)
4269 search(*i);
4270 }
4271
4272 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004273 // Check for a method in this container which matches this selector.
4274 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00004275 Method->isInstanceMethod(),
4276 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00004277
4278 // If we find one, record it and bail out.
4279 if (meth) {
4280 Overridden.insert(meth);
4281 return;
4282 }
4283
4284 // Otherwise, search for methods that a hypothetical method here
4285 // would have overridden.
4286
4287 // Note that we're now in a recursive case.
4288 Recursive = true;
4289
4290 searchFromContainer(container);
4291 }
4292};
Hans Wennborgdcfba332015-10-06 23:40:43 +00004293} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00004294
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004295void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4296 ObjCInterfaceDecl *CurrentClass,
4297 ResultTypeCompatibilityKind RTC) {
4298 // Search for overridden methods and merge information down from them.
4299 OverrideSearch overrides(*this, ObjCMethod);
4300 // Keep track if the method overrides any method in the class's base classes,
4301 // its protocols, or its categories' protocols; we will keep that info
4302 // in the ObjCMethodDecl.
4303 // For this info, a method in an implementation is not considered as
4304 // overriding the same method in the interface or its categories.
4305 bool hasOverriddenMethodsInBaseOrProtocol = false;
4306 for (OverrideSearch::iterator
4307 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4308 ObjCMethodDecl *overridden = *i;
4309
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004310 if (!hasOverriddenMethodsInBaseOrProtocol) {
4311 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4312 CurrentClass != overridden->getClassInterface() ||
4313 overridden->isOverriding()) {
4314 hasOverriddenMethodsInBaseOrProtocol = true;
4315
4316 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4317 // OverrideSearch will return as "overridden" the same method in the
4318 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4319 // check whether a category of a base class introduced a method with the
4320 // same selector, after the interface method declaration.
4321 // To avoid unnecessary lookups in the majority of cases, we use the
4322 // extra info bits in GlobalMethodPool to check whether there were any
4323 // category methods with this selector.
4324 GlobalMethodPool::iterator It =
4325 MethodPool.find(ObjCMethod->getSelector());
4326 if (It != MethodPool.end()) {
4327 ObjCMethodList &List =
4328 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4329 unsigned CategCount = List.getBits();
4330 if (CategCount > 0) {
4331 // If the method is in a category we'll do lookup if there were at
4332 // least 2 category methods recorded, otherwise only one will do.
4333 if (CategCount > 1 ||
4334 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4335 OverrideSearch overrides(*this, overridden);
4336 for (OverrideSearch::iterator
4337 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4338 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00004339 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4340 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004341 hasOverriddenMethodsInBaseOrProtocol = true;
4342 overridden->setOverriding(true);
4343 break;
4344 }
4345 }
4346 }
4347 }
4348 }
4349 }
4350 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004351
4352 // Propagate down the 'related result type' bit from overridden methods.
4353 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4354 ObjCMethod->SetRelatedResultType();
4355
4356 // Then merge the declarations.
4357 mergeObjCMethodDecls(ObjCMethod, overridden);
4358
4359 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4360 continue; // Conflicting properties are detected elsewhere.
4361
4362 // Check for overriding methods
Fangrui Song6907ce22018-07-30 19:24:48 +00004363 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004364 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4365 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4366 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
Fangrui Song6907ce22018-07-30 19:24:48 +00004367
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004368 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004369 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4370 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004371 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4372 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004373 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4374 PrevE = overridden->param_end();
4375 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004376 assert(PrevI != overridden->param_end() && "Param mismatch");
4377 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4378 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4379 // If type of argument of method in this class does not match its
4380 // respective argument type in the super class method, issue warning;
4381 if (!Context.typesAreCompatible(T1, T2)) {
4382 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4383 << T1 << T2;
4384 Diag(overridden->getLocation(), diag::note_previous_declaration);
4385 break;
4386 }
4387 }
4388 }
4389 }
4390
4391 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4392}
4393
Douglas Gregor813a0662015-06-19 18:14:38 +00004394/// Merge type nullability from for a redeclaration of the same entity,
4395/// producing the updated type of the redeclared entity.
4396static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4397 QualType type,
4398 bool usesCSKeyword,
4399 SourceLocation prevLoc,
4400 QualType prevType,
4401 bool prevUsesCSKeyword) {
4402 // Determine the nullability of both types.
4403 auto nullability = type->getNullability(S.Context);
4404 auto prevNullability = prevType->getNullability(S.Context);
4405
4406 // Easy case: both have nullability.
4407 if (nullability.hasValue() == prevNullability.hasValue()) {
4408 // Neither has nullability; continue.
4409 if (!nullability)
4410 return type;
4411
4412 // The nullabilities are equivalent; do nothing.
4413 if (*nullability == *prevNullability)
4414 return type;
4415
4416 // Complain about mismatched nullability.
4417 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004418 << DiagNullabilityKind(*nullability, usesCSKeyword)
4419 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004420 return type;
4421 }
4422
4423 // If it's the redeclaration that has nullability, don't change anything.
4424 if (nullability)
4425 return type;
4426
4427 // Otherwise, provide the result with the same nullability.
4428 return S.Context.getAttributedType(
4429 AttributedType::getNullabilityAttrKind(*prevNullability),
4430 type, type);
4431}
4432
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004433/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004434/// (or a category/extension) into the corresponding method in the
4435/// @implementation (for a class or category).
4436static void mergeInterfaceMethodToImpl(Sema &S,
4437 ObjCMethodDecl *method,
4438 ObjCMethodDecl *prevMethod) {
4439 // Merge the objc_requires_super attribute.
4440 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4441 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4442 // merge the attribute into implementation.
4443 method->addAttr(
4444 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4445 method->getLocation()));
4446 }
4447
4448 // Merge nullability of the result type.
4449 QualType newReturnType
4450 = mergeTypeNullabilityForRedecl(
4451 S, method->getReturnTypeSourceRange().getBegin(),
4452 method->getReturnType(),
4453 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4454 prevMethod->getReturnTypeSourceRange().getBegin(),
4455 prevMethod->getReturnType(),
4456 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4457 method->setReturnType(newReturnType);
4458
4459 // Handle each of the parameters.
4460 unsigned numParams = method->param_size();
4461 unsigned numPrevParams = prevMethod->param_size();
4462 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4463 ParmVarDecl *param = method->param_begin()[i];
4464 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4465
4466 // Merge nullability.
4467 QualType newParamType
4468 = mergeTypeNullabilityForRedecl(
4469 S, param->getLocation(), param->getType(),
4470 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4471 prevParam->getLocation(), prevParam->getType(),
4472 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4473 param->setType(newParamType);
4474 }
4475}
4476
Alex Lorenza8a372d2017-04-27 10:43:48 +00004477/// Verify that the method parameters/return value have types that are supported
4478/// by the x86 target.
4479static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4480 const ObjCMethodDecl *Method) {
4481 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4482 llvm::Triple::x86 &&
4483 "x86-specific check invoked for a different target");
4484 SourceLocation Loc;
4485 QualType T;
4486 for (const ParmVarDecl *P : Method->parameters()) {
4487 if (P->getType()->isVectorType()) {
4488 Loc = P->getLocStart();
4489 T = P->getType();
4490 break;
4491 }
4492 }
4493 if (Loc.isInvalid()) {
4494 if (Method->getReturnType()->isVectorType()) {
4495 Loc = Method->getReturnTypeSourceRange().getBegin();
4496 T = Method->getReturnType();
4497 } else
4498 return;
4499 }
4500
4501 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4502 // iOS < 9 and macOS < 10.11.
4503 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4504 VersionTuple AcceptedInVersion;
4505 if (Triple.getOS() == llvm::Triple::IOS)
4506 AcceptedInVersion = VersionTuple(/*Major=*/9);
4507 else if (Triple.isMacOSX())
4508 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4509 else
4510 return;
Alex Lorenza8a372d2017-04-27 10:43:48 +00004511 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
Alex Lorenz92824832017-05-05 16:15:17 +00004512 AcceptedInVersion)
Alex Lorenza8a372d2017-04-27 10:43:48 +00004513 return;
4514 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4515 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4516 : /*parameter*/ 0)
4517 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4518}
4519
John McCall48871652010-08-21 09:40:31 +00004520Decl *Sema::ActOnMethodDeclaration(
Erich Keanec480f302018-07-12 21:09:05 +00004521 Scope *S, SourceLocation MethodLoc, SourceLocation EndLoc,
4522 tok::TokenKind MethodType, ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
4523 ArrayRef<SourceLocation> SelectorLocs, Selector Sel,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004524 // optional arguments. The number of types/arguments is obtained
4525 // from the Sel.getNumArgs().
Erich Keanec480f302018-07-12 21:09:05 +00004526 ObjCArgInfo *ArgInfo, DeclaratorChunk::ParamInfo *CParamInfo,
4527 unsigned CNumArgs, // c-style args
4528 const ParsedAttributesView &AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004529 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004530 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004531 if (!CurContext->isObjCContainer()) {
Richard Smithf8812672016-12-02 22:38:31 +00004532 Diag(MethodLoc, diag::err_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004533 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004534 }
George Burgess IV00f70bd2018-03-01 05:43:23 +00004535 Decl *ClassDecl = cast<ObjCContainerDecl>(CurContext);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004536 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004537
Douglas Gregorbab8a962011-09-08 01:46:34 +00004538 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004539 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004540 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004541 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004542
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004543 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004544 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004545
Douglas Gregor813a0662015-06-19 18:14:38 +00004546 QualType bareResultType = resultDeclType;
4547 (void)AttributedType::stripOuterNullability(bareResultType);
4548 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004549 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004550 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004551 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004552 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004553 }
Mike Stump11289f42009-09-09 15:08:12 +00004554
Alp Toker314cc812014-01-25 16:55:45 +00004555 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4556 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4557 MethodType == tok::minus, isVariadic,
4558 /*isPropertyAccessor=*/false,
4559 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4560 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4561 : ObjCMethodDecl::Required,
4562 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004563
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004564 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004565
Chris Lattner23b0faf2009-04-11 19:42:43 +00004566 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004567 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004568 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004569
David Blaikie7d170102013-05-15 07:37:26 +00004570 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004571 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004572 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004573 } else {
John McCall856bbea2009-10-23 21:48:59 +00004574 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004575 }
Mike Stump11289f42009-09-09 15:08:12 +00004576
Fangrui Song6907ce22018-07-30 19:24:48 +00004577 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00004578 LookupOrdinaryName, forRedeclarationInCurContext());
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004579 LookupName(R, S);
4580 if (R.isSingleResult()) {
4581 NamedDecl *PrevDecl = R.getFoundDecl();
4582 if (S->isDeclScope(PrevDecl)) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004583 Diag(ArgInfo[i].NameLoc,
4584 (MethodDefinition ? diag::warn_method_param_redefinition
4585 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004586 << ArgInfo[i].Name;
Fangrui Song6907ce22018-07-30 19:24:48 +00004587 Diag(PrevDecl->getLocation(),
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004588 diag::note_previous_declaration);
4589 }
4590 }
4591
Abramo Bagnaradff19302011-03-08 08:55:46 +00004592 SourceLocation StartLoc = DI
4593 ? DI->getTypeLoc().getBeginLoc()
4594 : ArgInfo[i].NameLoc;
4595
John McCalld44f4d72011-04-23 02:46:06 +00004596 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4597 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004598 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004599
John McCall82490832011-05-02 00:30:12 +00004600 Param->setObjCMethodScopeInfo(i);
4601
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004602 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004603 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004604
Chris Lattner9713a1c2009-04-11 19:34:56 +00004605 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004606 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004607 AddPragmaAttributes(TUScope, Param);
Mike Stump11289f42009-09-09 15:08:12 +00004608
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004609 if (Param->hasAttr<BlocksAttr>()) {
4610 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4611 Param->setInvalidDecl();
4612 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004613 S->AddDecl(Param);
4614 IdResolver.AddDecl(Param);
4615
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004616 Params.push_back(Param);
4617 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004618
Fariborz Jahanian60462092010-04-08 00:30:06 +00004619 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004620 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004621 QualType ArgType = Param->getType();
4622 if (ArgType.isNull())
4623 ArgType = Context.getObjCIdType();
4624 else
4625 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004626 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004627
Fariborz Jahanian60462092010-04-08 00:30:06 +00004628 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004629 Params.push_back(Param);
4630 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004631
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004632 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004633 ObjCMethod->setObjCDeclQualifier(
4634 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004635
Erich Keanec480f302018-07-12 21:09:05 +00004636 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004637 AddPragmaAttributes(TUScope, ObjCMethod);
Mike Stump11289f42009-09-09 15:08:12 +00004638
Douglas Gregor87e92752010-12-21 17:34:17 +00004639 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004640 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004641 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004642 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004643 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4644 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004645 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004646 PrevMethod = ImpDecl->getClassMethod(Sel);
4647 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004648 }
Douglas Gregor33823722011-06-11 01:09:30 +00004649
Douglas Gregor813a0662015-06-19 18:14:38 +00004650 // Merge information from the @interface declaration into the
4651 // @implementation.
4652 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4653 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4654 ObjCMethod->isInstanceMethod())) {
4655 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4656
4657 // Warn about defining -dealloc in a category.
4658 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4659 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4660 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4661 << ObjCMethod->getDeclName();
4662 }
4663 }
Akira Hatanakaa6b5e002018-07-28 04:06:13 +00004664
4665 // Warn if a method declared in a protocol to which a category or
4666 // extension conforms is non-escaping and the implementation's method is
4667 // escaping.
4668 for (auto *C : IDecl->visible_categories())
4669 for (auto &P : C->protocols())
4670 if (auto *IMD = P->lookupMethod(ObjCMethod->getSelector(),
4671 ObjCMethod->isInstanceMethod())) {
4672 assert(ObjCMethod->parameters().size() ==
4673 IMD->parameters().size() &&
4674 "Methods have different number of parameters");
4675 auto OI = IMD->param_begin(), OE = IMD->param_end();
4676 auto NI = ObjCMethod->param_begin();
4677 for (; OI != OE; ++OI, ++NI)
4678 diagnoseNoescape(*NI, *OI, C, P, *this);
4679 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004680 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004681 } else {
4682 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004683 }
John McCalld2930c22011-07-22 02:45:48 +00004684
Chris Lattnerda463fe2007-12-12 07:09:47 +00004685 if (PrevMethod) {
4686 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004687 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004688 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004689 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004690 ObjCMethod->setInvalidDecl();
4691 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004692 }
John McCall28a6aea2009-11-04 02:18:39 +00004693
Douglas Gregor33823722011-06-11 01:09:30 +00004694 // If this Objective-C method does not have a related result type, but we
4695 // are allowed to infer related result types, try to do so based on the
4696 // method family.
4697 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4698 if (!CurrentClass) {
4699 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4700 CurrentClass = Cat->getClassInterface();
4701 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4702 CurrentClass = Impl->getClassInterface();
4703 else if (ObjCCategoryImplDecl *CatImpl
4704 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4705 CurrentClass = CatImpl->getClassInterface();
4706 }
John McCalld2930c22011-07-22 02:45:48 +00004707
Douglas Gregorbab8a962011-09-08 01:46:34 +00004708 ResultTypeCompatibilityKind RTC
4709 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004710
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004711 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004712
John McCall31168b02011-06-15 23:02:42 +00004713 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004714 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004715 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004716
Douglas Gregorbab8a962011-09-08 01:46:34 +00004717 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004718 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004719 !ObjCMethod->hasRelatedResultType() &&
4720 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004721 bool InferRelatedResultType = false;
4722 switch (ObjCMethod->getMethodFamily()) {
4723 case OMF_None:
4724 case OMF_copy:
4725 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004726 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004727 case OMF_mutableCopy:
4728 case OMF_release:
4729 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004730 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004731 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004732 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004733
Douglas Gregor33823722011-06-11 01:09:30 +00004734 case OMF_alloc:
4735 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004736 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004737 break;
Fangrui Song6907ce22018-07-30 19:24:48 +00004738
Douglas Gregor33823722011-06-11 01:09:30 +00004739 case OMF_init:
4740 case OMF_autorelease:
4741 case OMF_retain:
4742 case OMF_self:
4743 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4744 break;
4745 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004746
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004747 if (InferRelatedResultType &&
4748 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004749 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004750 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004751
Alex Lorenza8a372d2017-04-27 10:43:48 +00004752 if (MethodDefinition &&
4753 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4754 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4755
Steven Wu3bb4aa52018-04-16 23:34:18 +00004756 // + load method cannot have availability attributes. It get called on
4757 // startup, so it has to have the availability of the deployment target.
4758 if (const auto *attr = ObjCMethod->getAttr<AvailabilityAttr>()) {
4759 if (ObjCMethod->isClassMethod() &&
4760 ObjCMethod->getSelector().getAsString() == "load") {
4761 Diag(attr->getLocation(), diag::warn_availability_on_static_initializer)
4762 << 0;
4763 ObjCMethod->dropAttr<AvailabilityAttr>();
4764 }
4765 }
4766
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004767 ActOnDocumentableDecl(ObjCMethod);
4768
John McCall48871652010-08-21 09:40:31 +00004769 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004770}
4771
Chris Lattner438e5012008-12-17 07:13:27 +00004772bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004773 // Following is also an error. But it is caused by a missing @end
4774 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004775 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004776 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004777
4778 // If we switched context to translation unit while we are still lexically in
4779 // an objc container, it means the parser missed emitting an error.
4780 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4781 return false;
Fangrui Song6907ce22018-07-30 19:24:48 +00004782
Anders Carlssona6b508a2008-11-04 16:57:32 +00004783 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4784 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004785
Anders Carlssona6b508a2008-11-04 16:57:32 +00004786 return true;
4787}
Chris Lattner438e5012008-12-17 07:13:27 +00004788
James Dennett634962f2012-06-14 21:40:34 +00004789/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004790/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004791void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004792 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004793 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004794 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004795 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004796 if (!Class) {
4797 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4798 return;
4799 }
John McCall5fb5df92012-06-20 06:18:46 +00004800 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004801 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4802 return;
4803 }
Mike Stump11289f42009-09-09 15:08:12 +00004804
Chris Lattner438e5012008-12-17 07:13:27 +00004805 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004806 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004807 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004808 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004809 for (unsigned i = 0; i < Ivars.size(); i++) {
George Burgess IV00f70bd2018-03-01 05:43:23 +00004810 const FieldDecl* ID = Ivars[i];
John McCall48871652010-08-21 09:40:31 +00004811 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004812 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4813 /*FIXME: StartL=*/ID->getLocation(),
4814 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004815 ID->getIdentifier(), ID->getType(),
4816 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004817 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004818 }
Mike Stump11289f42009-09-09 15:08:12 +00004819
Chris Lattner438e5012008-12-17 07:13:27 +00004820 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004821 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004822 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004823 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004824 if (getLangOpts().CPlusPlus)
George Burgess IV00f70bd2018-03-01 05:43:23 +00004825 PushOnScopeChains(FD, S);
John McCall48871652010-08-21 09:40:31 +00004826 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004827 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004828 }
4829}
4830
Adrian Prantl9fc8faf2018-05-09 01:00:01 +00004831/// Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004832VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4833 SourceLocation StartLoc,
4834 SourceLocation IdLoc,
4835 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004836 bool Invalid) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004837 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
Douglas Gregorf3564192010-04-26 17:32:49 +00004838 // duration shall not be qualified by an address-space qualifier."
4839 // Since all parameters have automatic store duration, they can not have
4840 // an address space.
Alexander Richardson6d989432017-10-15 18:48:14 +00004841 if (T.getAddressSpace() != LangAS::Default) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004842 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004843 Invalid = true;
4844 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004845
Douglas Gregorf3564192010-04-26 17:32:49 +00004846 // An @catch parameter must be an unqualified object pointer type;
4847 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4848 if (Invalid) {
4849 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004850 } else if (T->isDependentType()) {
4851 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004852 } else if (T->isObjCQualifiedIdType()) {
4853 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004854 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Saleem Abdulrasool278e1c42018-05-20 19:26:44 +00004855 } else if (T->isObjCIdType()) {
4856 // Okay: we don't know what this type will instantiate to.
4857 } else if (!T->isObjCObjectPointerType()) {
4858 Invalid = true;
4859 Diag(IdLoc, diag::err_catch_param_not_objc_type);
4860 } else if (!T->getAs<ObjCObjectPointerType>()->getInterfaceType()) {
4861 Invalid = true;
4862 Diag(IdLoc, diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004863 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004864
Abramo Bagnaradff19302011-03-08 08:55:46 +00004865 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004866 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004867 New->setExceptionVariable(true);
Fangrui Song6907ce22018-07-30 19:24:48 +00004868
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004869 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004870 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004871 Invalid = true;
4872
Douglas Gregorf3564192010-04-26 17:32:49 +00004873 if (Invalid)
4874 New->setInvalidDecl();
4875 return New;
4876}
4877
John McCall48871652010-08-21 09:40:31 +00004878Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004879 const DeclSpec &DS = D.getDeclSpec();
Fangrui Song6907ce22018-07-30 19:24:48 +00004880
Douglas Gregorf3564192010-04-26 17:32:49 +00004881 // We allow the "register" storage class on exception variables because
4882 // GCC did, but we drop it completely. Any other storage class is an error.
4883 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4884 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4885 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004886 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004887 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004888 << DeclSpec::getSpecifierName(SCS);
4889 }
Richard Smith62f19e72016-06-25 00:15:56 +00004890 if (DS.isInlineSpecified())
4891 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
Aaron Ballmanc351fba2017-12-04 20:27:34 +00004892 << getLangOpts().CPlusPlus17;
Richard Smithb4a9e862013-04-12 22:46:28 +00004893 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4894 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4895 diag::err_invalid_thread)
4896 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004897 D.getMutableDeclSpec().ClearStorageClassSpecs();
4898
Richard Smithb1402ae2013-03-18 22:52:47 +00004899 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Fangrui Song6907ce22018-07-30 19:24:48 +00004900
Douglas Gregorf3564192010-04-26 17:32:49 +00004901 // Check that there are no default arguments inside the type of this
4902 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004903 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004904 CheckExtraCXXDefaultArguments(D);
Fangrui Song6907ce22018-07-30 19:24:48 +00004905
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004906 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004907 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004908
Abramo Bagnaradff19302011-03-08 08:55:46 +00004909 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4910 D.getSourceRange().getBegin(),
4911 D.getIdentifierLoc(),
4912 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004913 D.isInvalidType());
Fangrui Song6907ce22018-07-30 19:24:48 +00004914
Douglas Gregorf3564192010-04-26 17:32:49 +00004915 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4916 if (D.getCXXScopeSpec().isSet()) {
4917 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4918 << D.getCXXScopeSpec().getRange();
4919 New->setInvalidDecl();
4920 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004921
Douglas Gregorf3564192010-04-26 17:32:49 +00004922 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004923 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004924 if (D.getIdentifier())
4925 IdResolver.AddDecl(New);
Fangrui Song6907ce22018-07-30 19:24:48 +00004926
Douglas Gregorf3564192010-04-26 17:32:49 +00004927 ProcessDeclAttributes(S, New, D);
Fangrui Song6907ce22018-07-30 19:24:48 +00004928
Douglas Gregorf3564192010-04-26 17:32:49 +00004929 if (New->hasAttr<BlocksAttr>())
4930 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004931 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004932}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004933
4934/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004935/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004936void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004937 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fangrui Song6907ce22018-07-30 19:24:48 +00004938 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004939 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004940 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004941 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004942 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004943 }
4944}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004945
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004946void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004947 // Load referenced selectors from the external source.
4948 if (ExternalSource) {
4949 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4950 ExternalSource->ReadReferencedSelectors(Sels);
4951 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4952 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4953 }
Fangrui Song6907ce22018-07-30 19:24:48 +00004954
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004955 // Warning will be issued only when selector table is
4956 // generated (which means there is at lease one implementation
4957 // in the TU). This is to match gcc's behavior.
Fangrui Song6907ce22018-07-30 19:24:48 +00004958 if (ReferencedSelectors.empty() ||
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004959 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004960 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004961 for (auto &SelectorAndLocation : ReferencedSelectors) {
4962 Selector Sel = SelectorAndLocation.first;
4963 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004964 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004965 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004966 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004967}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004968
4969ObjCIvarDecl *
4970Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4971 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004972 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004973 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004974 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4975 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004976 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004977 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4978 /*shallowCategoryLookup=*/false,
4979 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004980 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004981 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004982 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004983 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4984 // property backing ivar must belong to property's class
4985 // or be a private ivar in class's implementation.
4986 // FIXME. fix the const-ness issue.
4987 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4988 IV->getIdentifier());
4989 return IV;
4990 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004991 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004992}
4993
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004994namespace {
4995 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4996 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004997 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00004998 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004999 public:
5000 Sema &S;
5001 const ObjCMethodDecl *Method;
5002 const ObjCIvarDecl *IvarD;
5003 bool AccessedIvar;
5004 bool InvokedSelfMethod;
5005
5006 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
5007 const ObjCIvarDecl *IvarD)
5008 : S(S), Method(Method), IvarD(IvarD),
5009 AccessedIvar(false), InvokedSelfMethod(false) {
5010 assert(IvarD);
5011 }
5012
5013 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
5014 if (E->getDecl() == IvarD) {
5015 AccessedIvar = true;
5016 return false;
5017 }
5018 return true;
5019 }
5020
5021 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
5022 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
5023 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
5024 InvokedSelfMethod = true;
5025 }
5026 return true;
5027 }
5028 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00005029} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005030
5031void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
5032 const ObjCImplementationDecl *ImplD) {
5033 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005034 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005035
Aaron Ballmanf26acce2014-03-13 19:50:17 +00005036 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005037 unsigned DIAG = diag::warn_unused_property_backing_ivar;
5038 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00005039 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005040 continue;
5041
5042 const ObjCPropertyDecl *PDecl;
5043 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
5044 if (!IV)
5045 continue;
5046
5047 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
5048 Checker.TraverseStmt(CurMethod->getBody());
5049 if (Checker.AccessedIvar)
5050 continue;
5051
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005052 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00005053 // implementation makes a self call. This is to prevent false positive in
5054 // cases where the ivar is accessed by another method that the accessor
5055 // delegates to.
5056 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00005057 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00005058 Diag(PDecl->getLocation(), diag::note_property_declare);
5059 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00005060 }
5061}