blob: 5ab9d80c00b0a712964d46bc16fc0b07f0e041bb [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
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000112void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
Douglas Gregor66a8ca02013-01-15 22:43:08 +0000113 const ObjCMethodDecl *Overridden) {
Douglas Gregor33823722011-06-11 01:09:30 +0000114 if (Overridden->hasRelatedResultType() &&
115 !NewMethod->hasRelatedResultType()) {
116 // This can only happen when the method follows a naming convention that
117 // implies a related result type, and the original (overridden) method has
118 // a suitable return type, but the new (overriding) method does not have
119 // a suitable return type.
Alp Toker314cc812014-01-25 16:55:45 +0000120 QualType ResultType = NewMethod->getReturnType();
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000121 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
Douglas Gregor33823722011-06-11 01:09:30 +0000122
123 // Figure out which class this method is part of, if any.
124 ObjCInterfaceDecl *CurrentClass
125 = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
126 if (!CurrentClass) {
127 DeclContext *DC = NewMethod->getDeclContext();
128 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
129 CurrentClass = Cat->getClassInterface();
130 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
131 CurrentClass = Impl->getClassInterface();
132 else if (ObjCCategoryImplDecl *CatImpl
133 = dyn_cast<ObjCCategoryImplDecl>(DC))
134 CurrentClass = CatImpl->getClassInterface();
135 }
136
137 if (CurrentClass) {
138 Diag(NewMethod->getLocation(),
139 diag::warn_related_result_type_compatibility_class)
140 << Context.getObjCInterfaceType(CurrentClass)
141 << ResultType
142 << ResultTypeRange;
143 } else {
144 Diag(NewMethod->getLocation(),
145 diag::warn_related_result_type_compatibility_protocol)
146 << ResultType
147 << ResultTypeRange;
148 }
149
Douglas Gregorbab8a962011-09-08 01:46:34 +0000150 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
151 Diag(Overridden->getLocation(),
John McCall5ec7e7d2013-03-19 07:04:25 +0000152 diag::note_related_result_type_family)
153 << /*overridden method*/ 0
Douglas Gregorbab8a962011-09-08 01:46:34 +0000154 << Family;
155 else
156 Diag(Overridden->getLocation(),
157 diag::note_related_result_type_overridden);
Douglas Gregor33823722011-06-11 01:09:30 +0000158 }
David Blaikiebbafb8a2012-03-11 07:00:24 +0000159 if (getLangOpts().ObjCAutoRefCount) {
Akira Hatanaka7d85b8f2017-09-20 05:39:18 +0000160 Diags.setSeverity(diag::warn_nsreturns_retained_attribute_mismatch,
161 diag::Severity::Error, SourceLocation());
162 Diags.setSeverity(diag::warn_nsconsumed_attribute_mismatch,
163 diag::Severity::Error, SourceLocation());
164 }
165
166 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
167 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
168 Diag(NewMethod->getLocation(),
169 diag::warn_nsreturns_retained_attribute_mismatch) << 1;
170 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
171 }
172 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
173 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
174 Diag(NewMethod->getLocation(),
175 diag::warn_nsreturns_retained_attribute_mismatch) << 0;
176 Diag(Overridden->getLocation(), diag::note_previous_decl) << "method";
177 }
178
179 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
180 oe = Overridden->param_end();
181 for (ObjCMethodDecl::param_iterator ni = NewMethod->param_begin(),
182 ne = NewMethod->param_end();
183 ni != ne && oi != oe; ++ni, ++oi) {
184 const ParmVarDecl *oldDecl = (*oi);
185 ParmVarDecl *newDecl = (*ni);
186 if (newDecl->hasAttr<NSConsumedAttr>() !=
187 oldDecl->hasAttr<NSConsumedAttr>()) {
188 Diag(newDecl->getLocation(), diag::warn_nsconsumed_attribute_mismatch);
189 Diag(oldDecl->getLocation(), diag::note_previous_decl) << "parameter";
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000190 }
Akira Hatanaka98a49332017-09-22 00:41:05 +0000191
192 // A parameter of the overriding method should be annotated with noescape
193 // if the corresponding parameter of the overridden method is annotated.
194 if (oldDecl->hasAttr<NoEscapeAttr>() && !newDecl->hasAttr<NoEscapeAttr>()) {
195 Diag(newDecl->getLocation(),
196 diag::warn_overriding_method_missing_noescape);
197 Diag(oldDecl->getLocation(), diag::note_overridden_marked_noescape);
198 }
Fariborz Jahanianac8dbf02011-09-27 22:35:36 +0000199 }
Douglas Gregor33823722011-06-11 01:09:30 +0000200}
201
John McCall31168b02011-06-15 23:02:42 +0000202/// \brief Check a method declaration for compatibility with the Objective-C
203/// ARC conventions.
John McCalle48f3892013-04-04 01:38:37 +0000204bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
John McCall31168b02011-06-15 23:02:42 +0000205 ObjCMethodFamily family = method->getMethodFamily();
206 switch (family) {
207 case OMF_None:
Nico Weber1fb82662011-08-28 22:35:17 +0000208 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000209 case OMF_retain:
210 case OMF_release:
211 case OMF_autorelease:
212 case OMF_retainCount:
213 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000214 case OMF_initialize:
John McCalld2930c22011-07-22 02:45:48 +0000215 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000216 return false;
217
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000218 case OMF_dealloc:
Alp Toker314cc812014-01-25 16:55:45 +0000219 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
Aaron Ballman41b10ac2014-08-01 13:20:09 +0000220 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000221 if (ResultTypeRange.isInvalid())
Richard Smithf8812672016-12-02 22:38:31 +0000222 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000223 << method->getReturnType()
224 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000225 else
Richard Smithf8812672016-12-02 22:38:31 +0000226 Diag(method->getLocation(), diag::err_dealloc_bad_result_type)
Alp Toker314cc812014-01-25 16:55:45 +0000227 << method->getReturnType()
228 << FixItHint::CreateReplacement(ResultTypeRange, "void");
Fariborz Jahanianb7f03c12012-07-30 20:52:48 +0000229 return true;
230 }
231 return false;
232
John McCall31168b02011-06-15 23:02:42 +0000233 case OMF_init:
234 // If the method doesn't obey the init rules, don't bother annotating it.
John McCalle48f3892013-04-04 01:38:37 +0000235 if (checkInitMethod(method, QualType()))
John McCall31168b02011-06-15 23:02:42 +0000236 return true;
237
Aaron Ballman36a53502014-01-16 13:03:14 +0000238 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000239
240 // Don't add a second copy of this attribute, but otherwise don't
241 // let it be suppressed.
242 if (method->hasAttr<NSReturnsRetainedAttr>())
243 return false;
244 break;
245
246 case OMF_alloc:
247 case OMF_copy:
248 case OMF_mutableCopy:
249 case OMF_new:
250 if (method->hasAttr<NSReturnsRetainedAttr>() ||
251 method->hasAttr<NSReturnsNotRetainedAttr>() ||
252 method->hasAttr<NSReturnsAutoreleasedAttr>())
253 return false;
254 break;
255 }
256
Aaron Ballman36a53502014-01-16 13:03:14 +0000257 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
John McCall31168b02011-06-15 23:02:42 +0000258 return false;
259}
260
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000261static void DiagnoseObjCImplementedDeprecations(Sema &S, const NamedDecl *ND,
262 SourceLocation ImplLoc) {
263 if (!ND)
264 return;
265 bool IsCategory = false;
Alex Lorenze1088dc2017-07-13 16:37:11 +0000266 AvailabilityResult Availability = ND->getAvailability();
267 if (Availability != AR_Deprecated) {
Eric Christopher7aba9782017-07-14 01:42:57 +0000268 if (isa<ObjCMethodDecl>(ND)) {
Alex Lorenze1088dc2017-07-13 16:37:11 +0000269 if (Availability != AR_Unavailable)
270 return;
271 // Warn about implementing unavailable methods.
272 S.Diag(ImplLoc, diag::warn_unavailable_def);
273 S.Diag(ND->getLocation(), diag::note_method_declared_at)
274 << ND->getDeclName();
275 return;
276 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000277 if (const auto *CD = dyn_cast<ObjCCategoryDecl>(ND)) {
278 if (!CD->getClassInterface()->isDeprecated())
279 return;
280 ND = CD->getClassInterface();
281 IsCategory = true;
282 } else
283 return;
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000284 }
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000285 S.Diag(ImplLoc, diag::warn_deprecated_def)
286 << (isa<ObjCMethodDecl>(ND)
287 ? /*Method*/ 0
288 : isa<ObjCCategoryDecl>(ND) || IsCategory ? /*Category*/ 2
289 : /*Class*/ 1);
290 if (isa<ObjCMethodDecl>(ND))
291 S.Diag(ND->getLocation(), diag::note_method_declared_at)
292 << ND->getDeclName();
293 else
294 S.Diag(ND->getLocation(), diag::note_previous_decl)
295 << (isa<ObjCCategoryDecl>(ND) ? "category" : "class");
Fariborz Jahaniand724a102011-02-15 17:49:58 +0000296}
297
Fariborz Jahanianbd0642f2011-08-31 17:37:55 +0000298/// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
299/// pool.
300void Sema::AddAnyMethodToGlobalPool(Decl *D) {
301 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
302
303 // If we don't have a valid method decl, simply return.
304 if (!MDecl)
305 return;
306 if (MDecl->isInstanceMethod())
307 AddInstanceMethodToGlobalPool(MDecl, true);
308 else
309 AddFactoryMethodToGlobalPool(MDecl, true);
310}
311
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000312/// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
313/// has explicit ownership attribute; false otherwise.
314static bool
315HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
316 QualType T = Param->getType();
317
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000318 if (const PointerType *PT = T->getAs<PointerType>()) {
319 T = PT->getPointeeType();
320 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
321 T = RT->getPointeeType();
322 } else {
323 return true;
324 }
325
326 // If we have a lifetime qualifier, but it's local, we must have
327 // inferred it. So, it is implicit.
328 return !T.getLocalQualifiers().hasObjCLifetime();
329}
330
Fariborz Jahanian18d0a5d2012-08-08 23:41:08 +0000331/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
332/// and user declared, in the method definition's AST.
333void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
Craig Topperc3ec1492014-05-26 06:22:03 +0000334 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
John McCall48871652010-08-21 09:40:31 +0000335 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
Fariborz Jahanian577574a2012-07-02 23:37:09 +0000336
Steve Naroff542cd5d2008-07-25 17:57:26 +0000337 // If we don't have a valid method decl, simply return.
338 if (!MDecl)
339 return;
Steve Naroff1d2538c2007-12-18 01:30:32 +0000340
Chris Lattnerda463fe2007-12-12 07:09:47 +0000341 // Allow all of Sema to see that we are entering a method definition.
Douglas Gregor91f84212008-12-11 16:49:14 +0000342 PushDeclContext(FnBodyScope, MDecl);
Douglas Gregor9a28e842010-03-01 23:15:13 +0000343 PushFunctionScope();
344
Chris Lattnerda463fe2007-12-12 07:09:47 +0000345 // Create Decl objects for each parameter, entrring them in the scope for
346 // binding to their use.
Chris Lattnerda463fe2007-12-12 07:09:47 +0000347
348 // Insert the invisible arguments, self and _cmd!
Fariborz Jahanian3d8552a2008-12-09 20:23:04 +0000349 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
Mike Stump11289f42009-09-09 15:08:12 +0000350
Daniel Dunbar279d1cc2008-08-26 06:07:48 +0000351 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
352 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000353
Reid Kleckner5a115802013-06-24 14:38:26 +0000354 // The ObjC parser requires parameter names so there's no need to check.
David Majnemer59f77922016-06-24 04:05:48 +0000355 CheckParmsForFunctionDef(MDecl->parameters(),
Reid Kleckner5a115802013-06-24 14:38:26 +0000356 /*CheckParameterNames=*/false);
357
Chris Lattner58258242008-04-10 02:22:51 +0000358 // Introduce all of the other parameters into this scope.
David Majnemer59f77922016-06-24 04:05:48 +0000359 for (auto *Param : MDecl->parameters()) {
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000360 if (!Param->isInvalidDecl() &&
Fariborz Jahanian1dfeace2012-09-13 18:53:14 +0000361 getLangOpts().ObjCAutoRefCount &&
362 !HasExplicitOwnershipAttr(*this, Param))
363 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
364 Param->getType();
Fariborz Jahaniancd278ff2012-08-30 23:56:02 +0000365
Aaron Ballman43b68be2014-03-07 17:50:17 +0000366 if (Param->getIdentifier())
367 PushOnScopeChains(Param, FnBodyScope);
Fariborz Jahanianb3e87122010-09-17 22:07:07 +0000368 }
John McCall31168b02011-06-15 23:02:42 +0000369
370 // In ARC, disallow definition of retain/release/autorelease/retainCount
David Blaikiebbafb8a2012-03-11 07:00:24 +0000371 if (getLangOpts().ObjCAutoRefCount) {
John McCall31168b02011-06-15 23:02:42 +0000372 switch (MDecl->getMethodFamily()) {
373 case OMF_retain:
374 case OMF_retainCount:
375 case OMF_release:
376 case OMF_autorelease:
377 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
Fariborz Jahanian39d1c422013-05-16 19:08:44 +0000378 << 0 << MDecl->getSelector();
John McCall31168b02011-06-15 23:02:42 +0000379 break;
380
381 case OMF_None:
382 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +0000383 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +0000384 case OMF_alloc:
385 case OMF_init:
386 case OMF_mutableCopy:
387 case OMF_copy:
388 case OMF_new:
389 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +0000390 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +0000391 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +0000392 break;
393 }
394 }
395
Nico Weber715abaf2011-08-22 17:25:57 +0000396 // Warn on deprecated methods under -Wdeprecated-implementations,
397 // and prepare for warning on missing super calls.
398 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
Fariborz Jahanian566fff02012-09-07 23:46:23 +0000399 ObjCMethodDecl *IMD =
400 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
401
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000402 if (IMD) {
403 ObjCImplDecl *ImplDeclOfMethodDef =
404 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
405 ObjCContainerDecl *ContDeclOfMethodDecl =
406 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
Craig Topperc3ec1492014-05-26 06:22:03 +0000407 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000408 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
409 ImplDeclOfMethodDecl = OID->getImplementation();
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000410 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
411 if (CD->IsClassExtension()) {
412 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
413 ImplDeclOfMethodDecl = OID->getImplementation();
414 } else
415 ImplDeclOfMethodDecl = CD->getImplementation();
Fariborz Jahanian19a08bb2014-03-18 00:10:37 +0000416 }
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000417 // No need to issue deprecated warning if deprecated mehod in class/category
418 // is being implemented in its own implementation (no overriding is involved).
Fariborz Jahanianed39e7c2014-03-18 16:25:22 +0000419 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
Alex Lorenzf81d97e2017-07-13 16:35:59 +0000420 DiagnoseObjCImplementedDeprecations(*this, IMD, MDecl->getLocation());
Fariborz Jahaniand91d21c2012-11-17 20:53:53 +0000421 }
Nico Weber715abaf2011-08-22 17:25:57 +0000422
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000423 if (MDecl->getMethodFamily() == OMF_init) {
424 if (MDecl->isDesignatedInitializerForTheInterface()) {
425 getCurFunction()->ObjCIsDesignatedInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000426 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
Craig Topperc3ec1492014-05-26 06:22:03 +0000427 IC->getSuperClass() != nullptr;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000428 } else if (IC->hasDesignatedInitializers()) {
429 getCurFunction()->ObjCIsSecondaryInit = true;
Fariborz Jahaniane3b5c992014-03-14 23:30:18 +0000430 getCurFunction()->ObjCWarnForNoInitDelegation = true;
Argyrios Kyrtzidisb66d3cf2013-12-03 21:11:49 +0000431 }
432 }
Argyrios Kyrtzidis22bfa2c2013-12-03 21:11:36 +0000433
Nico Weber1fb82662011-08-28 22:35:17 +0000434 // If this is "dealloc" or "finalize", set some bit here.
Nico Weber715abaf2011-08-22 17:25:57 +0000435 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
436 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
437 // Only do this if the current class actually has a superclass.
Jordan Rosed03d99d2013-03-05 01:27:54 +0000438 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
Jordan Rose2afd6612012-10-19 16:05:26 +0000439 ObjCMethodFamily Family = MDecl->getMethodFamily();
440 if (Family == OMF_dealloc) {
441 if (!(getLangOpts().ObjCAutoRefCount ||
442 getLangOpts().getGC() == LangOptions::GCOnly))
443 getCurFunction()->ObjCShouldCallSuper = true;
444
445 } else if (Family == OMF_finalize) {
446 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
447 getCurFunction()->ObjCShouldCallSuper = true;
448
Fariborz Jahaniance4bbb22013-11-05 00:28:21 +0000449 } else {
Jordan Rose2afd6612012-10-19 16:05:26 +0000450 const ObjCMethodDecl *SuperMethod =
Jordan Rosed03d99d2013-03-05 01:27:54 +0000451 SuperClass->lookupMethod(MDecl->getSelector(),
452 MDecl->isInstanceMethod());
Jordan Rose2afd6612012-10-19 16:05:26 +0000453 getCurFunction()->ObjCShouldCallSuper =
454 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
Fariborz Jahaniand6876b22012-09-10 18:04:25 +0000455 }
Nico Weber1fb82662011-08-28 22:35:17 +0000456 }
Nico Weber715abaf2011-08-22 17:25:57 +0000457 }
Chris Lattnerda463fe2007-12-12 07:09:47 +0000458}
459
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000460namespace {
461
462// Callback to only accept typo corrections that are Objective-C classes.
463// If an ObjCInterfaceDecl* is given to the constructor, then the validation
464// function will reject corrections to that class.
465class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
466 public:
Craig Topperc3ec1492014-05-26 06:22:03 +0000467 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000468 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
469 : CurrentIDecl(IDecl) {}
470
Craig Toppere14c0f82014-03-12 04:55:44 +0000471 bool ValidateCandidate(const TypoCorrection &candidate) override {
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000472 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
473 return ID && !declaresSameEntity(ID, CurrentIDecl);
474 }
475
476 private:
477 ObjCInterfaceDecl *CurrentIDecl;
478};
479
Hans Wennborgdcfba332015-10-06 23:40:43 +0000480} // end anonymous namespace
Kaelyn Uhraine31b8882012-01-13 01:32:50 +0000481
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000482static void diagnoseUseOfProtocols(Sema &TheSema,
483 ObjCContainerDecl *CD,
484 ObjCProtocolDecl *const *ProtoRefs,
485 unsigned NumProtoRefs,
486 const SourceLocation *ProtoLocs) {
487 assert(ProtoRefs);
488 // Diagnose availability in the context of the ObjC container.
489 Sema::ContextRAII SavedContext(TheSema, CD);
490 for (unsigned i = 0; i < NumProtoRefs; ++i) {
Alex Lorenzcdd596f2017-07-07 09:15:29 +0000491 (void)TheSema.DiagnoseUseOfDecl(ProtoRefs[i], ProtoLocs[i],
492 /*UnknownObjCClass=*/nullptr,
493 /*ObjCPropertyAccess=*/false,
494 /*AvoidPartialAvailabilityChecks=*/true);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +0000495 }
496}
497
Douglas Gregore9d95f12015-07-07 03:57:35 +0000498void Sema::
499ActOnSuperClassOfClassInterface(Scope *S,
500 SourceLocation AtInterfaceLoc,
501 ObjCInterfaceDecl *IDecl,
502 IdentifierInfo *ClassName,
503 SourceLocation ClassLoc,
504 IdentifierInfo *SuperName,
505 SourceLocation SuperLoc,
506 ArrayRef<ParsedType> SuperTypeArgs,
507 SourceRange SuperTypeArgsRange) {
508 // Check if a different kind of symbol declared in this scope.
509 NamedDecl *PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
510 LookupOrdinaryName);
511
512 if (!PrevDecl) {
513 // Try to correct for a typo in the superclass name without correcting
514 // to the class we're defining.
515 if (TypoCorrection Corrected = CorrectTypo(
516 DeclarationNameInfo(SuperName, SuperLoc),
517 LookupOrdinaryName, TUScope,
Hans Wennborgdcfba332015-10-06 23:40:43 +0000518 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
Douglas Gregore9d95f12015-07-07 03:57:35 +0000519 CTK_ErrorRecovery)) {
520 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
521 << SuperName << ClassName);
522 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
523 }
524 }
525
526 if (declaresSameEntity(PrevDecl, IDecl)) {
527 Diag(SuperLoc, diag::err_recursive_superclass)
528 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
529 IDecl->setEndOfDefinitionLoc(ClassLoc);
530 } else {
531 ObjCInterfaceDecl *SuperClassDecl =
532 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
533 QualType SuperClassType;
534
535 // Diagnose classes that inherit from deprecated classes.
536 if (SuperClassDecl) {
537 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
538 SuperClassType = Context.getObjCInterfaceType(SuperClassDecl);
539 }
540
Hans Wennborgdcfba332015-10-06 23:40:43 +0000541 if (PrevDecl && !SuperClassDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000542 // The previous declaration was not a class decl. Check if we have a
543 // typedef. If we do, get the underlying class type.
544 if (const TypedefNameDecl *TDecl =
545 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
546 QualType T = TDecl->getUnderlyingType();
547 if (T->isObjCObjectType()) {
548 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
549 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
550 SuperClassType = Context.getTypeDeclType(TDecl);
551
552 // This handles the following case:
553 // @interface NewI @end
554 // typedef NewI DeprI __attribute__((deprecated("blah")))
555 // @interface SI : DeprI /* warn here */ @end
556 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
557 }
558 }
559 }
560
561 // This handles the following case:
562 //
563 // typedef int SuperClass;
564 // @interface MyClass : SuperClass {} @end
565 //
566 if (!SuperClassDecl) {
567 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
568 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
569 }
570 }
571
572 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
573 if (!SuperClassDecl)
574 Diag(SuperLoc, diag::err_undef_superclass)
575 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
576 else if (RequireCompleteType(SuperLoc,
577 SuperClassType,
578 diag::err_forward_superclass,
579 SuperClassDecl->getDeclName(),
580 ClassName,
581 SourceRange(AtInterfaceLoc, ClassLoc))) {
Hans Wennborgdcfba332015-10-06 23:40:43 +0000582 SuperClassDecl = nullptr;
Douglas Gregore9d95f12015-07-07 03:57:35 +0000583 SuperClassType = QualType();
584 }
585 }
586
587 if (SuperClassType.isNull()) {
588 assert(!SuperClassDecl && "Failed to set SuperClassType?");
589 return;
590 }
591
592 // Handle type arguments on the superclass.
593 TypeSourceInfo *SuperClassTInfo = nullptr;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +0000594 if (!SuperTypeArgs.empty()) {
595 TypeResult fullSuperClassType = actOnObjCTypeArgsAndProtocolQualifiers(
596 S,
597 SuperLoc,
598 CreateParsedType(SuperClassType,
599 nullptr),
600 SuperTypeArgsRange.getBegin(),
601 SuperTypeArgs,
602 SuperTypeArgsRange.getEnd(),
603 SourceLocation(),
604 { },
605 { },
606 SourceLocation());
Douglas Gregore9d95f12015-07-07 03:57:35 +0000607 if (!fullSuperClassType.isUsable())
608 return;
609
610 SuperClassType = GetTypeFromParser(fullSuperClassType.get(),
611 &SuperClassTInfo);
612 }
613
614 if (!SuperClassTInfo) {
615 SuperClassTInfo = Context.getTrivialTypeSourceInfo(SuperClassType,
616 SuperLoc);
617 }
618
619 IDecl->setSuperClass(SuperClassTInfo);
620 IDecl->setEndOfDefinitionLoc(SuperClassTInfo->getTypeLoc().getLocEnd());
621 }
622}
623
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000624DeclResult Sema::actOnObjCTypeParam(Scope *S,
625 ObjCTypeParamVariance variance,
626 SourceLocation varianceLoc,
627 unsigned index,
Douglas Gregore83b9562015-07-07 03:57:53 +0000628 IdentifierInfo *paramName,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000629 SourceLocation paramLoc,
630 SourceLocation colonLoc,
631 ParsedType parsedTypeBound) {
632 // If there was an explicitly-provided type bound, check it.
633 TypeSourceInfo *typeBoundInfo = nullptr;
634 if (parsedTypeBound) {
635 // The type bound can be any Objective-C pointer type.
636 QualType typeBound = GetTypeFromParser(parsedTypeBound, &typeBoundInfo);
637 if (typeBound->isObjCObjectPointerType()) {
638 // okay
639 } else if (typeBound->isObjCObjectType()) {
640 // The user forgot the * on an Objective-C pointer type, e.g.,
641 // "T : NSView".
Craig Topper07fa1762015-11-15 02:31:46 +0000642 SourceLocation starLoc = getLocForEndOfToken(
Douglas Gregor85f3f952015-07-07 03:57:15 +0000643 typeBoundInfo->getTypeLoc().getEndLoc());
644 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
645 diag::err_objc_type_param_bound_missing_pointer)
646 << typeBound << paramName
647 << FixItHint::CreateInsertion(starLoc, " *");
648
649 // Create a new type location builder so we can update the type
650 // location information we have.
651 TypeLocBuilder builder;
652 builder.pushFullCopy(typeBoundInfo->getTypeLoc());
653
654 // Create the Objective-C pointer type.
655 typeBound = Context.getObjCObjectPointerType(typeBound);
656 ObjCObjectPointerTypeLoc newT
657 = builder.push<ObjCObjectPointerTypeLoc>(typeBound);
658 newT.setStarLoc(starLoc);
659
660 // Form the new type source information.
661 typeBoundInfo = builder.getTypeSourceInfo(Context, typeBound);
662 } else {
Douglas Gregore9d95f12015-07-07 03:57:35 +0000663 // Not a valid type bound.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000664 Diag(typeBoundInfo->getTypeLoc().getBeginLoc(),
665 diag::err_objc_type_param_bound_nonobject)
666 << typeBound << paramName;
667
668 // Forget the bound; we'll default to id later.
669 typeBoundInfo = nullptr;
670 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000671
John McCall69975252015-09-23 22:14:21 +0000672 // Type bounds cannot have qualifiers (even indirectly) or explicit
673 // nullability.
Douglas Gregore83b9562015-07-07 03:57:53 +0000674 if (typeBoundInfo) {
John McCall69975252015-09-23 22:14:21 +0000675 QualType typeBound = typeBoundInfo->getType();
676 TypeLoc qual = typeBoundInfo->getTypeLoc().findExplicitQualifierLoc();
677 if (qual || typeBound.hasQualifiers()) {
678 bool diagnosed = false;
679 SourceRange rangeToRemove;
680 if (qual) {
681 if (auto attr = qual.getAs<AttributedTypeLoc>()) {
682 rangeToRemove = attr.getLocalSourceRange();
683 if (attr.getTypePtr()->getImmediateNullability()) {
684 Diag(attr.getLocStart(),
685 diag::err_objc_type_param_bound_explicit_nullability)
686 << paramName << typeBound
687 << FixItHint::CreateRemoval(rangeToRemove);
688 diagnosed = true;
689 }
690 }
691 }
692
693 if (!diagnosed) {
694 Diag(qual ? qual.getLocStart()
695 : typeBoundInfo->getTypeLoc().getLocStart(),
696 diag::err_objc_type_param_bound_qualified)
697 << paramName << typeBound << typeBound.getQualifiers().getAsString()
698 << FixItHint::CreateRemoval(rangeToRemove);
699 }
700
701 // If the type bound has qualifiers other than CVR, we need to strip
702 // them or we'll probably assert later when trying to apply new
703 // qualifiers.
704 Qualifiers quals = typeBound.getQualifiers();
705 quals.removeCVRQualifiers();
706 if (!quals.empty()) {
707 typeBoundInfo =
708 Context.getTrivialTypeSourceInfo(typeBound.getUnqualifiedType());
709 }
Douglas Gregore83b9562015-07-07 03:57:53 +0000710 }
711 }
Douglas Gregor85f3f952015-07-07 03:57:15 +0000712 }
713
714 // If there was no explicit type bound (or we removed it due to an error),
715 // use 'id' instead.
716 if (!typeBoundInfo) {
717 colonLoc = SourceLocation();
718 typeBoundInfo = Context.getTrivialTypeSourceInfo(Context.getObjCIdType());
719 }
720
721 // Create the type parameter.
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000722 return ObjCTypeParamDecl::Create(Context, CurContext, variance, varianceLoc,
723 index, paramLoc, paramName, colonLoc,
724 typeBoundInfo);
Douglas Gregor85f3f952015-07-07 03:57:15 +0000725}
726
727ObjCTypeParamList *Sema::actOnObjCTypeParamList(Scope *S,
728 SourceLocation lAngleLoc,
729 ArrayRef<Decl *> typeParamsIn,
730 SourceLocation rAngleLoc) {
731 // We know that the array only contains Objective-C type parameters.
732 ArrayRef<ObjCTypeParamDecl *>
733 typeParams(
734 reinterpret_cast<ObjCTypeParamDecl * const *>(typeParamsIn.data()),
735 typeParamsIn.size());
736
737 // Diagnose redeclarations of type parameters.
738 // We do this now because Objective-C type parameters aren't pushed into
739 // scope until later (after the instance variable block), but we want the
740 // diagnostics to occur right after we parse the type parameter list.
741 llvm::SmallDenseMap<IdentifierInfo *, ObjCTypeParamDecl *> knownParams;
742 for (auto typeParam : typeParams) {
743 auto known = knownParams.find(typeParam->getIdentifier());
744 if (known != knownParams.end()) {
745 Diag(typeParam->getLocation(), diag::err_objc_type_param_redecl)
746 << typeParam->getIdentifier()
747 << SourceRange(known->second->getLocation());
748
749 typeParam->setInvalidDecl();
750 } else {
751 knownParams.insert(std::make_pair(typeParam->getIdentifier(), typeParam));
752
753 // Push the type parameter into scope.
754 PushOnScopeChains(typeParam, S, /*AddToContext=*/false);
755 }
756 }
757
758 // Create the parameter list.
759 return ObjCTypeParamList::create(Context, lAngleLoc, typeParams, rAngleLoc);
760}
761
762void Sema::popObjCTypeParamList(Scope *S, ObjCTypeParamList *typeParamList) {
763 for (auto typeParam : *typeParamList) {
764 if (!typeParam->isInvalidDecl()) {
765 S->RemoveDecl(typeParam);
766 IdResolver.RemoveDecl(typeParam);
767 }
768 }
769}
770
771namespace {
772 /// The context in which an Objective-C type parameter list occurs, for use
773 /// in diagnostics.
774 enum class TypeParamListContext {
775 ForwardDeclaration,
776 Definition,
777 Category,
778 Extension
779 };
Hans Wennborgdcfba332015-10-06 23:40:43 +0000780} // end anonymous namespace
Douglas Gregor85f3f952015-07-07 03:57:15 +0000781
782/// Check consistency between two Objective-C type parameter lists, e.g.,
NAKAMURA Takumi4c3ab452015-07-08 02:35:56 +0000783/// between a category/extension and an \@interface or between an \@class and an
784/// \@interface.
Douglas Gregor85f3f952015-07-07 03:57:15 +0000785static bool checkTypeParamListConsistency(Sema &S,
786 ObjCTypeParamList *prevTypeParams,
787 ObjCTypeParamList *newTypeParams,
788 TypeParamListContext newContext) {
789 // If the sizes don't match, complain about that.
790 if (prevTypeParams->size() != newTypeParams->size()) {
791 SourceLocation diagLoc;
792 if (newTypeParams->size() > prevTypeParams->size()) {
793 diagLoc = newTypeParams->begin()[prevTypeParams->size()]->getLocation();
794 } else {
Craig Topper07fa1762015-11-15 02:31:46 +0000795 diagLoc = S.getLocForEndOfToken(newTypeParams->back()->getLocEnd());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000796 }
797
798 S.Diag(diagLoc, diag::err_objc_type_param_arity_mismatch)
799 << static_cast<unsigned>(newContext)
800 << (newTypeParams->size() > prevTypeParams->size())
801 << prevTypeParams->size()
802 << newTypeParams->size();
803
804 return true;
805 }
806
807 // Match up the type parameters.
808 for (unsigned i = 0, n = prevTypeParams->size(); i != n; ++i) {
809 ObjCTypeParamDecl *prevTypeParam = prevTypeParams->begin()[i];
810 ObjCTypeParamDecl *newTypeParam = newTypeParams->begin()[i];
811
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000812 // Check for consistency of the variance.
813 if (newTypeParam->getVariance() != prevTypeParam->getVariance()) {
814 if (newTypeParam->getVariance() == ObjCTypeParamVariance::Invariant &&
815 newContext != TypeParamListContext::Definition) {
816 // When the new type parameter is invariant and is not part
817 // of the definition, just propagate the variance.
818 newTypeParam->setVariance(prevTypeParam->getVariance());
819 } else if (prevTypeParam->getVariance()
820 == ObjCTypeParamVariance::Invariant &&
821 !(isa<ObjCInterfaceDecl>(prevTypeParam->getDeclContext()) &&
822 cast<ObjCInterfaceDecl>(prevTypeParam->getDeclContext())
823 ->getDefinition() == prevTypeParam->getDeclContext())) {
824 // When the old parameter is invariant and was not part of the
825 // definition, just ignore the difference because it doesn't
826 // matter.
827 } else {
828 {
829 // Diagnose the conflict and update the second declaration.
830 SourceLocation diagLoc = newTypeParam->getVarianceLoc();
831 if (diagLoc.isInvalid())
832 diagLoc = newTypeParam->getLocStart();
833
834 auto diag = S.Diag(diagLoc,
835 diag::err_objc_type_param_variance_conflict)
836 << static_cast<unsigned>(newTypeParam->getVariance())
837 << newTypeParam->getDeclName()
838 << static_cast<unsigned>(prevTypeParam->getVariance())
839 << prevTypeParam->getDeclName();
840 switch (prevTypeParam->getVariance()) {
841 case ObjCTypeParamVariance::Invariant:
842 diag << FixItHint::CreateRemoval(newTypeParam->getVarianceLoc());
843 break;
844
845 case ObjCTypeParamVariance::Covariant:
846 case ObjCTypeParamVariance::Contravariant: {
847 StringRef newVarianceStr
848 = prevTypeParam->getVariance() == ObjCTypeParamVariance::Covariant
849 ? "__covariant"
850 : "__contravariant";
851 if (newTypeParam->getVariance()
852 == ObjCTypeParamVariance::Invariant) {
853 diag << FixItHint::CreateInsertion(newTypeParam->getLocStart(),
854 (newVarianceStr + " ").str());
855 } else {
856 diag << FixItHint::CreateReplacement(newTypeParam->getVarianceLoc(),
857 newVarianceStr);
858 }
859 }
860 }
861 }
862
863 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
864 << prevTypeParam->getDeclName();
865
866 // Override the variance.
867 newTypeParam->setVariance(prevTypeParam->getVariance());
868 }
869 }
870
Douglas Gregor85f3f952015-07-07 03:57:15 +0000871 // If the bound types match, there's nothing to do.
872 if (S.Context.hasSameType(prevTypeParam->getUnderlyingType(),
873 newTypeParam->getUnderlyingType()))
874 continue;
875
876 // If the new type parameter's bound was explicit, complain about it being
877 // different from the original.
878 if (newTypeParam->hasExplicitBound()) {
879 SourceRange newBoundRange = newTypeParam->getTypeSourceInfo()
880 ->getTypeLoc().getSourceRange();
881 S.Diag(newBoundRange.getBegin(), diag::err_objc_type_param_bound_conflict)
882 << newTypeParam->getUnderlyingType()
883 << newTypeParam->getDeclName()
884 << prevTypeParam->hasExplicitBound()
885 << prevTypeParam->getUnderlyingType()
886 << (newTypeParam->getDeclName() == prevTypeParam->getDeclName())
887 << prevTypeParam->getDeclName()
888 << FixItHint::CreateReplacement(
889 newBoundRange,
890 prevTypeParam->getUnderlyingType().getAsString(
891 S.Context.getPrintingPolicy()));
892
893 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
894 << prevTypeParam->getDeclName();
895
896 // Override the new type parameter's bound type with the previous type,
897 // so that it's consistent.
898 newTypeParam->setTypeSourceInfo(
899 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
900 continue;
901 }
902
903 // The new type parameter got the implicit bound of 'id'. That's okay for
904 // categories and extensions (overwrite it later), but not for forward
905 // declarations and @interfaces, because those must be standalone.
906 if (newContext == TypeParamListContext::ForwardDeclaration ||
907 newContext == TypeParamListContext::Definition) {
908 // Diagnose this problem for forward declarations and definitions.
909 SourceLocation insertionLoc
Craig Topper07fa1762015-11-15 02:31:46 +0000910 = S.getLocForEndOfToken(newTypeParam->getLocation());
Douglas Gregor85f3f952015-07-07 03:57:15 +0000911 std::string newCode
912 = " : " + prevTypeParam->getUnderlyingType().getAsString(
913 S.Context.getPrintingPolicy());
914 S.Diag(newTypeParam->getLocation(),
915 diag::err_objc_type_param_bound_missing)
916 << prevTypeParam->getUnderlyingType()
917 << newTypeParam->getDeclName()
918 << (newContext == TypeParamListContext::ForwardDeclaration)
919 << FixItHint::CreateInsertion(insertionLoc, newCode);
920
921 S.Diag(prevTypeParam->getLocation(), diag::note_objc_type_param_here)
922 << prevTypeParam->getDeclName();
923 }
924
925 // Update the new type parameter's bound to match the previous one.
926 newTypeParam->setTypeSourceInfo(
927 S.Context.getTrivialTypeSourceInfo(prevTypeParam->getUnderlyingType()));
928 }
929
930 return false;
931}
932
John McCall48871652010-08-21 09:40:31 +0000933Decl *Sema::
Douglas Gregore9d95f12015-07-07 03:57:35 +0000934ActOnStartClassInterface(Scope *S, SourceLocation AtInterfaceLoc,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000935 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +0000936 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000937 IdentifierInfo *SuperName, SourceLocation SuperLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +0000938 ArrayRef<ParsedType> SuperTypeArgs,
939 SourceRange SuperTypeArgsRange,
John McCall48871652010-08-21 09:40:31 +0000940 Decl * const *ProtoRefs, unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +0000941 const SourceLocation *ProtoLocs,
Chris Lattnerd7352d62008-07-21 22:17:28 +0000942 SourceLocation EndProtoLoc, AttributeList *AttrList) {
Chris Lattnerda463fe2007-12-12 07:09:47 +0000943 assert(ClassName && "Missing class identifier");
Mike Stump11289f42009-09-09 15:08:12 +0000944
Chris Lattnerda463fe2007-12-12 07:09:47 +0000945 // Check for another declaration kind with the same name.
Richard Smithbecb92d2017-10-10 22:33:17 +0000946 NamedDecl *PrevDecl =
947 LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
948 forRedeclarationInCurContext());
Douglas Gregor5101c242008-12-05 18:15:24 +0000949
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000950 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +0000951 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +0000952 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +0000953 }
Mike Stump11289f42009-09-09 15:08:12 +0000954
Douglas Gregordc9166c2011-12-15 20:29:51 +0000955 // Create a declaration to describe this @interface.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +0000956 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +0000957
958 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
959 // A previous decl with a different name is because of
960 // @compatibility_alias, for example:
961 // \code
962 // @class NewImage;
963 // @compatibility_alias OldImage NewImage;
964 // \endcode
965 // A lookup for 'OldImage' will return the 'NewImage' decl.
966 //
967 // In such a case use the real declaration name, instead of the alias one,
968 // otherwise we will break IdentifierResolver and redecls-chain invariants.
969 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
970 // has been aliased.
971 ClassName = PrevIDecl->getIdentifier();
972 }
973
Douglas Gregor85f3f952015-07-07 03:57:15 +0000974 // If there was a forward declaration with type parameters, check
975 // for consistency.
976 if (PrevIDecl) {
977 if (ObjCTypeParamList *prevTypeParamList = PrevIDecl->getTypeParamList()) {
978 if (typeParamList) {
979 // Both have type parameter lists; check for consistency.
980 if (checkTypeParamListConsistency(*this, prevTypeParamList,
981 typeParamList,
982 TypeParamListContext::Definition)) {
983 typeParamList = nullptr;
984 }
985 } else {
986 Diag(ClassLoc, diag::err_objc_parameterized_forward_class_first)
987 << ClassName;
988 Diag(prevTypeParamList->getLAngleLoc(), diag::note_previous_decl)
989 << ClassName;
990
991 // Clone the type parameter list.
992 SmallVector<ObjCTypeParamDecl *, 4> clonedTypeParams;
993 for (auto typeParam : *prevTypeParamList) {
994 clonedTypeParams.push_back(
995 ObjCTypeParamDecl::Create(
996 Context,
997 CurContext,
Douglas Gregor1ac1b632015-07-07 03:58:54 +0000998 typeParam->getVariance(),
999 SourceLocation(),
Douglas Gregore83b9562015-07-07 03:57:53 +00001000 typeParam->getIndex(),
Douglas Gregor85f3f952015-07-07 03:57:15 +00001001 SourceLocation(),
1002 typeParam->getIdentifier(),
1003 SourceLocation(),
1004 Context.getTrivialTypeSourceInfo(typeParam->getUnderlyingType())));
1005 }
1006
1007 typeParamList = ObjCTypeParamList::create(Context,
1008 SourceLocation(),
1009 clonedTypeParams,
1010 SourceLocation());
1011 }
1012 }
1013 }
1014
Douglas Gregordc9166c2011-12-15 20:29:51 +00001015 ObjCInterfaceDecl *IDecl
1016 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001017 typeParamList, PrevIDecl, ClassLoc);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001018 if (PrevIDecl) {
1019 // Class already seen. Was it a definition?
1020 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
1021 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
1022 << PrevIDecl->getDeclName();
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001023 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001024 IDecl->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00001025 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001026 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00001027
1028 if (AttrList)
1029 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001030 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregordc9166c2011-12-15 20:29:51 +00001031 PushOnScopeChains(IDecl, TUScope);
Mike Stump11289f42009-09-09 15:08:12 +00001032
Douglas Gregordc9166c2011-12-15 20:29:51 +00001033 // Start the definition of this class. If we're in a redefinition case, there
1034 // may already be a definition, so we'll end up adding to it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001035 if (!IDecl->hasDefinition())
1036 IDecl->startDefinition();
1037
Chris Lattnerda463fe2007-12-12 07:09:47 +00001038 if (SuperName) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001039 // Diagnose availability in the context of the @interface.
1040 ContextRAII SavedContext(*this, IDecl);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001041
Douglas Gregore9d95f12015-07-07 03:57:35 +00001042 ActOnSuperClassOfClassInterface(S, AtInterfaceLoc, IDecl,
1043 ClassName, ClassLoc,
1044 SuperName, SuperLoc, SuperTypeArgs,
1045 SuperTypeArgsRange);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001046 } else { // we have a root class.
Douglas Gregor16408322011-12-15 22:34:59 +00001047 IDecl->setEndOfDefinitionLoc(ClassLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001048 }
Mike Stump11289f42009-09-09 15:08:12 +00001049
Sebastian Redle7c1fe62010-08-13 00:28:03 +00001050 // Check then save referenced protocols.
Chris Lattnerdf59f5a2008-07-26 04:13:19 +00001051 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001052 diagnoseUseOfProtocols(*this, IDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1053 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001054 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001055 ProtoLocs, Context);
Douglas Gregor16408322011-12-15 22:34:59 +00001056 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001057 }
Mike Stump11289f42009-09-09 15:08:12 +00001058
Anders Carlssona6b508a2008-11-04 16:57:32 +00001059 CheckObjCDeclScope(IDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001060 return ActOnObjCContainerStartDefinition(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001061}
1062
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001063/// ActOnTypedefedProtocols - this action finds protocol list as part of the
1064/// typedef'ed use for a qualified super class and adds them to the list
1065/// of the protocols.
1066void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001067 SmallVectorImpl<SourceLocation> &ProtocolLocs,
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001068 IdentifierInfo *SuperName,
1069 SourceLocation SuperLoc) {
1070 if (!SuperName)
1071 return;
1072 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
1073 LookupOrdinaryName);
1074 if (!IDecl)
1075 return;
1076
1077 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
1078 QualType T = TDecl->getUnderlyingType();
1079 if (T->isObjCObjectType())
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001080 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>()) {
Benjamin Kramerf9890422015-02-17 16:48:30 +00001081 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
Argyrios Kyrtzidisf95a0002016-11-09 02:47:07 +00001082 // FIXME: Consider whether this should be an invalid loc since the loc
1083 // is not actually pointing to a protocol name reference but to the
1084 // typedef reference. Note that the base class name loc is also pointing
1085 // at the typedef.
1086 ProtocolLocs.append(OPT->getNumProtocols(), SuperLoc);
1087 }
Fariborz Jahanianb7c5f742013-09-25 19:36:32 +00001088 }
1089}
1090
Richard Smithac4e36d2012-08-08 23:32:13 +00001091/// ActOnCompatibilityAlias - this action is called after complete parsing of
James Dennett634962f2012-06-14 21:40:34 +00001092/// a \@compatibility_alias declaration. It sets up the alias relationships.
Richard Smithac4e36d2012-08-08 23:32:13 +00001093Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
1094 IdentifierInfo *AliasName,
1095 SourceLocation AliasLocation,
1096 IdentifierInfo *ClassName,
1097 SourceLocation ClassLocation) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001098 // Look for previous declaration of alias name
Richard Smithbecb92d2017-10-10 22:33:17 +00001099 NamedDecl *ADecl =
1100 LookupSingleName(TUScope, AliasName, AliasLocation, LookupOrdinaryName,
1101 forRedeclarationInCurContext());
Chris Lattnerda463fe2007-12-12 07:09:47 +00001102 if (ADecl) {
Eli Friedmanfd6b3f82013-06-21 01:49:53 +00001103 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
Chris Lattnerd0685032008-11-23 23:20:13 +00001104 Diag(ADecl->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001105 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001106 }
1107 // Check for class declaration
Richard Smithbecb92d2017-10-10 22:33:17 +00001108 NamedDecl *CDeclU =
1109 LookupSingleName(TUScope, ClassName, ClassLocation, LookupOrdinaryName,
1110 forRedeclarationInCurContext());
Richard Smithdda56e42011-04-15 14:24:37 +00001111 if (const TypedefNameDecl *TDecl =
1112 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001113 QualType T = TDecl->getUnderlyingType();
John McCall8b07ec22010-05-15 11:32:37 +00001114 if (T->isObjCObjectType()) {
1115 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001116 ClassName = IDecl->getIdentifier();
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001117 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
Richard Smithbecb92d2017-10-10 22:33:17 +00001118 LookupOrdinaryName,
1119 forRedeclarationInCurContext());
Fariborz Jahanian17290c32009-01-08 01:10:55 +00001120 }
1121 }
1122 }
Chris Lattner219b3e92008-03-16 21:17:37 +00001123 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
Craig Topperc3ec1492014-05-26 06:22:03 +00001124 if (!CDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001125 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
Chris Lattner219b3e92008-03-16 21:17:37 +00001126 if (CDeclU)
Chris Lattnerd0685032008-11-23 23:20:13 +00001127 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
Craig Topperc3ec1492014-05-26 06:22:03 +00001128 return nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001129 }
Mike Stump11289f42009-09-09 15:08:12 +00001130
Chris Lattner219b3e92008-03-16 21:17:37 +00001131 // Everything checked out, instantiate a new alias declaration AST.
Mike Stump11289f42009-09-09 15:08:12 +00001132 ObjCCompatibleAliasDecl *AliasDecl =
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001133 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
Mike Stump11289f42009-09-09 15:08:12 +00001134
Anders Carlssona6b508a2008-11-04 16:57:32 +00001135 if (!CheckObjCDeclScope(AliasDecl))
Douglas Gregor38feed82009-04-24 02:57:34 +00001136 PushOnScopeChains(AliasDecl, TUScope);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001137
John McCall48871652010-08-21 09:40:31 +00001138 return AliasDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001139}
1140
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001141bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
Steve Naroff41d09ad2009-03-05 15:22:01 +00001142 IdentifierInfo *PName,
1143 SourceLocation &Ploc, SourceLocation PrevLoc,
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001144 const ObjCList<ObjCProtocolDecl> &PList) {
1145
1146 bool res = false;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001147 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
1148 E = PList.end(); I != E; ++I) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001149 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
1150 Ploc)) {
Steve Naroff41d09ad2009-03-05 15:22:01 +00001151 if (PDecl->getIdentifier() == PName) {
1152 Diag(Ploc, diag::err_protocol_has_circular_dependency);
1153 Diag(PrevLoc, diag::note_previous_definition);
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001154 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001155 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001156
1157 if (!PDecl->hasDefinition())
1158 continue;
1159
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001160 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
1161 PDecl->getLocation(), PDecl->getReferencedProtocols()))
1162 res = true;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001163 }
1164 }
Fariborz Jahanian7d622732011-05-13 18:02:08 +00001165 return res;
Steve Naroff41d09ad2009-03-05 15:22:01 +00001166}
1167
John McCall48871652010-08-21 09:40:31 +00001168Decl *
Chris Lattner3bbae002008-07-26 04:03:38 +00001169Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
1170 IdentifierInfo *ProtocolName,
1171 SourceLocation ProtocolLoc,
John McCall48871652010-08-21 09:40:31 +00001172 Decl * const *ProtoRefs,
Chris Lattner3bbae002008-07-26 04:03:38 +00001173 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001174 const SourceLocation *ProtoLocs,
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001175 SourceLocation EndProtoLoc,
1176 AttributeList *AttrList) {
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001177 bool err = false;
Daniel Dunbar26e2ab42008-09-26 04:48:09 +00001178 // FIXME: Deal with AttrList.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001179 assert(ProtocolName && "Missing protocol identifier");
Douglas Gregor32c17572012-01-01 20:30:41 +00001180 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00001181 forRedeclarationInCurContext());
Craig Topperc3ec1492014-05-26 06:22:03 +00001182 ObjCProtocolDecl *PDecl = nullptr;
1183 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
Douglas Gregor32c17572012-01-01 20:30:41 +00001184 // If we already have a definition, complain.
1185 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
1186 Diag(Def->getLocation(), diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00001187
Douglas Gregor32c17572012-01-01 20:30:41 +00001188 // Create a new protocol that is completely distinct from previous
1189 // declarations, and do not make this protocol available for name lookup.
1190 // That way, we'll end up completely ignoring the duplicate.
1191 // FIXME: Can we turn this into an error?
1192 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
1193 ProtocolLoc, AtProtoInterfaceLoc,
Craig Topperc3ec1492014-05-26 06:22:03 +00001194 /*PrevDecl=*/nullptr);
Douglas Gregor32c17572012-01-01 20:30:41 +00001195 PDecl->startDefinition();
1196 } else {
1197 if (PrevDecl) {
1198 // Check for circular dependencies among protocol declarations. This can
1199 // only happen if this protocol was forward-declared.
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001200 ObjCList<ObjCProtocolDecl> PList;
1201 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
1202 err = CheckForwardProtocolDeclarationForCircularDependency(
Douglas Gregor32c17572012-01-01 20:30:41 +00001203 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
Argyrios Kyrtzidis95dfc122011-11-13 22:08:30 +00001204 }
Douglas Gregor32c17572012-01-01 20:30:41 +00001205
1206 // Create the new declaration.
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001207 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
Argyrios Kyrtzidis1f4bee52011-10-17 19:48:06 +00001208 ProtocolLoc, AtProtoInterfaceLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001209 /*PrevDecl=*/PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001210
Douglas Gregorde9f17e2009-04-23 23:18:26 +00001211 PushOnScopeChains(PDecl, TUScope);
Douglas Gregore6e48b12012-01-01 19:29:29 +00001212 PDecl->startDefinition();
Chris Lattnerf87ca0a2008-03-16 01:23:04 +00001213 }
Douglas Gregore6e48b12012-01-01 19:29:29 +00001214
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001215 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001216 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001217 AddPragmaAttributes(TUScope, PDecl);
1218
Douglas Gregor32c17572012-01-01 20:30:41 +00001219 // Merge attributes from previous declarations.
1220 if (PrevDecl)
1221 mergeDeclAttributes(PDecl, PrevDecl);
1222
Fariborz Jahaniancadf7c52011-05-12 22:04:39 +00001223 if (!err && NumProtoRefs ) {
Chris Lattneracc04a92008-03-16 20:19:15 +00001224 /// Check then save referenced protocols.
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001225 diagnoseUseOfProtocols(*this, PDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1226 NumProtoRefs, ProtoLocs);
Roman Divackye6377112012-09-06 15:59:27 +00001227 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001228 ProtoLocs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001229 }
Mike Stump11289f42009-09-09 15:08:12 +00001230
1231 CheckObjCDeclScope(PDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001232 return ActOnObjCContainerStartDefinition(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001233}
1234
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001235static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
1236 ObjCProtocolDecl *&UndefinedProtocol) {
1237 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
1238 UndefinedProtocol = PDecl;
1239 return true;
1240 }
1241
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00001242 for (auto *PI : PDecl->protocols())
1243 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
1244 UndefinedProtocol = PI;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001245 return true;
1246 }
1247 return false;
1248}
1249
Chris Lattnerda463fe2007-12-12 07:09:47 +00001250/// FindProtocolDeclaration - This routine looks up protocols and
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00001251/// issues an error if they are not declared. It returns list of
1252/// protocol declarations in its 'Protocols' argument.
Chris Lattnerda463fe2007-12-12 07:09:47 +00001253void
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001254Sema::FindProtocolDeclaration(bool WarnOnDeclarations, bool ForObjCContainer,
Craig Toppera9247eb2015-10-22 04:59:56 +00001255 ArrayRef<IdentifierLocPair> ProtocolId,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00001256 SmallVectorImpl<Decl *> &Protocols) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001257 for (const IdentifierLocPair &Pair : ProtocolId) {
1258 ObjCProtocolDecl *PDecl = LookupProtocol(Pair.first, Pair.second);
Chris Lattner9c1842b2008-07-26 03:47:43 +00001259 if (!PDecl) {
Douglas Gregorc2fa1692011-06-28 16:20:02 +00001260 TypoCorrection Corrected = CorrectTypo(
Craig Toppera9247eb2015-10-22 04:59:56 +00001261 DeclarationNameInfo(Pair.first, Pair.second),
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001262 LookupObjCProtocolName, TUScope, nullptr,
1263 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
Craig Topperc3ec1492014-05-26 06:22:03 +00001264 CTK_ErrorRecovery);
Richard Smithf9b15102013-08-17 00:46:16 +00001265 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
1266 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
Craig Toppera9247eb2015-10-22 04:59:56 +00001267 << Pair.first);
Douglas Gregor35b0bac2010-01-03 18:01:57 +00001268 }
1269
1270 if (!PDecl) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001271 Diag(Pair.second, diag::err_undeclared_protocol) << Pair.first;
Chris Lattner9c1842b2008-07-26 03:47:43 +00001272 continue;
1273 }
Fariborz Jahanianada44a22013-04-09 17:52:29 +00001274 // If this is a forward protocol declaration, get its definition.
1275 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
1276 PDecl = PDecl->getDefinition();
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001277
1278 // For an objc container, delay protocol reference checking until after we
1279 // can set the objc decl as the availability context, otherwise check now.
1280 if (!ForObjCContainer) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001281 (void)DiagnoseUseOfDecl(PDecl, Pair.second);
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001282 }
Chris Lattner9c1842b2008-07-26 03:47:43 +00001283
1284 // If this is a forward declaration and we are supposed to warn in this
1285 // case, do it.
Douglas Gregoreed49792013-01-17 00:38:46 +00001286 // FIXME: Recover nicely in the hidden case.
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001287 ObjCProtocolDecl *UndefinedProtocol;
1288
Douglas Gregoreed49792013-01-17 00:38:46 +00001289 if (WarnOnDeclarations &&
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001290 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
Craig Toppera9247eb2015-10-22 04:59:56 +00001291 Diag(Pair.second, diag::warn_undef_protocolref) << Pair.first;
Fariborz Jahanianbf678e82014-03-11 17:10:51 +00001292 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
1293 << UndefinedProtocol;
1294 }
John McCall48871652010-08-21 09:40:31 +00001295 Protocols.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001296 }
1297}
1298
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001299namespace {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001300// Callback to only accept typo corrections that are either
1301// Objective-C protocols or valid Objective-C type arguments.
1302class ObjCTypeArgOrProtocolValidatorCCC : public CorrectionCandidateCallback {
1303 ASTContext &Context;
1304 Sema::LookupNameKind LookupKind;
1305 public:
1306 ObjCTypeArgOrProtocolValidatorCCC(ASTContext &context,
1307 Sema::LookupNameKind lookupKind)
1308 : Context(context), LookupKind(lookupKind) { }
1309
1310 bool ValidateCandidate(const TypoCorrection &candidate) override {
1311 // If we're allowed to find protocols and we have a protocol, accept it.
1312 if (LookupKind != Sema::LookupOrdinaryName) {
1313 if (candidate.getCorrectionDeclAs<ObjCProtocolDecl>())
1314 return true;
1315 }
1316
1317 // If we're allowed to find type names and we have one, accept it.
1318 if (LookupKind != Sema::LookupObjCProtocolName) {
1319 // If we have a type declaration, we might accept this result.
1320 if (auto typeDecl = candidate.getCorrectionDeclAs<TypeDecl>()) {
1321 // If we found a tag declaration outside of C++, skip it. This
1322 // can happy because we look for any name when there is no
1323 // bias to protocol or type names.
1324 if (isa<RecordDecl>(typeDecl) && !Context.getLangOpts().CPlusPlus)
1325 return false;
1326
1327 // Make sure the type is something we would accept as a type
1328 // argument.
1329 auto type = Context.getTypeDeclType(typeDecl);
1330 if (type->isObjCObjectPointerType() ||
1331 type->isBlockPointerType() ||
1332 type->isDependentType() ||
1333 type->isObjCObjectType())
1334 return true;
1335
1336 return false;
1337 }
1338
1339 // If we have an Objective-C class type, accept it; there will
1340 // be another fix to add the '*'.
1341 if (candidate.getCorrectionDeclAs<ObjCInterfaceDecl>())
1342 return true;
1343
1344 return false;
1345 }
1346
1347 return false;
1348 }
1349};
Benjamin Kramer8b851d02015-07-13 20:42:13 +00001350} // end anonymous namespace
Douglas Gregore9d95f12015-07-07 03:57:35 +00001351
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001352void Sema::DiagnoseTypeArgsAndProtocols(IdentifierInfo *ProtocolId,
1353 SourceLocation ProtocolLoc,
1354 IdentifierInfo *TypeArgId,
1355 SourceLocation TypeArgLoc,
1356 bool SelectProtocolFirst) {
1357 Diag(TypeArgLoc, diag::err_objc_type_args_and_protocols)
1358 << SelectProtocolFirst << TypeArgId << ProtocolId
1359 << SourceRange(ProtocolLoc);
1360}
1361
Douglas Gregore9d95f12015-07-07 03:57:35 +00001362void Sema::actOnObjCTypeArgsOrProtocolQualifiers(
1363 Scope *S,
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001364 ParsedType baseType,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001365 SourceLocation lAngleLoc,
1366 ArrayRef<IdentifierInfo *> identifiers,
1367 ArrayRef<SourceLocation> identifierLocs,
1368 SourceLocation rAngleLoc,
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001369 SourceLocation &typeArgsLAngleLoc,
1370 SmallVectorImpl<ParsedType> &typeArgs,
1371 SourceLocation &typeArgsRAngleLoc,
1372 SourceLocation &protocolLAngleLoc,
1373 SmallVectorImpl<Decl *> &protocols,
1374 SourceLocation &protocolRAngleLoc,
Douglas Gregore9d95f12015-07-07 03:57:35 +00001375 bool warnOnIncompleteProtocols) {
1376 // Local function that updates the declaration specifiers with
1377 // protocol information.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001378 unsigned numProtocolsResolved = 0;
1379 auto resolvedAsProtocols = [&] {
1380 assert(numProtocolsResolved == identifiers.size() && "Unresolved protocols");
1381
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001382 // Determine whether the base type is a parameterized class, in
1383 // which case we want to warn about typos such as
1384 // "NSArray<NSObject>" (that should be NSArray<NSObject *>).
1385 ObjCInterfaceDecl *baseClass = nullptr;
1386 QualType base = GetTypeFromParser(baseType, nullptr);
1387 bool allAreTypeNames = false;
1388 SourceLocation firstClassNameLoc;
1389 if (!base.isNull()) {
1390 if (const auto *objcObjectType = base->getAs<ObjCObjectType>()) {
1391 baseClass = objcObjectType->getInterface();
1392 if (baseClass) {
1393 if (auto typeParams = baseClass->getTypeParamList()) {
1394 if (typeParams->size() == numProtocolsResolved) {
1395 // Note that we should be looking for type names, too.
1396 allAreTypeNames = true;
1397 }
1398 }
1399 }
1400 }
1401 }
1402
Douglas Gregore9d95f12015-07-07 03:57:35 +00001403 for (unsigned i = 0, n = protocols.size(); i != n; ++i) {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001404 ObjCProtocolDecl *&proto
1405 = reinterpret_cast<ObjCProtocolDecl *&>(protocols[i]);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001406 // For an objc container, delay protocol reference checking until after we
1407 // can set the objc decl as the availability context, otherwise check now.
1408 if (!warnOnIncompleteProtocols) {
1409 (void)DiagnoseUseOfDecl(proto, identifierLocs[i]);
1410 }
1411
1412 // If this is a forward protocol declaration, get its definition.
1413 if (!proto->isThisDeclarationADefinition() && proto->getDefinition())
1414 proto = proto->getDefinition();
1415
1416 // If this is a forward declaration and we are supposed to warn in this
1417 // case, do it.
1418 // FIXME: Recover nicely in the hidden case.
1419 ObjCProtocolDecl *forwardDecl = nullptr;
1420 if (warnOnIncompleteProtocols &&
1421 NestedProtocolHasNoDefinition(proto, forwardDecl)) {
1422 Diag(identifierLocs[i], diag::warn_undef_protocolref)
1423 << proto->getDeclName();
1424 Diag(forwardDecl->getLocation(), diag::note_protocol_decl_undefined)
1425 << forwardDecl;
1426 }
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001427
1428 // If everything this far has been a type name (and we care
1429 // about such things), check whether this name refers to a type
1430 // as well.
1431 if (allAreTypeNames) {
1432 if (auto *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1433 LookupOrdinaryName)) {
1434 if (isa<ObjCInterfaceDecl>(decl)) {
1435 if (firstClassNameLoc.isInvalid())
1436 firstClassNameLoc = identifierLocs[i];
1437 } else if (!isa<TypeDecl>(decl)) {
1438 // Not a type.
1439 allAreTypeNames = false;
1440 }
1441 } else {
1442 allAreTypeNames = false;
1443 }
1444 }
1445 }
1446
1447 // All of the protocols listed also have type names, and at least
1448 // one is an Objective-C class name. Check whether all of the
1449 // protocol conformances are declared by the base class itself, in
1450 // which case we warn.
1451 if (allAreTypeNames && firstClassNameLoc.isValid()) {
1452 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> knownProtocols;
1453 Context.CollectInheritedProtocols(baseClass, knownProtocols);
1454 bool allProtocolsDeclared = true;
1455 for (auto proto : protocols) {
1456 if (knownProtocols.count(static_cast<ObjCProtocolDecl *>(proto)) == 0) {
1457 allProtocolsDeclared = false;
1458 break;
1459 }
1460 }
1461
1462 if (allProtocolsDeclared) {
1463 Diag(firstClassNameLoc, diag::warn_objc_redundant_qualified_class_type)
1464 << baseClass->getDeclName() << SourceRange(lAngleLoc, rAngleLoc)
Craig Topper07fa1762015-11-15 02:31:46 +00001465 << FixItHint::CreateInsertion(getLocForEndOfToken(firstClassNameLoc),
1466 " *");
Douglas Gregor10dc9d82015-07-07 03:58:28 +00001467 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001468 }
1469
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001470 protocolLAngleLoc = lAngleLoc;
1471 protocolRAngleLoc = rAngleLoc;
1472 assert(protocols.size() == identifierLocs.size());
Douglas Gregore9d95f12015-07-07 03:57:35 +00001473 };
1474
1475 // Attempt to resolve all of the identifiers as protocols.
1476 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1477 ObjCProtocolDecl *proto = LookupProtocol(identifiers[i], identifierLocs[i]);
1478 protocols.push_back(proto);
1479 if (proto)
1480 ++numProtocolsResolved;
1481 }
1482
1483 // If all of the names were protocols, these were protocol qualifiers.
1484 if (numProtocolsResolved == identifiers.size())
1485 return resolvedAsProtocols();
1486
1487 // Attempt to resolve all of the identifiers as type names or
1488 // Objective-C class names. The latter is technically ill-formed,
1489 // but is probably something like \c NSArray<NSView *> missing the
1490 // \c*.
1491 typedef llvm::PointerUnion<TypeDecl *, ObjCInterfaceDecl *> TypeOrClassDecl;
1492 SmallVector<TypeOrClassDecl, 4> typeDecls;
1493 unsigned numTypeDeclsResolved = 0;
1494 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1495 NamedDecl *decl = LookupSingleName(S, identifiers[i], identifierLocs[i],
1496 LookupOrdinaryName);
1497 if (!decl) {
1498 typeDecls.push_back(TypeOrClassDecl());
1499 continue;
1500 }
1501
1502 if (auto typeDecl = dyn_cast<TypeDecl>(decl)) {
1503 typeDecls.push_back(typeDecl);
1504 ++numTypeDeclsResolved;
1505 continue;
1506 }
1507
1508 if (auto objcClass = dyn_cast<ObjCInterfaceDecl>(decl)) {
1509 typeDecls.push_back(objcClass);
1510 ++numTypeDeclsResolved;
1511 continue;
1512 }
1513
1514 typeDecls.push_back(TypeOrClassDecl());
1515 }
1516
1517 AttributeFactory attrFactory;
1518
1519 // Local function that forms a reference to the given type or
1520 // Objective-C class declaration.
1521 auto resolveTypeReference = [&](TypeOrClassDecl typeDecl, SourceLocation loc)
1522 -> TypeResult {
1523 // Form declaration specifiers. They simply refer to the type.
1524 DeclSpec DS(attrFactory);
1525 const char* prevSpec; // unused
1526 unsigned diagID; // unused
1527 QualType type;
1528 if (auto *actualTypeDecl = typeDecl.dyn_cast<TypeDecl *>())
1529 type = Context.getTypeDeclType(actualTypeDecl);
1530 else
1531 type = Context.getObjCInterfaceType(typeDecl.get<ObjCInterfaceDecl *>());
1532 TypeSourceInfo *parsedTSInfo = Context.getTrivialTypeSourceInfo(type, loc);
1533 ParsedType parsedType = CreateParsedType(type, parsedTSInfo);
1534 DS.SetTypeSpecType(DeclSpec::TST_typename, loc, prevSpec, diagID,
1535 parsedType, Context.getPrintingPolicy());
1536 // Use the identifier location for the type source range.
1537 DS.SetRangeStart(loc);
1538 DS.SetRangeEnd(loc);
1539
1540 // Form the declarator.
1541 Declarator D(DS, Declarator::TypeNameContext);
1542
1543 // If we have a typedef of an Objective-C class type that is missing a '*',
1544 // add the '*'.
1545 if (type->getAs<ObjCInterfaceType>()) {
Craig Topper07fa1762015-11-15 02:31:46 +00001546 SourceLocation starLoc = getLocForEndOfToken(loc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001547 ParsedAttributes parsedAttrs(attrFactory);
1548 D.AddTypeInfo(DeclaratorChunk::getPointer(/*typeQuals=*/0, starLoc,
1549 SourceLocation(),
1550 SourceLocation(),
1551 SourceLocation(),
Andrey Bokhanko45d41322016-05-11 18:38:21 +00001552 SourceLocation(),
Douglas Gregore9d95f12015-07-07 03:57:35 +00001553 SourceLocation()),
Hans Wennborgdcfba332015-10-06 23:40:43 +00001554 parsedAttrs,
1555 starLoc);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001556
1557 // Diagnose the missing '*'.
1558 Diag(loc, diag::err_objc_type_arg_missing_star)
1559 << type
1560 << FixItHint::CreateInsertion(starLoc, " *");
1561 }
1562
1563 // Convert this to a type.
1564 return ActOnTypeName(S, D);
1565 };
1566
1567 // Local function that updates the declaration specifiers with
1568 // type argument information.
1569 auto resolvedAsTypeDecls = [&] {
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001570 // We did not resolve these as protocols.
1571 protocols.clear();
1572
Douglas Gregore9d95f12015-07-07 03:57:35 +00001573 assert(numTypeDeclsResolved == identifiers.size() && "Unresolved type decl");
1574 // Map type declarations to type arguments.
Douglas Gregore9d95f12015-07-07 03:57:35 +00001575 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1576 // Map type reference to a type.
1577 TypeResult type = resolveTypeReference(typeDecls[i], identifierLocs[i]);
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001578 if (!type.isUsable()) {
1579 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001580 return;
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001581 }
Douglas Gregore9d95f12015-07-07 03:57:35 +00001582
1583 typeArgs.push_back(type.get());
1584 }
1585
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001586 typeArgsLAngleLoc = lAngleLoc;
1587 typeArgsRAngleLoc = rAngleLoc;
Douglas Gregore9d95f12015-07-07 03:57:35 +00001588 };
1589
1590 // If all of the identifiers can be resolved as type names or
1591 // Objective-C class names, we have type arguments.
1592 if (numTypeDeclsResolved == identifiers.size())
1593 return resolvedAsTypeDecls();
1594
1595 // Error recovery: some names weren't found, or we have a mix of
1596 // type and protocol names. Go resolve all of the unresolved names
1597 // and complain if we can't find a consistent answer.
1598 LookupNameKind lookupKind = LookupAnyName;
1599 for (unsigned i = 0, n = identifiers.size(); i != n; ++i) {
1600 // If we already have a protocol or type. Check whether it is the
1601 // right thing.
1602 if (protocols[i] || typeDecls[i]) {
1603 // If we haven't figured out whether we want types or protocols
1604 // yet, try to figure it out from this name.
1605 if (lookupKind == LookupAnyName) {
1606 // If this name refers to both a protocol and a type (e.g., \c
1607 // NSObject), don't conclude anything yet.
1608 if (protocols[i] && typeDecls[i])
1609 continue;
1610
1611 // Otherwise, let this name decide whether we'll be correcting
1612 // toward types or protocols.
1613 lookupKind = protocols[i] ? LookupObjCProtocolName
1614 : LookupOrdinaryName;
1615 continue;
1616 }
1617
1618 // If we want protocols and we have a protocol, there's nothing
1619 // more to do.
1620 if (lookupKind == LookupObjCProtocolName && protocols[i])
1621 continue;
1622
1623 // If we want types and we have a type declaration, there's
1624 // nothing more to do.
1625 if (lookupKind == LookupOrdinaryName && typeDecls[i])
1626 continue;
1627
1628 // We have a conflict: some names refer to protocols and others
1629 // refer to types.
Bruno Cardoso Lopesc54768f2016-04-13 20:59:07 +00001630 DiagnoseTypeArgsAndProtocols(identifiers[0], identifierLocs[0],
1631 identifiers[i], identifierLocs[i],
1632 protocols[i] != nullptr);
Douglas Gregore9d95f12015-07-07 03:57:35 +00001633
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001634 protocols.clear();
1635 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001636 return;
1637 }
1638
1639 // Perform typo correction on the name.
1640 TypoCorrection corrected = CorrectTypo(
1641 DeclarationNameInfo(identifiers[i], identifierLocs[i]), lookupKind, S,
1642 nullptr,
1643 llvm::make_unique<ObjCTypeArgOrProtocolValidatorCCC>(Context,
1644 lookupKind),
1645 CTK_ErrorRecovery);
1646 if (corrected) {
1647 // Did we find a protocol?
1648 if (auto proto = corrected.getCorrectionDeclAs<ObjCProtocolDecl>()) {
1649 diagnoseTypo(corrected,
1650 PDiag(diag::err_undeclared_protocol_suggest)
1651 << identifiers[i]);
1652 lookupKind = LookupObjCProtocolName;
1653 protocols[i] = proto;
1654 ++numProtocolsResolved;
1655 continue;
1656 }
1657
1658 // Did we find a type?
1659 if (auto typeDecl = corrected.getCorrectionDeclAs<TypeDecl>()) {
1660 diagnoseTypo(corrected,
1661 PDiag(diag::err_unknown_typename_suggest)
1662 << identifiers[i]);
1663 lookupKind = LookupOrdinaryName;
1664 typeDecls[i] = typeDecl;
1665 ++numTypeDeclsResolved;
1666 continue;
1667 }
1668
1669 // Did we find an Objective-C class?
1670 if (auto objcClass = corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1671 diagnoseTypo(corrected,
1672 PDiag(diag::err_unknown_type_or_class_name_suggest)
1673 << identifiers[i] << true);
1674 lookupKind = LookupOrdinaryName;
1675 typeDecls[i] = objcClass;
1676 ++numTypeDeclsResolved;
1677 continue;
1678 }
1679 }
1680
1681 // We couldn't find anything.
1682 Diag(identifierLocs[i],
1683 (lookupKind == LookupAnyName ? diag::err_objc_type_arg_missing
1684 : lookupKind == LookupObjCProtocolName ? diag::err_undeclared_protocol
1685 : diag::err_unknown_typename))
1686 << identifiers[i];
Douglas Gregor9bda6cf2015-07-07 03:58:14 +00001687 protocols.clear();
1688 typeArgs.clear();
Douglas Gregore9d95f12015-07-07 03:57:35 +00001689 return;
1690 }
1691
1692 // If all of the names were (corrected to) protocols, these were
1693 // protocol qualifiers.
1694 if (numProtocolsResolved == identifiers.size())
1695 return resolvedAsProtocols();
1696
1697 // Otherwise, all of the names were (corrected to) types.
1698 assert(numTypeDeclsResolved == identifiers.size() && "Not all types?");
1699 return resolvedAsTypeDecls();
1700}
1701
Fariborz Jahanianabf63e7b2009-03-02 19:06:08 +00001702/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001703/// a class method in its extension.
1704///
Mike Stump11289f42009-09-09 15:08:12 +00001705void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001706 ObjCInterfaceDecl *ID) {
1707 if (!ID)
1708 return; // Possibly due to previous error
1709
1710 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001711 for (auto *MD : ID->methods())
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001712 MethodMap[MD->getSelector()] = MD;
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001713
1714 if (MethodMap.empty())
1715 return;
Aaron Ballmanaff18c02014-03-13 19:03:34 +00001716 for (const auto *Method : CAT->methods()) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001717 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
Fariborz Jahanian83d674e2014-03-17 17:46:10 +00001718 if (PrevMethod &&
1719 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
1720 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
Fariborz Jahanian33afd772009-03-02 19:05:07 +00001721 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1722 << Method->getDeclName();
1723 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1724 }
1725 }
1726}
1727
James Dennett634962f2012-06-14 21:40:34 +00001728/// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
Douglas Gregorf6102672012-01-01 21:23:57 +00001729Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00001730Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
Craig Topper0f723bb2015-10-22 05:00:01 +00001731 ArrayRef<IdentifierLocPair> IdentList,
Fariborz Jahanian1470e932008-12-17 01:07:27 +00001732 AttributeList *attrList) {
Douglas Gregorf6102672012-01-01 21:23:57 +00001733 SmallVector<Decl *, 8> DeclsInGroup;
Craig Topper0f723bb2015-10-22 05:00:01 +00001734 for (const IdentifierLocPair &IdentPair : IdentList) {
1735 IdentifierInfo *Ident = IdentPair.first;
1736 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentPair.second,
Richard Smithbecb92d2017-10-10 22:33:17 +00001737 forRedeclarationInCurContext());
Douglas Gregor32c17572012-01-01 20:30:41 +00001738 ObjCProtocolDecl *PDecl
1739 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
Craig Topper0f723bb2015-10-22 05:00:01 +00001740 IdentPair.second, AtProtocolLoc,
Douglas Gregor05a1f4d2012-01-01 22:06:18 +00001741 PrevDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001742
1743 PushOnScopeChains(PDecl, TUScope);
Douglas Gregorf6102672012-01-01 21:23:57 +00001744 CheckObjCDeclScope(PDecl);
Douglas Gregor32c17572012-01-01 20:30:41 +00001745
Douglas Gregor42ff1bb2012-01-01 20:33:24 +00001746 if (attrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00001747 ProcessDeclAttributeList(TUScope, PDecl, attrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001748 AddPragmaAttributes(TUScope, PDecl);
1749
Douglas Gregor32c17572012-01-01 20:30:41 +00001750 if (PrevDecl)
1751 mergeDeclAttributes(PDecl, PrevDecl);
1752
Douglas Gregorf6102672012-01-01 21:23:57 +00001753 DeclsInGroup.push_back(PDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001754 }
Mike Stump11289f42009-09-09 15:08:12 +00001755
Richard Smith3beb7c62017-01-12 02:27:38 +00001756 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001757}
1758
John McCall48871652010-08-21 09:40:31 +00001759Decl *Sema::
Chris Lattnerd7352d62008-07-21 22:17:28 +00001760ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
1761 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001762 ObjCTypeParamList *typeParamList,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001763 IdentifierInfo *CategoryName,
1764 SourceLocation CategoryLoc,
John McCall48871652010-08-21 09:40:31 +00001765 Decl * const *ProtoRefs,
Chris Lattnerd7352d62008-07-21 22:17:28 +00001766 unsigned NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001767 const SourceLocation *ProtoLocs,
Alex Lorenzf9371392017-03-23 11:44:25 +00001768 SourceLocation EndProtoLoc,
1769 AttributeList *AttrList) {
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001770 ObjCCategoryDecl *CDecl;
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001771 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Ted Kremenek514ff702010-02-23 19:39:46 +00001772
1773 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001774
1775 if (!IDecl
1776 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
Douglas Gregor7bfb2d02012-05-04 16:32:21 +00001777 diag::err_category_forward_interface,
Craig Topperc3ec1492014-05-26 06:22:03 +00001778 CategoryName == nullptr)) {
Ted Kremenek514ff702010-02-23 19:39:46 +00001779 // Create an invalid ObjCCategoryDecl to serve as context for
1780 // the enclosing method declarations. We mark the decl invalid
1781 // to make it clear that this isn't a valid AST.
1782 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001783 ClassLoc, CategoryLoc, CategoryName,
1784 IDecl, typeParamList);
Ted Kremenek514ff702010-02-23 19:39:46 +00001785 CDecl->setInvalidDecl();
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00001786 CurContext->addDecl(CDecl);
Douglas Gregor4123a862011-11-14 22:10:01 +00001787
1788 if (!IDecl)
1789 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001790 return ActOnObjCContainerStartDefinition(CDecl);
Ted Kremenek514ff702010-02-23 19:39:46 +00001791 }
1792
Fariborz Jahanian3bf0ded2010-06-22 23:20:40 +00001793 if (!CategoryName && IDecl->getImplementation()) {
1794 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
1795 Diag(IDecl->getImplementation()->getLocation(),
1796 diag::note_implementation_declared);
Ted Kremenek514ff702010-02-23 19:39:46 +00001797 }
1798
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001799 if (CategoryName) {
1800 /// Check for duplicate interface declaration for this category
Douglas Gregor048fbfa2013-01-16 23:00:23 +00001801 if (ObjCCategoryDecl *Previous
1802 = IDecl->FindCategoryDeclaration(CategoryName)) {
1803 // Class extensions can be declared multiple times, categories cannot.
1804 Diag(CategoryLoc, diag::warn_dup_category_def)
1805 << ClassName << CategoryName;
1806 Diag(Previous->getLocation(), diag::note_previous_definition);
Chris Lattner9018ca82009-02-16 21:26:43 +00001807 }
1808 }
Chris Lattner9018ca82009-02-16 21:26:43 +00001809
Douglas Gregor85f3f952015-07-07 03:57:15 +00001810 // If we have a type parameter list, check it.
1811 if (typeParamList) {
1812 if (auto prevTypeParamList = IDecl->getTypeParamList()) {
1813 if (checkTypeParamListConsistency(*this, prevTypeParamList, typeParamList,
1814 CategoryName
1815 ? TypeParamListContext::Category
1816 : TypeParamListContext::Extension))
1817 typeParamList = nullptr;
1818 } else {
1819 Diag(typeParamList->getLAngleLoc(),
1820 diag::err_objc_parameterized_category_nonclass)
1821 << (CategoryName != nullptr)
1822 << ClassName
1823 << typeParamList->getSourceRange();
1824
1825 typeParamList = nullptr;
1826 }
1827 }
1828
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001829 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001830 ClassLoc, CategoryLoc, CategoryName, IDecl,
1831 typeParamList);
Argyrios Kyrtzidis3a5094b2011-08-30 19:43:26 +00001832 // FIXME: PushOnScopeChains?
1833 CurContext->addDecl(CDecl);
1834
Chris Lattnerda463fe2007-12-12 07:09:47 +00001835 if (NumProtoRefs) {
Argyrios Kyrtzidis4ecdd2c2015-04-19 20:15:55 +00001836 diagnoseUseOfProtocols(*this, CDecl, (ObjCProtocolDecl*const*)ProtoRefs,
1837 NumProtoRefs, ProtoLocs);
1838 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
Douglas Gregor002b6712010-01-16 15:02:53 +00001839 ProtoLocs, Context);
Fariborz Jahanian092cd6e2009-10-05 20:41:32 +00001840 // Protocols in the class extension belong to the class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00001841 if (CDecl->IsClassExtension())
Roman Divackye6377112012-09-06 15:59:27 +00001842 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
Ted Kremenek0ef508d2010-09-01 01:21:15 +00001843 NumProtoRefs, Context);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001844 }
Mike Stump11289f42009-09-09 15:08:12 +00001845
Alex Lorenzf9371392017-03-23 11:44:25 +00001846 if (AttrList)
1847 ProcessDeclAttributeList(TUScope, CDecl, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001848 AddPragmaAttributes(TUScope, CDecl);
Alex Lorenzf9371392017-03-23 11:44:25 +00001849
Anders Carlssona6b508a2008-11-04 16:57:32 +00001850 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001851 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001852}
1853
1854/// ActOnStartCategoryImplementation - Perform semantic checks on the
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001855/// category implementation declaration and build an ObjCCategoryImplDecl
Chris Lattnerda463fe2007-12-12 07:09:47 +00001856/// object.
John McCall48871652010-08-21 09:40:31 +00001857Decl *Sema::ActOnStartCategoryImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001858 SourceLocation AtCatImplLoc,
1859 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1860 IdentifierInfo *CatName, SourceLocation CatLoc) {
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001861 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
Craig Topperc3ec1492014-05-26 06:22:03 +00001862 ObjCCategoryDecl *CatIDecl = nullptr;
Argyrios Kyrtzidis4af2cb32012-03-02 19:14:29 +00001863 if (IDecl && IDecl->hasDefinition()) {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001864 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
1865 if (!CatIDecl) {
1866 // Category @implementation with no corresponding @interface.
1867 // Create and install one.
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001868 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
1869 ClassLoc, CatLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001870 CatName, IDecl,
1871 /*typeParamList=*/nullptr);
Argyrios Kyrtzidis41fc05c2011-11-23 20:27:26 +00001872 CatIDecl->setImplicit();
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001873 }
1874 }
1875
Mike Stump11289f42009-09-09 15:08:12 +00001876 ObjCCategoryImplDecl *CDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00001877 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
Argyrios Kyrtzidis4996f5f2011-12-09 00:31:40 +00001878 ClassLoc, AtCatImplLoc, CatLoc);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001879 /// Check that class of this category is already completely declared.
Douglas Gregor4123a862011-11-14 22:10:01 +00001880 if (!IDecl) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001881 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
John McCalld2930c22011-07-22 02:45:48 +00001882 CDecl->setInvalidDecl();
Douglas Gregor4123a862011-11-14 22:10:01 +00001883 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1884 diag::err_undef_interface)) {
1885 CDecl->setInvalidDecl();
John McCalld2930c22011-07-22 02:45:48 +00001886 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001887
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001888 // FIXME: PushOnScopeChains?
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001889 CurContext->addDecl(CDecl);
Douglas Gregorc25d7a72009-01-09 00:49:46 +00001890
Douglas Gregor24ae22c2016-04-01 23:23:52 +00001891 // If the interface has the objc_runtime_visible attribute, we
1892 // cannot implement a category for it.
1893 if (IDecl && IDecl->hasAttr<ObjCRuntimeVisibleAttr>()) {
1894 Diag(ClassLoc, diag::err_objc_runtime_visible_category)
1895 << IDecl->getDeclName();
1896 }
1897
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001898 /// Check that CatName, category name, is not used in another implementation.
1899 if (CatIDecl) {
1900 if (CatIDecl->getImplementation()) {
1901 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
1902 << CatName;
1903 Diag(CatIDecl->getImplementation()->getLocation(),
1904 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00001905 CDecl->setInvalidDecl();
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001906 } else {
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001907 CatIDecl->setImplementation(CDecl);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001908 // Warn on implementating category of deprecated class under
1909 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00001910 DiagnoseObjCImplementedDeprecations(*this, CatIDecl,
1911 CDecl->getLocation());
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00001912 }
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00001913 }
Mike Stump11289f42009-09-09 15:08:12 +00001914
Anders Carlssona6b508a2008-11-04 16:57:32 +00001915 CheckObjCDeclScope(CDecl);
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00001916 return ActOnObjCContainerStartDefinition(CDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001917}
1918
John McCall48871652010-08-21 09:40:31 +00001919Decl *Sema::ActOnStartClassImplementation(
Chris Lattnerda463fe2007-12-12 07:09:47 +00001920 SourceLocation AtClassImplLoc,
1921 IdentifierInfo *ClassName, SourceLocation ClassLoc,
Mike Stump11289f42009-09-09 15:08:12 +00001922 IdentifierInfo *SuperClassname,
Chris Lattnerda463fe2007-12-12 07:09:47 +00001923 SourceLocation SuperClassLoc) {
Craig Topperc3ec1492014-05-26 06:22:03 +00001924 ObjCInterfaceDecl *IDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001925 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00001926 NamedDecl *PrevDecl
Douglas Gregorb8eaf292010-04-15 23:40:53 +00001927 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
Richard Smithbecb92d2017-10-10 22:33:17 +00001928 forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001929 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001930 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
Chris Lattner0369c572008-11-23 23:12:31 +00001931 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Douglas Gregor1c283312010-08-11 12:19:30 +00001932 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
Richard Smithdb0ac552015-12-18 22:40:25 +00001933 // FIXME: This will produce an error if the definition of the interface has
1934 // been imported from a module but is not visible.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001935 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1936 diag::warn_undef_interface);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001937 } else {
Richard Smithf9b15102013-08-17 00:46:16 +00001938 // We did not find anything with the name ClassName; try to correct for
Douglas Gregor40f7a002010-01-04 17:27:12 +00001939 // typos in the class name.
Kaelyn Takata89c881b2014-10-27 18:07:29 +00001940 TypoCorrection Corrected = CorrectTypo(
1941 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1942 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
Richard Smithf9b15102013-08-17 00:46:16 +00001943 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1944 // Suggest the (potentially) correct interface name. Don't provide a
1945 // code-modification hint or use the typo name for recovery, because
1946 // this is just a warning. The program may actually be correct.
1947 diagnoseTypo(Corrected,
1948 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1949 /*ErrorRecovery*/false);
Douglas Gregor40f7a002010-01-04 17:27:12 +00001950 } else {
1951 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1952 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00001953 }
Mike Stump11289f42009-09-09 15:08:12 +00001954
Chris Lattnerda463fe2007-12-12 07:09:47 +00001955 // Check that super class name is valid class name
Craig Topperc3ec1492014-05-26 06:22:03 +00001956 ObjCInterfaceDecl *SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001957 if (SuperClassname) {
1958 // Check if a different kind of symbol declared in this scope.
Douglas Gregorb2ccf012010-04-15 22:33:43 +00001959 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1960 LookupOrdinaryName);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001961 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001962 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1963 << SuperClassname;
Chris Lattner0369c572008-11-23 23:12:31 +00001964 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001965 } else {
Mike Stump11289f42009-09-09 15:08:12 +00001966 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidis3b60cff2012-03-13 01:09:36 +00001967 if (SDecl && !SDecl->hasDefinition())
Craig Topperc3ec1492014-05-26 06:22:03 +00001968 SDecl = nullptr;
Chris Lattnerda463fe2007-12-12 07:09:47 +00001969 if (!SDecl)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001970 Diag(SuperClassLoc, diag::err_undef_superclass)
1971 << SuperClassname << ClassName;
Douglas Gregor0b144e12011-12-15 00:29:59 +00001972 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00001973 // This implementation and its interface do not have the same
1974 // super class.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00001975 Diag(SuperClassLoc, diag::err_conflicting_super_class)
Chris Lattnere3d20d92008-11-23 21:45:46 +00001976 << SDecl->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00001977 Diag(SDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00001978 }
1979 }
1980 }
Mike Stump11289f42009-09-09 15:08:12 +00001981
Chris Lattnerda463fe2007-12-12 07:09:47 +00001982 if (!IDecl) {
1983 // Legacy case of @implementation with no corresponding @interface.
1984 // Build, chain & install the interface decl into the identifier.
Daniel Dunbar73a73f52008-08-20 18:02:42 +00001985
Mike Stump87c57ac2009-05-16 07:39:55 +00001986 // FIXME: Do we support attributes on the @implementation? If so we should
1987 // copy them over.
Mike Stump11289f42009-09-09 15:08:12 +00001988 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00001989 ClassName, /*typeParamList=*/nullptr,
1990 /*PrevDecl=*/nullptr, ClassLoc,
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00001991 true);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00001992 AddPragmaAttributes(TUScope, IDecl);
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00001993 IDecl->startDefinition();
Douglas Gregor16408322011-12-15 22:34:59 +00001994 if (SDecl) {
Douglas Gregore9d95f12015-07-07 03:57:35 +00001995 IDecl->setSuperClass(Context.getTrivialTypeSourceInfo(
1996 Context.getObjCInterfaceType(SDecl),
1997 SuperClassLoc));
Douglas Gregor16408322011-12-15 22:34:59 +00001998 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1999 } else {
2000 IDecl->setEndOfDefinitionLoc(ClassLoc);
2001 }
2002
Douglas Gregorac345a32009-04-24 00:16:12 +00002003 PushOnScopeChains(IDecl, TUScope);
Douglas Gregor1c283312010-08-11 12:19:30 +00002004 } else {
2005 // Mark the interface as being completed, even if it was just as
2006 // @class ....;
2007 // declaration; the user cannot reopen it.
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00002008 if (!IDecl->hasDefinition())
2009 IDecl->startDefinition();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002010 }
Mike Stump11289f42009-09-09 15:08:12 +00002011
2012 ObjCImplementationDecl* IMPDecl =
Argyrios Kyrtzidis52f53fb2011-10-04 04:48:02 +00002013 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
Argyrios Kyrtzidisfac31622013-05-03 18:05:44 +00002014 ClassLoc, AtClassImplLoc, SuperClassLoc);
Mike Stump11289f42009-09-09 15:08:12 +00002015
Anders Carlssona6b508a2008-11-04 16:57:32 +00002016 if (CheckObjCDeclScope(IMPDecl))
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002017 return ActOnObjCContainerStartDefinition(IMPDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002018
Chris Lattnerda463fe2007-12-12 07:09:47 +00002019 // Check that there is no duplicate implementation of this class.
Douglas Gregor1c283312010-08-11 12:19:30 +00002020 if (IDecl->getImplementation()) {
2021 // FIXME: Don't leak everything!
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002022 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
Argyrios Kyrtzidis43cee9352009-07-21 00:06:04 +00002023 Diag(IDecl->getImplementation()->getLocation(),
2024 diag::note_previous_definition);
Argyrios Kyrtzidis0f6d5ca2013-05-30 18:53:21 +00002025 IMPDecl->setInvalidDecl();
Douglas Gregor1c283312010-08-11 12:19:30 +00002026 } else { // add it to the list.
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002027 IDecl->setImplementation(IMPDecl);
Douglas Gregor79947a22009-04-24 00:11:27 +00002028 PushOnScopeChains(IMPDecl, TUScope);
Fariborz Jahaniand33ab8c2011-02-15 00:59:30 +00002029 // Warn on implementating deprecated class under
2030 // -Wdeprecated-implementations flag.
Alex Lorenzf81d97e2017-07-13 16:35:59 +00002031 DiagnoseObjCImplementedDeprecations(*this, IDecl, IMPDecl->getLocation());
Argyrios Kyrtzidis6d9fab72009-07-21 00:05:53 +00002032 }
Douglas Gregor24ae22c2016-04-01 23:23:52 +00002033
2034 // If the superclass has the objc_runtime_visible attribute, we
2035 // cannot implement a subclass of it.
2036 if (IDecl->getSuperClass() &&
2037 IDecl->getSuperClass()->hasAttr<ObjCRuntimeVisibleAttr>()) {
2038 Diag(ClassLoc, diag::err_objc_runtime_visible_subclass)
2039 << IDecl->getDeclName()
2040 << IDecl->getSuperClass()->getDeclName();
2041 }
2042
Argyrios Kyrtzidis9321ad32011-10-06 23:23:20 +00002043 return ActOnObjCContainerStartDefinition(IMPDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002044}
2045
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002046Sema::DeclGroupPtrTy
2047Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
2048 SmallVector<Decl *, 64> DeclsInGroup;
2049 DeclsInGroup.reserve(Decls.size() + 1);
2050
2051 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
2052 Decl *Dcl = Decls[i];
2053 if (!Dcl)
2054 continue;
2055 if (Dcl->getDeclContext()->isFileContext())
2056 Dcl->setTopLevelDeclInObjCContainer();
2057 DeclsInGroup.push_back(Dcl);
2058 }
2059
2060 DeclsInGroup.push_back(ObjCImpDecl);
2061
Richard Smith3beb7c62017-01-12 02:27:38 +00002062 return BuildDeclaratorGroup(DeclsInGroup);
Argyrios Kyrtzidis2e85c5f2012-02-23 21:11:20 +00002063}
2064
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002065void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
2066 ObjCIvarDecl **ivars, unsigned numIvars,
Chris Lattnerda463fe2007-12-12 07:09:47 +00002067 SourceLocation RBrace) {
2068 assert(ImpDecl && "missing implementation decl");
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002069 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
Chris Lattnerda463fe2007-12-12 07:09:47 +00002070 if (!IDecl)
2071 return;
James Dennett634962f2012-06-14 21:40:34 +00002072 /// Check case of non-existing \@interface decl.
2073 /// (legacy objective-c \@implementation decl without an \@interface decl).
Chris Lattnerda463fe2007-12-12 07:09:47 +00002074 /// Add implementations's ivar to the synthesize class's ivar list.
Steve Naroffaac654a2009-04-20 20:09:33 +00002075 if (IDecl->isImplicitInterfaceDecl()) {
Douglas Gregor16408322011-12-15 22:34:59 +00002076 IDecl->setEndOfDefinitionLoc(RBrace);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002077 // Add ivar's to class's DeclContext.
2078 for (unsigned i = 0, e = numIvars; i != e; ++i) {
Fariborz Jahanianc0309cd2010-02-17 18:10:54 +00002079 ivars[i]->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002080 IDecl->makeDeclVisibleInContext(ivars[i]);
Fariborz Jahanianaef66222010-02-19 00:31:17 +00002081 ImpDecl->addDecl(ivars[i]);
Fariborz Jahanian20912d62010-02-17 17:00:07 +00002082 }
2083
Chris Lattnerda463fe2007-12-12 07:09:47 +00002084 return;
2085 }
2086 // If implementation has empty ivar list, just return.
2087 if (numIvars == 0)
2088 return;
Mike Stump11289f42009-09-09 15:08:12 +00002089
Chris Lattnerda463fe2007-12-12 07:09:47 +00002090 assert(ivars && "missing @implementation ivars");
John McCall5fb5df92012-06-20 06:18:46 +00002091 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002092 if (ImpDecl->getSuperClass())
2093 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
2094 for (unsigned i = 0; i < numIvars; i++) {
2095 ObjCIvarDecl* ImplIvar = ivars[i];
2096 if (const ObjCIvarDecl *ClsIvar =
2097 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2098 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2099 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
2100 continue;
2101 }
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002102 // Check class extensions (unnamed categories) for duplicate ivars.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002103 for (const auto *CDecl : IDecl->visible_extensions()) {
Fariborz Jahaniane23f26b2013-06-26 22:10:27 +00002104 if (const ObjCIvarDecl *ClsExtIvar =
2105 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
2106 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
2107 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
2108 continue;
2109 }
2110 }
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002111 // Instance ivar to Implementation's DeclContext.
2112 ImplIvar->setLexicalDeclContext(ImpDecl);
Richard Smith05afe5e2012-03-13 03:12:56 +00002113 IDecl->makeDeclVisibleInContext(ImplIvar);
Fariborz Jahanian34e3cef2010-02-19 20:58:54 +00002114 ImpDecl->addDecl(ImplIvar);
2115 }
2116 return;
2117 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002118 // Check interface's Ivar list against those in the implementation.
2119 // names and types must match.
2120 //
Chris Lattnerda463fe2007-12-12 07:09:47 +00002121 unsigned j = 0;
Mike Stump11289f42009-09-09 15:08:12 +00002122 ObjCInterfaceDecl::ivar_iterator
Chris Lattner061227a2007-12-12 17:58:05 +00002123 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
2124 for (; numIvars > 0 && IVI != IVE; ++IVI) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002125 ObjCIvarDecl* ImplIvar = ivars[j++];
David Blaikie40ed2972012-06-06 20:45:41 +00002126 ObjCIvarDecl* ClsIvar = *IVI;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002127 assert (ImplIvar && "missing implementation ivar");
2128 assert (ClsIvar && "missing class ivar");
Mike Stump11289f42009-09-09 15:08:12 +00002129
Steve Naroff157599f2009-03-03 14:49:36 +00002130 // First, make sure the types match.
Richard Smithcaf33902011-10-10 18:28:20 +00002131 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
Chris Lattner3b054132008-11-19 05:08:23 +00002132 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002133 << ImplIvar->getIdentifier()
2134 << ImplIvar->getType() << ClsIvar->getType();
Chris Lattner0369c572008-11-23 23:12:31 +00002135 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Richard Smithcaf33902011-10-10 18:28:20 +00002136 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
2137 ImplIvar->getBitWidthValue(Context) !=
2138 ClsIvar->getBitWidthValue(Context)) {
2139 Diag(ImplIvar->getBitWidth()->getLocStart(),
2140 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
2141 Diag(ClsIvar->getBitWidth()->getLocStart(),
2142 diag::note_previous_definition);
Mike Stump11289f42009-09-09 15:08:12 +00002143 }
Steve Naroff157599f2009-03-03 14:49:36 +00002144 // Make sure the names are identical.
2145 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
Chris Lattner3b054132008-11-19 05:08:23 +00002146 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
Chris Lattnere3d20d92008-11-23 21:45:46 +00002147 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
Chris Lattner0369c572008-11-23 23:12:31 +00002148 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002149 }
2150 --numIvars;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002151 }
Mike Stump11289f42009-09-09 15:08:12 +00002152
Chris Lattner0f29d982007-12-12 18:11:49 +00002153 if (numIvars > 0)
Alp Tokerfff06742013-12-02 03:50:21 +00002154 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattner0f29d982007-12-12 18:11:49 +00002155 else if (IVI != IVE)
Alp Tokerfff06742013-12-02 03:50:21 +00002156 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002157}
2158
Ted Kremenekf87decd2013-12-13 05:58:44 +00002159static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
2160 ObjCMethodDecl *method,
2161 bool &IncompleteImpl,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002162 unsigned DiagID,
Craig Topperc3ec1492014-05-26 06:22:03 +00002163 NamedDecl *NeededFor = nullptr) {
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002164 // No point warning no definition of method which is 'unavailable'.
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002165 switch (method->getAvailability()) {
2166 case AR_Available:
2167 case AR_Deprecated:
2168 break;
2169
2170 // Don't warn about unavailable or not-yet-introduced methods.
2171 case AR_NotYetIntroduced:
2172 case AR_Unavailable:
Fariborz Jahanian9fc39c42011-06-24 20:31:37 +00002173 return;
Douglas Gregorc2e3d5c2012-12-11 18:53:07 +00002174 }
2175
Ted Kremenek65d63572013-03-27 00:02:21 +00002176 // FIXME: For now ignore 'IncompleteImpl'.
2177 // Previously we grouped all unimplemented methods under a single
2178 // warning, but some users strongly voiced that they would prefer
2179 // separate warnings. We will give that approach a try, as that
2180 // matches what we do with protocols.
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002181 {
2182 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
2183 B << method;
2184 if (NeededFor)
2185 B << NeededFor;
2186 }
Ted Kremenek65d63572013-03-27 00:02:21 +00002187
2188 // Issue a note to the original declaration.
2189 SourceLocation MethodLoc = method->getLocStart();
2190 if (MethodLoc.isValid())
Ted Kremenekf87decd2013-12-13 05:58:44 +00002191 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
Steve Naroff15833ed2008-02-10 21:38:56 +00002192}
2193
David Chisnallb62d15c2010-10-25 17:23:52 +00002194/// Determines if type B can be substituted for type A. Returns true if we can
2195/// guarantee that anything that the user will do to an object of type A can
2196/// also be done to an object of type B. This is trivially true if the two
2197/// types are the same, or if B is a subclass of A. It becomes more complex
2198/// in cases where protocols are involved.
2199///
2200/// Object types in Objective-C describe the minimum requirements for an
2201/// object, rather than providing a complete description of a type. For
2202/// example, if A is a subclass of B, then B* may refer to an instance of A.
2203/// The principle of substitutability means that we may use an instance of A
2204/// anywhere that we may use an instance of B - it will implement all of the
2205/// ivars of B and all of the methods of B.
2206///
2207/// This substitutability is important when type checking methods, because
2208/// the implementation may have stricter type definitions than the interface.
2209/// The interface specifies minimum requirements, but the implementation may
2210/// have more accurate ones. For example, a method may privately accept
2211/// instances of B, but only publish that it accepts instances of A. Any
2212/// object passed to it will be type checked against B, and so will implicitly
2213/// by a valid A*. Similarly, a method may return a subclass of the class that
2214/// it is declared as returning.
2215///
2216/// This is most important when considering subclassing. A method in a
2217/// subclass must accept any object as an argument that its superclass's
2218/// implementation accepts. It may, however, accept a more general type
2219/// without breaking substitutability (i.e. you can still use the subclass
2220/// anywhere that you can use the superclass, but not vice versa). The
2221/// converse requirement applies to return types: the return type for a
2222/// subclass method must be a valid object of the kind that the superclass
2223/// advertises, but it may be specified more accurately. This avoids the need
2224/// for explicit down-casting by callers.
2225///
2226/// Note: This is a stricter requirement than for assignment.
John McCall071df462010-10-28 02:34:38 +00002227static bool isObjCTypeSubstitutable(ASTContext &Context,
2228 const ObjCObjectPointerType *A,
2229 const ObjCObjectPointerType *B,
2230 bool rejectId) {
2231 // Reject a protocol-unqualified id.
2232 if (rejectId && B->isObjCIdType()) return false;
David Chisnallb62d15c2010-10-25 17:23:52 +00002233
2234 // If B is a qualified id, then A must also be a qualified id and it must
2235 // implement all of the protocols in B. It may not be a qualified class.
2236 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
2237 // stricter definition so it is not substitutable for id<A>.
2238 if (B->isObjCQualifiedIdType()) {
2239 return A->isObjCQualifiedIdType() &&
John McCall071df462010-10-28 02:34:38 +00002240 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
2241 QualType(B,0),
2242 false);
David Chisnallb62d15c2010-10-25 17:23:52 +00002243 }
2244
2245 /*
2246 // id is a special type that bypasses type checking completely. We want a
2247 // warning when it is used in one place but not another.
2248 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
2249
2250
2251 // If B is a qualified id, then A must also be a qualified id (which it isn't
2252 // if we've got this far)
2253 if (B->isObjCQualifiedIdType()) return false;
2254 */
2255
2256 // Now we know that A and B are (potentially-qualified) class types. The
2257 // normal rules for assignment apply.
John McCall071df462010-10-28 02:34:38 +00002258 return Context.canAssignObjCInterfaces(A, B);
David Chisnallb62d15c2010-10-25 17:23:52 +00002259}
2260
John McCall071df462010-10-28 02:34:38 +00002261static SourceRange getTypeRange(TypeSourceInfo *TSI) {
2262 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
2263}
2264
Douglas Gregor813a0662015-06-19 18:14:38 +00002265/// Determine whether two set of Objective-C declaration qualifiers conflict.
2266static bool objcModifiersConflict(Decl::ObjCDeclQualifier x,
2267 Decl::ObjCDeclQualifier y) {
2268 return (x & ~Decl::OBJC_TQ_CSNullability) !=
2269 (y & ~Decl::OBJC_TQ_CSNullability);
2270}
2271
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002272static bool CheckMethodOverrideReturn(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002273 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002274 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002275 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002276 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002277 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002278 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002279 objcModifiersConflict(MethodDecl->getObjCDeclQualifier(),
2280 MethodImpl->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002281 if (Warn) {
Alp Toker314cc812014-01-25 16:55:45 +00002282 S.Diag(MethodImpl->getLocation(),
2283 (IsOverridingMode
2284 ? diag::warn_conflicting_overriding_ret_type_modifiers
2285 : diag::warn_conflicting_ret_type_modifiers))
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002286 << MethodImpl->getDeclName()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002287 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002288 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002289 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002290 }
2291 else
2292 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002293 }
Douglas Gregor813a0662015-06-19 18:14:38 +00002294 if (Warn && IsOverridingMode &&
2295 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2296 !S.Context.hasSameNullabilityTypeQualifier(MethodImpl->getReturnType(),
2297 MethodDecl->getReturnType(),
2298 false)) {
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002299 auto nullabilityMethodImpl =
2300 *MethodImpl->getReturnType()->getNullability(S.Context);
2301 auto nullabilityMethodDecl =
2302 *MethodDecl->getReturnType()->getNullability(S.Context);
Douglas Gregor813a0662015-06-19 18:14:38 +00002303 S.Diag(MethodImpl->getLocation(),
2304 diag::warn_conflicting_nullability_attr_overriding_ret_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002305 << DiagNullabilityKind(
2306 nullabilityMethodImpl,
2307 ((MethodImpl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2308 != 0))
2309 << DiagNullabilityKind(
2310 nullabilityMethodDecl,
2311 ((MethodDecl->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2312 != 0));
Douglas Gregor813a0662015-06-19 18:14:38 +00002313 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
2314 }
2315
Alp Toker314cc812014-01-25 16:55:45 +00002316 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
2317 MethodDecl->getReturnType()))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002318 return true;
2319 if (!Warn)
2320 return false;
John McCall071df462010-10-28 02:34:38 +00002321
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002322 unsigned DiagID =
2323 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
2324 : diag::warn_conflicting_ret_types;
John McCall071df462010-10-28 02:34:38 +00002325
2326 // Mismatches between ObjC pointers go into a different warning
2327 // category, and sometimes they're even completely whitelisted.
2328 if (const ObjCObjectPointerType *ImplPtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002329 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002330 if (const ObjCObjectPointerType *IfacePtrTy =
Alp Toker314cc812014-01-25 16:55:45 +00002331 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
John McCall071df462010-10-28 02:34:38 +00002332 // Allow non-matching return types as long as they don't violate
2333 // the principle of substitutability. Specifically, we permit
2334 // return types that are subclasses of the declared return type,
2335 // or that are more-qualified versions of the declared type.
2336 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002337 return false;
John McCall071df462010-10-28 02:34:38 +00002338
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002339 DiagID =
2340 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002341 : diag::warn_non_covariant_ret_types;
John McCall071df462010-10-28 02:34:38 +00002342 }
2343 }
2344
2345 S.Diag(MethodImpl->getLocation(), DiagID)
Alp Toker314cc812014-01-25 16:55:45 +00002346 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
2347 << MethodImpl->getReturnType()
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002348 << MethodImpl->getReturnTypeSourceRange();
Alp Toker314cc812014-01-25 16:55:45 +00002349 S.Diag(MethodDecl->getLocation(), IsOverridingMode
2350 ? diag::note_previous_declaration
2351 : diag::note_previous_definition)
Aaron Ballman41b10ac2014-08-01 13:20:09 +00002352 << MethodDecl->getReturnTypeSourceRange();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002353 return false;
John McCall071df462010-10-28 02:34:38 +00002354}
2355
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002356static bool CheckMethodOverrideParam(Sema &S,
John McCall071df462010-10-28 02:34:38 +00002357 ObjCMethodDecl *MethodImpl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002358 ObjCMethodDecl *MethodDecl,
John McCall071df462010-10-28 02:34:38 +00002359 ParmVarDecl *ImplVar,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002360 ParmVarDecl *IfaceVar,
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002361 bool IsProtocolMethodDecl,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002362 bool IsOverridingMode,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002363 bool Warn) {
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002364 if (IsProtocolMethodDecl &&
Douglas Gregor813a0662015-06-19 18:14:38 +00002365 objcModifiersConflict(ImplVar->getObjCDeclQualifier(),
2366 IfaceVar->getObjCDeclQualifier())) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002367 if (Warn) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002368 if (IsOverridingMode)
2369 S.Diag(ImplVar->getLocation(),
2370 diag::warn_conflicting_overriding_param_modifiers)
2371 << getTypeRange(ImplVar->getTypeSourceInfo())
2372 << MethodImpl->getDeclName();
2373 else S.Diag(ImplVar->getLocation(),
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002374 diag::warn_conflicting_param_modifiers)
2375 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002376 << MethodImpl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002377 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
2378 << getTypeRange(IfaceVar->getTypeSourceInfo());
2379 }
2380 else
2381 return false;
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002382 }
2383
John McCall071df462010-10-28 02:34:38 +00002384 QualType ImplTy = ImplVar->getType();
2385 QualType IfaceTy = IfaceVar->getType();
Douglas Gregor813a0662015-06-19 18:14:38 +00002386 if (Warn && IsOverridingMode &&
2387 !isa<ObjCImplementationDecl>(MethodImpl->getDeclContext()) &&
2388 !S.Context.hasSameNullabilityTypeQualifier(ImplTy, IfaceTy, true)) {
Douglas Gregor813a0662015-06-19 18:14:38 +00002389 S.Diag(ImplVar->getLocation(),
2390 diag::warn_conflicting_nullability_attr_overriding_param_types)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00002391 << DiagNullabilityKind(
2392 *ImplTy->getNullability(S.Context),
2393 ((ImplVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2394 != 0))
2395 << DiagNullabilityKind(
2396 *IfaceTy->getNullability(S.Context),
2397 ((IfaceVar->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability)
2398 != 0));
2399 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration);
Douglas Gregor813a0662015-06-19 18:14:38 +00002400 }
John McCall071df462010-10-28 02:34:38 +00002401 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002402 return true;
Manman Renc5705ba2016-09-13 17:41:05 +00002403
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002404 if (!Warn)
2405 return false;
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002406 unsigned DiagID =
2407 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
2408 : diag::warn_conflicting_param_types;
John McCall071df462010-10-28 02:34:38 +00002409
2410 // Mismatches between ObjC pointers go into a different warning
2411 // category, and sometimes they're even completely whitelisted.
2412 if (const ObjCObjectPointerType *ImplPtrTy =
2413 ImplTy->getAs<ObjCObjectPointerType>()) {
2414 if (const ObjCObjectPointerType *IfacePtrTy =
2415 IfaceTy->getAs<ObjCObjectPointerType>()) {
2416 // Allow non-matching argument types as long as they don't
2417 // violate the principle of substitutability. Specifically, the
2418 // implementation must accept any objects that the superclass
2419 // accepts, however it may also accept others.
2420 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002421 return false;
John McCall071df462010-10-28 02:34:38 +00002422
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002423 DiagID =
2424 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002425 : diag::warn_non_contravariant_param_types;
John McCall071df462010-10-28 02:34:38 +00002426 }
2427 }
2428
2429 S.Diag(ImplVar->getLocation(), DiagID)
2430 << getTypeRange(ImplVar->getTypeSourceInfo())
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002431 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
2432 S.Diag(IfaceVar->getLocation(),
2433 (IsOverridingMode ? diag::note_previous_declaration
Craig Topper8f7f3ea2015-11-17 05:40:05 +00002434 : diag::note_previous_definition))
John McCall071df462010-10-28 02:34:38 +00002435 << getTypeRange(IfaceVar->getTypeSourceInfo());
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002436 return false;
John McCall071df462010-10-28 02:34:38 +00002437}
John McCall31168b02011-06-15 23:02:42 +00002438
2439/// In ARC, check whether the conventional meanings of the two methods
2440/// match. If they don't, it's a hard error.
2441static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
2442 ObjCMethodDecl *decl) {
2443 ObjCMethodFamily implFamily = impl->getMethodFamily();
2444 ObjCMethodFamily declFamily = decl->getMethodFamily();
2445 if (implFamily == declFamily) return false;
2446
2447 // Since conventions are sorted by selector, the only possibility is
2448 // that the types differ enough to cause one selector or the other
2449 // to fall out of the family.
2450 assert(implFamily == OMF_None || declFamily == OMF_None);
2451
2452 // No further diagnostics required on invalid declarations.
2453 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
2454
2455 const ObjCMethodDecl *unmatched = impl;
2456 ObjCMethodFamily family = declFamily;
2457 unsigned errorID = diag::err_arc_lost_method_convention;
2458 unsigned noteID = diag::note_arc_lost_method_convention;
2459 if (declFamily == OMF_None) {
2460 unmatched = decl;
2461 family = implFamily;
2462 errorID = diag::err_arc_gained_method_convention;
2463 noteID = diag::note_arc_gained_method_convention;
2464 }
2465
2466 // Indexes into a %select clause in the diagnostic.
2467 enum FamilySelector {
2468 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
2469 };
2470 FamilySelector familySelector = FamilySelector();
2471
2472 switch (family) {
2473 case OMF_None: llvm_unreachable("logic error, no method convention");
2474 case OMF_retain:
2475 case OMF_release:
2476 case OMF_autorelease:
2477 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00002478 case OMF_finalize:
John McCall31168b02011-06-15 23:02:42 +00002479 case OMF_retainCount:
2480 case OMF_self:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00002481 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00002482 case OMF_performSelector:
John McCall31168b02011-06-15 23:02:42 +00002483 // Mismatches for these methods don't change ownership
2484 // conventions, so we don't care.
2485 return false;
2486
2487 case OMF_init: familySelector = F_init; break;
2488 case OMF_alloc: familySelector = F_alloc; break;
2489 case OMF_copy: familySelector = F_copy; break;
2490 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
2491 case OMF_new: familySelector = F_new; break;
2492 }
2493
2494 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
2495 ReasonSelector reasonSelector;
2496
2497 // The only reason these methods don't fall within their families is
2498 // due to unusual result types.
Alp Toker314cc812014-01-25 16:55:45 +00002499 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
John McCall31168b02011-06-15 23:02:42 +00002500 reasonSelector = R_UnrelatedReturn;
2501 } else {
2502 reasonSelector = R_NonObjectReturn;
2503 }
2504
Joerg Sonnenbergerffc6d492013-06-26 21:31:47 +00002505 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
2506 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
John McCall31168b02011-06-15 23:02:42 +00002507
2508 return true;
2509}
John McCall071df462010-10-28 02:34:38 +00002510
Fariborz Jahanian7988d7d2008-12-05 18:18:52 +00002511void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002512 ObjCMethodDecl *MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002513 bool IsProtocolMethodDecl) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00002514 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00002515 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
2516 return;
2517
Fariborz Jahaniand7b0cb52011-02-21 23:49:15 +00002518 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002519 IsProtocolMethodDecl, false,
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002520 true);
Mike Stump11289f42009-09-09 15:08:12 +00002521
Chris Lattner67f35b02009-04-11 19:58:42 +00002522 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002523 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2524 EF = MethodDecl->param_end();
2525 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002526 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002527 IsProtocolMethodDecl, false, true);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002528 }
Fariborz Jahanian3c12dd72011-08-10 17:16:30 +00002529
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002530 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002531 Diag(ImpMethodDecl->getLocation(),
2532 diag::warn_conflicting_variadic);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002533 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002534 }
Fariborz Jahanian5ac085a2011-08-08 18:03:17 +00002535}
2536
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002537void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
2538 ObjCMethodDecl *Overridden,
2539 bool IsProtocolMethodDecl) {
2540
2541 CheckMethodOverrideReturn(*this, Method, Overridden,
2542 IsProtocolMethodDecl, true,
2543 true);
2544
2545 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002546 IF = Overridden->param_begin(), EM = Method->param_end(),
2547 EF = Overridden->param_end();
2548 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9a81f842011-10-10 17:53:29 +00002549 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
2550 IsProtocolMethodDecl, true, true);
2551 }
2552
2553 if (Method->isVariadic() != Overridden->isVariadic()) {
2554 Diag(Method->getLocation(),
2555 diag::warn_conflicting_overriding_variadic);
2556 Diag(Overridden->getLocation(), diag::note_previous_declaration);
2557 }
2558}
2559
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002560/// WarnExactTypedMethods - This routine issues a warning if method
2561/// implementation declaration matches exactly that of its declaration.
2562void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
2563 ObjCMethodDecl *MethodDecl,
2564 bool IsProtocolMethodDecl) {
2565 // don't issue warning when protocol method is optional because primary
2566 // class is not required to implement it and it is safe for protocol
2567 // to implement it.
2568 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
2569 return;
2570 // don't issue warning when primary class's method is
2571 // depecated/unavailable.
2572 if (MethodDecl->hasAttr<UnavailableAttr>() ||
2573 MethodDecl->hasAttr<DeprecatedAttr>())
2574 return;
2575
2576 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
2577 IsProtocolMethodDecl, false, false);
2578 if (match)
2579 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
Douglas Gregor0bf70f42012-05-17 23:13:29 +00002580 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
2581 EF = MethodDecl->param_end();
2582 IM != EM && IF != EF; ++IM, ++IF) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002583 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
2584 *IM, *IF,
2585 IsProtocolMethodDecl, false, false);
2586 if (!match)
2587 break;
2588 }
2589 if (match)
2590 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
David Chisnall92918512011-08-08 17:32:19 +00002591 if (match)
2592 match = !(MethodDecl->isClassMethod() &&
2593 MethodDecl->getSelector() == GetNullarySelector("load", Context));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002594
2595 if (match) {
2596 Diag(ImpMethodDecl->getLocation(),
2597 diag::warn_category_method_impl_match);
Ted Kremenek59b10db2012-02-27 22:55:11 +00002598 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
2599 << MethodDecl->getDeclName();
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002600 }
2601}
2602
Mike Stump87c57ac2009-05-16 07:39:55 +00002603/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
2604/// improve the efficiency of selector lookups and type checking by associating
2605/// with each protocol / interface / category the flattened instance tables. If
2606/// we used an immutable set to keep the table then it wouldn't add significant
2607/// memory cost and it would be handy for lookups.
Daniel Dunbar4684f372008-08-27 05:40:03 +00002608
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002609typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002610typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002611
2612static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
2613 ProtocolNameSet &PNS) {
2614 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
2615 PNS.insert(PDecl->getIdentifier());
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002616 for (const auto *PI : PDecl->protocols())
2617 findProtocolsWithExplicitImpls(PI, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002618}
2619
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002620/// Recursively populates a set with all conformed protocols in a class
2621/// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
2622/// attribute.
2623static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
2624 ProtocolNameSet &PNS) {
2625 if (!Super)
2626 return;
2627
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002628 for (const auto *I : Super->all_referenced_protocols())
2629 findProtocolsWithExplicitImpls(I, PNS);
Ted Kremenek760a2ac2014-03-05 23:18:22 +00002630
2631 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002632}
2633
Steve Naroffa36992242008-02-08 22:06:17 +00002634/// CheckProtocolMethodDefs - This routine checks unimplemented methods
Chris Lattnerda463fe2007-12-12 07:09:47 +00002635/// Declared in protocol, and those referenced by it.
Ted Kremenek285ee852013-12-13 06:26:10 +00002636static void CheckProtocolMethodDefs(Sema &S,
2637 SourceLocation ImpLoc,
2638 ObjCProtocolDecl *PDecl,
2639 bool& IncompleteImpl,
2640 const Sema::SelectorSet &InsMap,
2641 const Sema::SelectorSet &ClsMap,
Ted Kremenek33e430f2013-12-13 06:26:14 +00002642 ObjCContainerDecl *CDecl,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002643 LazyProtocolNameSet &ProtocolsExplictImpl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002644 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
2645 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
2646 : dyn_cast<ObjCInterfaceDecl>(CDecl);
Fariborz Jahanian2e8074b2010-03-27 21:10:05 +00002647 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
2648
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002649 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
Craig Topperc3ec1492014-05-26 06:22:03 +00002650 ObjCInterfaceDecl *NSIDecl = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002651
2652 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
2653 // then we should check if any class in the super class hierarchy also
2654 // conforms to this protocol, either directly or via protocol inheritance.
2655 // If so, we can skip checking this protocol completely because we
2656 // know that a parent class already satisfies this protocol.
2657 //
2658 // Note: we could generalize this logic for all protocols, and merely
2659 // add the limit on looking at the super class chain for just
2660 // specially marked protocols. This may be a good optimization. This
2661 // change is restricted to 'objc_protocol_requires_explicit_implementation'
2662 // protocols for now for controlled evaluation.
2663 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
Ahmed Charlesaf94d562014-03-09 11:34:25 +00002664 if (!ProtocolsExplictImpl) {
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002665 ProtocolsExplictImpl.reset(new ProtocolNameSet);
2666 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
2667 }
2668 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
2669 ProtocolsExplictImpl->end())
2670 return;
2671
2672 // If no super class conforms to the protocol, we should not search
2673 // for methods in the super class to implicitly satisfy the protocol.
Craig Topperc3ec1492014-05-26 06:22:03 +00002674 Super = nullptr;
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002675 }
2676
Ted Kremenek285ee852013-12-13 06:26:10 +00002677 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
Mike Stump11289f42009-09-09 15:08:12 +00002678 // check to see if class implements forwardInvocation method and objects
2679 // of this class are derived from 'NSProxy' so that to forward requests
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002680 // from one object to another.
Mike Stump11289f42009-09-09 15:08:12 +00002681 // Under such conditions, which means that every method possible is
2682 // implemented in the class, we should not issue "Method definition not
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002683 // found" warnings.
2684 // FIXME: Use a general GetUnarySelector method for this.
Ted Kremenek285ee852013-12-13 06:26:10 +00002685 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
2686 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002687 if (InsMap.count(fISelector))
2688 // Is IDecl derived from 'NSProxy'? If so, no instance methods
2689 // need be implemented in the implementation.
Ted Kremenek285ee852013-12-13 06:26:10 +00002690 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002691 }
Mike Stump11289f42009-09-09 15:08:12 +00002692
Fariborz Jahanianc41cf052013-01-07 19:21:03 +00002693 // If this is a forward protocol declaration, get its definition.
2694 if (!PDecl->isThisDeclarationADefinition() &&
2695 PDecl->getDefinition())
2696 PDecl = PDecl->getDefinition();
2697
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002698 // If a method lookup fails locally we still need to look and see if
2699 // the method was implemented by a base class or an inherited
2700 // protocol. This lookup is slow, but occurs rarely in correct code
2701 // and otherwise would terminate in a warning.
2702
Chris Lattnerda463fe2007-12-12 07:09:47 +00002703 // check unimplemented instance methods.
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002704 if (!NSIDecl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002705 for (auto *method : PDecl->instance_methods()) {
Mike Stump11289f42009-09-09 15:08:12 +00002706 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
Jordan Rosed01e83a2012-10-10 16:42:25 +00002707 !method->isPropertyAccessor() &&
2708 !InsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002709 (!Super || !Super->lookupMethod(method->getSelector(),
2710 true /* instance */,
2711 false /* shallowCategory */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002712 true /* followsSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002713 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002714 // If a method is not implemented in the category implementation but
2715 // has been declared in its primary class, superclass,
2716 // or in one of their protocols, no need to issue the warning.
2717 // This is because method will be implemented in the primary class
2718 // or one of its super class implementation.
2719
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002720 // Ugly, but necessary. Method declared in protcol might have
2721 // have been synthesized due to a property declared in the class which
2722 // uses the protocol.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002723 if (ObjCMethodDecl *MethodInClass =
Ted Kremenek00781502013-11-23 01:01:29 +00002724 IDecl->lookupMethod(method->getSelector(),
2725 true /* instance */,
2726 true /* shallowCategoryLookup */,
2727 false /* followSuper */))
Jordan Rosed01e83a2012-10-10 16:42:25 +00002728 if (C || MethodInClass->isPropertyAccessor())
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002729 continue;
2730 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002731 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002732 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
Ted Kremenek2ccf19e2013-12-13 05:58:51 +00002733 PDecl);
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002734 }
Fariborz Jahaniandb3a4c12009-05-22 17:12:32 +00002735 }
2736 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00002737 // check unimplemented class methods
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002738 for (auto *method : PDecl->class_methods()) {
Daniel Dunbarc7dfbfd2008-09-04 20:01:15 +00002739 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
2740 !ClsMap.count(method->getSelector()) &&
Ted Kremenek00781502013-11-23 01:01:29 +00002741 (!Super || !Super->lookupMethod(method->getSelector(),
2742 false /* class method */,
2743 false /* shallowCategoryLookup */,
Ted Kremenek28eace62013-11-23 01:01:34 +00002744 true /* followSuper */,
Craig Topperc3ec1492014-05-26 06:22:03 +00002745 nullptr /* category */))) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002746 // See above comment for instance method lookups.
Ted Kremenek00781502013-11-23 01:01:29 +00002747 if (C && IDecl->lookupMethod(method->getSelector(),
2748 false /* class */,
2749 true /* shallowCategoryLookup */,
2750 false /* followSuper */))
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002751 continue;
Ted Kremenek00781502013-11-23 01:01:29 +00002752
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002753 unsigned DIAG = diag::warn_unimplemented_protocol_method;
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00002754 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
Ted Kremenek285ee852013-12-13 06:26:10 +00002755 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
Fariborz Jahanianc1fb8622010-03-31 18:23:33 +00002756 }
Fariborz Jahanian97752f72010-03-27 19:02:17 +00002757 }
Steve Naroff3ce37a62007-12-14 23:37:57 +00002758 }
Chris Lattner390d39a2008-07-21 21:32:27 +00002759 // Check on this protocols's referenced protocols, recursively.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002760 for (auto *PI : PDecl->protocols())
2761 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002762 CDecl, ProtocolsExplictImpl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00002763}
2764
Fariborz Jahanianf9ae68a2011-07-16 00:08:33 +00002765/// MatchAllMethodDeclarations - Check methods declared in interface
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002766/// or protocol against those declared in their implementations.
2767///
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002768void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
2769 const SelectorSet &ClsMap,
2770 SelectorSet &InsMapSeen,
2771 SelectorSet &ClsMapSeen,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002772 ObjCImplDecl* IMPDecl,
2773 ObjCContainerDecl* CDecl,
2774 bool &IncompleteImpl,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002775 bool ImmediateClass,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002776 bool WarnCategoryMethodImpl) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002777 // Check and see if instance methods in class interface have been
2778 // implemented in the implementation class. If so, their types match.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002779 for (auto *I : CDecl->instance_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002780 if (!InsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002781 continue;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002782 if (!I->isPropertyAccessor() &&
2783 !InsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002784 if (ImmediateClass)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002785 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002786 diag::warn_undef_method_impl);
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002787 continue;
Mike Stump12b8ce12009-08-04 21:02:39 +00002788 } else {
Mike Stump11289f42009-09-09 15:08:12 +00002789 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002790 IMPDecl->getInstanceMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002791 assert(CDecl->getInstanceMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002792 "Expected to find the method through lookup as well");
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002793 // ImpMethodDecl may be null as in a @dynamic property.
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002794 if (ImpMethodDecl) {
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002795 if (!WarnCategoryMethodImpl)
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002796 WarnConflictingTypedMethods(ImpMethodDecl, I,
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002797 isa<ObjCProtocolDecl>(CDecl));
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002798 else if (!I->isPropertyAccessor())
2799 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002800 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002801 }
2802 }
Mike Stump11289f42009-09-09 15:08:12 +00002803
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002804 // Check and see if class methods in class interface have been
2805 // implemented in the implementation class. If so, their types match.
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002806 for (auto *I : CDecl->class_methods()) {
David Blaikie82e95a32014-11-19 07:49:47 +00002807 if (!ClsMapSeen.insert(I->getSelector()).second)
Benjamin Kramer9f8e2d72013-10-14 15:16:10 +00002808 continue;
Manman Rend36f7d52016-01-27 20:10:32 +00002809 if (!I->isPropertyAccessor() &&
2810 !ClsMap.count(I->getSelector())) {
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002811 if (ImmediateClass)
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002812 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
Ted Kremenek65d63572013-03-27 00:02:21 +00002813 diag::warn_undef_method_impl);
Mike Stump12b8ce12009-08-04 21:02:39 +00002814 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00002815 ObjCMethodDecl *ImpMethodDecl =
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002816 IMPDecl->getClassMethod(I->getSelector());
Manman Rena58f92f2016-10-11 21:18:20 +00002817 assert(CDecl->getClassMethod(I->getSelector(), true/*AllowHidden*/) &&
Argyrios Kyrtzidis342e08f2011-08-30 19:43:21 +00002818 "Expected to find the method through lookup as well");
Manman Rend36f7d52016-01-27 20:10:32 +00002819 // ImpMethodDecl may be null as in a @dynamic property.
2820 if (ImpMethodDecl) {
2821 if (!WarnCategoryMethodImpl)
2822 WarnConflictingTypedMethods(ImpMethodDecl, I,
2823 isa<ObjCProtocolDecl>(CDecl));
2824 else if (!I->isPropertyAccessor())
2825 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
2826 }
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002827 }
2828 }
Fariborz Jahanian73853e52010-10-08 22:59:25 +00002829
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002830 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
2831 // Also, check for methods declared in protocols inherited by
2832 // this protocol.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002833 for (auto *PI : PD->protocols())
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002834 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00002835 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian8181caa2013-08-14 23:58:55 +00002836 WarnCategoryMethodImpl);
2837 }
2838
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002839 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002840 // when checking that methods in implementation match their declaration,
2841 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
2842 // extension; as well as those in categories.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002843 if (!WarnCategoryMethodImpl) {
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002844 for (auto *Cat : I->visible_categories())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002845 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Argyrios Kyrtzidis3a437542015-10-13 23:27:34 +00002846 IMPDecl, Cat, IncompleteImpl,
2847 ImmediateClass && Cat->IsClassExtension(),
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002848 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002849 } else {
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002850 // Also methods in class extensions need be looked at next.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002851 for (auto *Ext : I->visible_extensions())
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002852 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00002853 IMPDecl, Ext, IncompleteImpl, false,
Fariborz Jahanian6f5309c2012-10-23 23:06:22 +00002854 WarnCategoryMethodImpl);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00002855 }
2856
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002857 // Check for any implementation of a methods declared in protocol.
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002858 for (auto *PI : I->all_referenced_protocols())
Mike Stump11289f42009-09-09 15:08:12 +00002859 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002860 IMPDecl, PI, IncompleteImpl, false,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002861 WarnCategoryMethodImpl);
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002862
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002863 // FIXME. For now, we are not checking for extact match of methods
2864 // in category implementation and its primary class's super class.
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002865 if (!WarnCategoryMethodImpl && I->getSuperClass())
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002866 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
Mike Stump11289f42009-09-09 15:08:12 +00002867 IMPDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002868 I->getSuperClass(), IncompleteImpl, false);
2869 }
2870}
2871
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002872/// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
2873/// category matches with those implemented in its primary class and
2874/// warns each time an exact match is found.
2875void Sema::CheckCategoryVsClassMethodMatches(
2876 ObjCCategoryImplDecl *CatIMPDecl) {
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002877 // Get category's primary class.
2878 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
2879 if (!CatDecl)
2880 return;
2881 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
2882 if (!IDecl)
2883 return;
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002884 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
2885 SelectorSet InsMap, ClsMap;
2886
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002887 for (const auto *I : CatIMPDecl->instance_methods()) {
2888 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002889 // When checking for methods implemented in the category, skip over
2890 // those declared in category class's super class. This is because
2891 // the super class must implement the method.
2892 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
2893 continue;
2894 InsMap.insert(Sel);
2895 }
2896
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002897 for (const auto *I : CatIMPDecl->class_methods()) {
2898 Selector Sel = I->getSelector();
Fariborz Jahanianf3077a22013-12-05 20:52:31 +00002899 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
2900 continue;
2901 ClsMap.insert(Sel);
2902 }
2903 if (InsMap.empty() && ClsMap.empty())
2904 return;
2905
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002906 SelectorSet InsMapSeen, ClsMapSeen;
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002907 bool IncompleteImpl = false;
2908 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2909 CatIMPDecl, IDecl,
Fariborz Jahanian29082a52012-02-09 21:30:24 +00002910 IncompleteImpl, false,
2911 true /*WarnCategoryMethodImpl*/);
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002912}
Fariborz Jahanian4ceec3f2011-07-24 20:53:26 +00002913
Fariborz Jahanian25491a22010-05-05 21:52:17 +00002914void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002915 ObjCContainerDecl* CDecl,
Chris Lattner9ef10f42009-03-01 00:56:52 +00002916 bool IncompleteImpl) {
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002917 SelectorSet InsMap;
Chris Lattnerda463fe2007-12-12 07:09:47 +00002918 // Check and see if instance methods in class interface have been
2919 // implemented in the implementation class.
Aaron Ballmanf26acce2014-03-13 19:50:17 +00002920 for (const auto *I : IMPDecl->instance_methods())
2921 InsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002922
Douglas Gregoracf4fd32015-11-03 01:15:46 +00002923 // Add the selectors for getters/setters of @dynamic properties.
2924 for (const auto *PImpl : IMPDecl->property_impls()) {
2925 // We only care about @dynamic implementations.
2926 if (PImpl->getPropertyImplementation() != ObjCPropertyImplDecl::Dynamic)
2927 continue;
2928
2929 const auto *P = PImpl->getPropertyDecl();
2930 if (!P) continue;
2931
2932 InsMap.insert(P->getGetterName());
2933 if (!P->getSetterName().isNull())
2934 InsMap.insert(P->getSetterName());
2935 }
2936
Fariborz Jahanian6c6aea92009-04-14 23:15:21 +00002937 // Check and see if properties declared in the interface have either 1)
2938 // an implementation or 2) there is a @synthesize/@dynamic implementation
2939 // of the property in the @implementation.
Ted Kremenek348e88c2014-02-21 19:41:34 +00002940 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
2941 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
2942 LangOpts.ObjCRuntime.isNonFragile() &&
2943 !IDecl->isObjCRequiresPropertyDefs();
2944 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
2945 }
2946
Douglas Gregor849ebc22015-06-19 18:14:46 +00002947 // Diagnose null-resettable synthesized setters.
2948 diagnoseNullResettableSynthesizedSetters(IMPDecl);
2949
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002950 SelectorSet ClsMap;
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00002951 for (const auto *I : IMPDecl->class_methods())
2952 ClsMap.insert(I->getSelector());
Mike Stump11289f42009-09-09 15:08:12 +00002953
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002954 // Check for type conflict of methods declared in a class/protocol and
2955 // its implementation; if any.
Benjamin Kramerb33ffee2012-05-27 13:28:52 +00002956 SelectorSet InsMapSeen, ClsMapSeen;
Mike Stump11289f42009-09-09 15:08:12 +00002957 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2958 IMPDecl, CDecl,
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002959 IncompleteImpl, true);
Fariborz Jahanian2bda1b62011-08-03 18:21:12 +00002960
Fariborz Jahanian9f8b19e2011-07-28 23:19:50 +00002961 // check all methods implemented in category against those declared
2962 // in its primary class.
2963 if (ObjCCategoryImplDecl *CatDecl =
2964 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2965 CheckCategoryVsClassMethodMatches(CatDecl);
Mike Stump11289f42009-09-09 15:08:12 +00002966
Chris Lattnerda463fe2007-12-12 07:09:47 +00002967 // Check the protocol list for unimplemented methods in the @implementation
2968 // class.
Fariborz Jahanian07b71652009-05-01 20:07:12 +00002969 // Check and see if class methods in class interface have been
2970 // implemented in the implementation class.
Mike Stump11289f42009-09-09 15:08:12 +00002971
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002972 LazyProtocolNameSet ExplicitImplProtocols;
2973
Chris Lattner9ef10f42009-03-01 00:56:52 +00002974 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
Aaron Ballmana9f49e32014-03-13 20:55:22 +00002975 for (auto *PI : I->all_referenced_protocols())
2976 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
2977 InsMap, ClsMap, I, ExplicitImplProtocols);
Chris Lattner9ef10f42009-03-01 00:56:52 +00002978 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
Fariborz Jahanian8764c742009-10-05 21:32:49 +00002979 // For extended class, unimplemented methods in its protocols will
2980 // be reported in the primary class.
Fariborz Jahanian30a42922010-02-15 21:55:26 +00002981 if (!C->IsClassExtension()) {
Aaron Ballman19a41762014-03-14 12:55:57 +00002982 for (auto *P : C->protocols())
2983 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
Ted Kremenek4b3c66e2014-03-05 08:13:08 +00002984 IncompleteImpl, InsMap, ClsMap, CDecl,
2985 ExplicitImplProtocols);
Ted Kremenek348e88c2014-02-21 19:41:34 +00002986 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
Nico Weber2e0c8f72014-12-27 03:58:08 +00002987 /*SynthesizeProperties=*/false);
Fariborz Jahanian4f8a5712010-01-20 19:36:21 +00002988 }
Chris Lattner9ef10f42009-03-01 00:56:52 +00002989 } else
David Blaikie83d382b2011-09-23 05:06:16 +00002990 llvm_unreachable("invalid ObjCContainerDecl type.");
Chris Lattnerda463fe2007-12-12 07:09:47 +00002991}
2992
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002993Sema::DeclGroupPtrTy
Chris Lattnerda463fe2007-12-12 07:09:47 +00002994Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
Chris Lattner99a83312009-02-16 19:25:52 +00002995 IdentifierInfo **IdentList,
Ted Kremeneka26da852009-11-17 23:12:20 +00002996 SourceLocation *IdentLocs,
Douglas Gregor85f3f952015-07-07 03:57:15 +00002997 ArrayRef<ObjCTypeParamList *> TypeParamLists,
Chris Lattner99a83312009-02-16 19:25:52 +00002998 unsigned NumElts) {
Fariborz Jahanian3a039e32011-08-27 20:50:59 +00002999 SmallVector<Decl *, 8> DeclsInGroup;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003000 for (unsigned i = 0; i != NumElts; ++i) {
3001 // Check for another declaration kind with the same name.
John McCall9f3059a2009-10-09 21:13:30 +00003002 NamedDecl *PrevDecl
Douglas Gregorb2ccf012010-04-15 22:33:43 +00003003 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
Richard Smithbecb92d2017-10-10 22:33:17 +00003004 LookupOrdinaryName, forRedeclarationInCurContext());
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003005 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
Steve Naroff946166f2008-06-05 22:57:10 +00003006 // GCC apparently allows the following idiom:
3007 //
3008 // typedef NSObject < XCElementTogglerP > XCElementToggler;
3009 // @class XCElementToggler;
3010 //
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003011 // Here we have chosen to ignore the forward class declaration
3012 // with a warning. Since this is the implied behavior.
Richard Smithdda56e42011-04-15 14:24:37 +00003013 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
John McCall8b07ec22010-05-15 11:32:37 +00003014 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003015 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
Chris Lattner0369c572008-11-23 23:12:31 +00003016 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
John McCall8b07ec22010-05-15 11:32:37 +00003017 } else {
Mike Stump12b8ce12009-08-04 21:02:39 +00003018 // a forward class declaration matching a typedef name of a class refers
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003019 // to the underlying class. Just ignore the forward class with a warning
Nico Weber2e0c8f72014-12-27 03:58:08 +00003020 // as this will force the intended behavior which is to lookup the
3021 // typedef name.
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003022 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003023 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
3024 << IdentList[i];
Fariborz Jahanian04c44552012-01-24 00:40:15 +00003025 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
3026 continue;
3027 }
Fariborz Jahanian0d451812009-05-07 21:49:26 +00003028 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003029 }
Douglas Gregordc9166c2011-12-15 20:29:51 +00003030
3031 // Create a declaration to describe this forward declaration.
Douglas Gregorab1ec82e2011-12-16 03:12:41 +00003032 ObjCInterfaceDecl *PrevIDecl
3033 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
Argyrios Kyrtzidisdd710632013-06-18 21:26:33 +00003034
3035 IdentifierInfo *ClassName = IdentList[i];
3036 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
3037 // A previous decl with a different name is because of
3038 // @compatibility_alias, for example:
3039 // \code
3040 // @class NewImage;
3041 // @compatibility_alias OldImage NewImage;
3042 // \endcode
3043 // A lookup for 'OldImage' will return the 'NewImage' decl.
3044 //
3045 // In such a case use the real declaration name, instead of the alias one,
3046 // otherwise we will break IdentifierResolver and redecls-chain invariants.
3047 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
3048 // has been aliased.
3049 ClassName = PrevIDecl->getIdentifier();
3050 }
3051
Douglas Gregor85f3f952015-07-07 03:57:15 +00003052 // If this forward declaration has type parameters, compare them with the
3053 // type parameters of the previous declaration.
3054 ObjCTypeParamList *TypeParams = TypeParamLists[i];
3055 if (PrevIDecl && TypeParams) {
3056 if (ObjCTypeParamList *PrevTypeParams = PrevIDecl->getTypeParamList()) {
3057 // Check for consistency with the previous declaration.
3058 if (checkTypeParamListConsistency(
3059 *this, PrevTypeParams, TypeParams,
3060 TypeParamListContext::ForwardDeclaration)) {
3061 TypeParams = nullptr;
3062 }
3063 } else if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
3064 // The @interface does not have type parameters. Complain.
3065 Diag(IdentLocs[i], diag::err_objc_parameterized_forward_class)
3066 << ClassName
3067 << TypeParams->getSourceRange();
3068 Diag(Def->getLocation(), diag::note_defined_here)
3069 << ClassName;
3070
3071 TypeParams = nullptr;
3072 }
3073 }
3074
Douglas Gregordc9166c2011-12-15 20:29:51 +00003075 ObjCInterfaceDecl *IDecl
3076 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
Douglas Gregor85f3f952015-07-07 03:57:15 +00003077 ClassName, TypeParams, PrevIDecl,
3078 IdentLocs[i]);
Douglas Gregordc9166c2011-12-15 20:29:51 +00003079 IDecl->setAtEndRange(IdentLocs[i]);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00003080
Douglas Gregordc9166c2011-12-15 20:29:51 +00003081 PushOnScopeChains(IDecl, TUScope);
Douglas Gregordeafd0b2011-12-27 22:43:10 +00003082 CheckObjCDeclScope(IDecl);
3083 DeclsInGroup.push_back(IDecl);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003084 }
Rafael Espindolaab417692013-07-09 12:05:01 +00003085
Richard Smith3beb7c62017-01-12 02:27:38 +00003086 return BuildDeclaratorGroup(DeclsInGroup);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003087}
3088
John McCall54507ab2011-06-16 01:15:19 +00003089static bool tryMatchRecordTypes(ASTContext &Context,
3090 Sema::MethodMatchStrategy strategy,
3091 const Type *left, const Type *right);
3092
John McCall31168b02011-06-15 23:02:42 +00003093static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
3094 QualType leftQT, QualType rightQT) {
3095 const Type *left =
3096 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
3097 const Type *right =
3098 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
3099
3100 if (left == right) return true;
3101
3102 // If we're doing a strict match, the types have to match exactly.
3103 if (strategy == Sema::MMS_strict) return false;
3104
3105 if (left->isIncompleteType() || right->isIncompleteType()) return false;
3106
3107 // Otherwise, use this absurdly complicated algorithm to try to
3108 // validate the basic, low-level compatibility of the two types.
3109
3110 // As a minimum, require the sizes and alignments to match.
David Majnemer34b57492014-07-30 01:30:47 +00003111 TypeInfo LeftTI = Context.getTypeInfo(left);
3112 TypeInfo RightTI = Context.getTypeInfo(right);
3113 if (LeftTI.Width != RightTI.Width)
3114 return false;
3115
3116 if (LeftTI.Align != RightTI.Align)
John McCall31168b02011-06-15 23:02:42 +00003117 return false;
3118
3119 // Consider all the kinds of non-dependent canonical types:
3120 // - functions and arrays aren't possible as return and parameter types
3121
3122 // - vector types of equal size can be arbitrarily mixed
3123 if (isa<VectorType>(left)) return isa<VectorType>(right);
3124 if (isa<VectorType>(right)) return false;
3125
3126 // - references should only match references of identical type
John McCall54507ab2011-06-16 01:15:19 +00003127 // - structs, unions, and Objective-C objects must match more-or-less
3128 // exactly
John McCall31168b02011-06-15 23:02:42 +00003129 // - everything else should be a scalar
3130 if (!left->isScalarType() || !right->isScalarType())
John McCall54507ab2011-06-16 01:15:19 +00003131 return tryMatchRecordTypes(Context, strategy, left, right);
John McCall31168b02011-06-15 23:02:42 +00003132
John McCall9320b872011-09-09 05:25:32 +00003133 // Make scalars agree in kind, except count bools as chars, and group
3134 // all non-member pointers together.
John McCall31168b02011-06-15 23:02:42 +00003135 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
3136 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
3137 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
3138 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
John McCall9320b872011-09-09 05:25:32 +00003139 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
3140 leftSK = Type::STK_ObjCObjectPointer;
3141 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
3142 rightSK = Type::STK_ObjCObjectPointer;
John McCall31168b02011-06-15 23:02:42 +00003143
3144 // Note that data member pointers and function member pointers don't
3145 // intermix because of the size differences.
3146
3147 return (leftSK == rightSK);
3148}
Chris Lattnerda463fe2007-12-12 07:09:47 +00003149
John McCall54507ab2011-06-16 01:15:19 +00003150static bool tryMatchRecordTypes(ASTContext &Context,
3151 Sema::MethodMatchStrategy strategy,
3152 const Type *lt, const Type *rt) {
3153 assert(lt && rt && lt != rt);
3154
3155 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
3156 RecordDecl *left = cast<RecordType>(lt)->getDecl();
3157 RecordDecl *right = cast<RecordType>(rt)->getDecl();
3158
3159 // Require union-hood to match.
3160 if (left->isUnion() != right->isUnion()) return false;
3161
3162 // Require an exact match if either is non-POD.
3163 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
3164 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
3165 return false;
3166
3167 // Require size and alignment to match.
David Majnemer34b57492014-07-30 01:30:47 +00003168 TypeInfo LeftTI = Context.getTypeInfo(lt);
3169 TypeInfo RightTI = Context.getTypeInfo(rt);
3170 if (LeftTI.Width != RightTI.Width)
3171 return false;
3172
3173 if (LeftTI.Align != RightTI.Align)
3174 return false;
John McCall54507ab2011-06-16 01:15:19 +00003175
3176 // Require fields to match.
3177 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
3178 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
3179 for (; li != le && ri != re; ++li, ++ri) {
3180 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
3181 return false;
3182 }
3183 return (li == le && ri == re);
3184}
3185
Chris Lattnerda463fe2007-12-12 07:09:47 +00003186/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
3187/// returns true, or false, accordingly.
3188/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
John McCall31168b02011-06-15 23:02:42 +00003189bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
3190 const ObjCMethodDecl *right,
3191 MethodMatchStrategy strategy) {
Alp Toker314cc812014-01-25 16:55:45 +00003192 if (!matchTypes(Context, strategy, left->getReturnType(),
3193 right->getReturnType()))
John McCall31168b02011-06-15 23:02:42 +00003194 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003195
Douglas Gregor560b7fa2013-02-07 19:13:24 +00003196 // If either is hidden, it is not considered to match.
3197 if (left->isHidden() || right->isHidden())
3198 return false;
3199
David Blaikiebbafb8a2012-03-11 07:00:24 +00003200 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003201 (left->hasAttr<NSReturnsRetainedAttr>()
3202 != right->hasAttr<NSReturnsRetainedAttr>() ||
3203 left->hasAttr<NSConsumesSelfAttr>()
3204 != right->hasAttr<NSConsumesSelfAttr>()))
3205 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003206
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003207 ObjCMethodDecl::param_const_iterator
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003208 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
3209 re = right->param_end();
Mike Stump11289f42009-09-09 15:08:12 +00003210
Douglas Gregor0bf70f42012-05-17 23:13:29 +00003211 for (; li != le && ri != re; ++li, ++ri) {
John McCall31168b02011-06-15 23:02:42 +00003212 assert(ri != right->param_end() && "Param mismatch");
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00003213 const ParmVarDecl *lparm = *li, *rparm = *ri;
John McCall31168b02011-06-15 23:02:42 +00003214
3215 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
3216 return false;
3217
David Blaikiebbafb8a2012-03-11 07:00:24 +00003218 if (getLangOpts().ObjCAutoRefCount &&
John McCall31168b02011-06-15 23:02:42 +00003219 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
3220 return false;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003221 }
3222 return true;
3223}
3224
Manman Ren71224532016-04-09 18:59:48 +00003225static bool isMethodContextSameForKindofLookup(ObjCMethodDecl *Method,
3226 ObjCMethodDecl *MethodInList) {
3227 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3228 auto *MethodInListProtocol =
3229 dyn_cast<ObjCProtocolDecl>(MethodInList->getDeclContext());
3230 // If this method belongs to a protocol but the method in list does not, or
3231 // vice versa, we say the context is not the same.
3232 if ((MethodProtocol && !MethodInListProtocol) ||
3233 (!MethodProtocol && MethodInListProtocol))
3234 return false;
3235
3236 if (MethodProtocol && MethodInListProtocol)
3237 return true;
3238
3239 ObjCInterfaceDecl *MethodInterface = Method->getClassInterface();
3240 ObjCInterfaceDecl *MethodInListInterface =
3241 MethodInList->getClassInterface();
3242 return MethodInterface == MethodInListInterface;
3243}
3244
Nico Weber2e0c8f72014-12-27 03:58:08 +00003245void Sema::addMethodToGlobalList(ObjCMethodList *List,
3246 ObjCMethodDecl *Method) {
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003247 // Record at the head of the list whether there were 0, 1, or >= 2 methods
3248 // inside categories.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003249 if (ObjCCategoryDecl *CD =
3250 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00003251 if (!CD->IsClassExtension() && List->getBits() < 2)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003252 List->setBits(List->getBits() + 1);
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003253
Douglas Gregorc454afe2012-01-25 00:19:56 +00003254 // If the list is empty, make it a singleton list.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003255 if (List->getMethod() == nullptr) {
3256 List->setMethod(Method);
Craig Topperc3ec1492014-05-26 06:22:03 +00003257 List->setNext(nullptr);
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003258 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003259 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003260
Douglas Gregorc454afe2012-01-25 00:19:56 +00003261 // We've seen a method with this name, see if we have already seen this type
3262 // signature.
3263 ObjCMethodList *Previous = List;
Manman Ren051d0b62016-04-13 23:43:56 +00003264 ObjCMethodList *ListWithSameDeclaration = nullptr;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003265 for (; List; Previous = List, List = List->getNext()) {
Douglas Gregor600a2f52013-06-21 00:20:25 +00003266 // If we are building a module, keep all of the methods.
Richard Smithbbcc9f02016-08-26 00:14:38 +00003267 if (getLangOpts().isCompilingModule())
Douglas Gregor600a2f52013-06-21 00:20:25 +00003268 continue;
3269
Manman Ren051d0b62016-04-13 23:43:56 +00003270 bool SameDeclaration = MatchTwoMethodDeclarations(Method,
3271 List->getMethod());
Manman Ren71224532016-04-09 18:59:48 +00003272 // Looking for method with a type bound requires the correct context exists.
Manman Ren051d0b62016-04-13 23:43:56 +00003273 // We need to insert a method into the list if the context is different.
3274 // If the method's declaration matches the list
3275 // a> the method belongs to a different context: we need to insert it, in
3276 // order to emit the availability message, we need to prioritize over
3277 // availability among the methods with the same declaration.
3278 // b> the method belongs to the same context: there is no need to insert a
3279 // new entry.
3280 // If the method's declaration does not match the list, we insert it to the
3281 // end.
3282 if (!SameDeclaration ||
Manman Ren71224532016-04-09 18:59:48 +00003283 !isMethodContextSameForKindofLookup(Method, List->getMethod())) {
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003284 // Even if two method types do not match, we would like to say
3285 // there is more than one declaration so unavailability/deprecated
3286 // warning is not too noisy.
3287 if (!Method->isDefined())
3288 List->setHasMoreThanOneDecl(true);
Manman Ren051d0b62016-04-13 23:43:56 +00003289
3290 // For methods with the same declaration, the one that is deprecated
3291 // should be put in the front for better diagnostics.
3292 if (Method->isDeprecated() && SameDeclaration &&
3293 !ListWithSameDeclaration && !List->getMethod()->isDeprecated())
3294 ListWithSameDeclaration = List;
3295
3296 if (Method->isUnavailable() && SameDeclaration &&
3297 !ListWithSameDeclaration &&
3298 List->getMethod()->getAvailability() < AR_Deprecated)
3299 ListWithSameDeclaration = List;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003300 continue;
Fariborz Jahaniand436b2a2015-04-07 16:56:27 +00003301 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003302
3303 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
Douglas Gregorc454afe2012-01-25 00:19:56 +00003304
3305 // Propagate the 'defined' bit.
3306 if (Method->isDefined())
3307 PrevObjCMethod->setDefined(true);
Nico Webere3b11042014-12-27 07:09:37 +00003308 else {
Nico Weber2e0c8f72014-12-27 03:58:08 +00003309 // Objective-C doesn't allow an @interface for a class after its
3310 // @implementation. So if Method is not defined and there already is
3311 // an entry for this type signature, Method has to be for a different
3312 // class than PrevObjCMethod.
3313 List->setHasMoreThanOneDecl(true);
3314 }
3315
Douglas Gregorc454afe2012-01-25 00:19:56 +00003316 // If a method is deprecated, push it in the global pool.
3317 // This is used for better diagnostics.
3318 if (Method->isDeprecated()) {
3319 if (!PrevObjCMethod->isDeprecated())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003320 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003321 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003322 // If the new method is unavailable, push it into global pool
Douglas Gregorc454afe2012-01-25 00:19:56 +00003323 // unless previous one is deprecated.
3324 if (Method->isUnavailable()) {
3325 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003326 List->setMethod(Method);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003327 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003328
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003329 return;
Douglas Gregorc454afe2012-01-25 00:19:56 +00003330 }
Nico Weber2e0c8f72014-12-27 03:58:08 +00003331
Douglas Gregorc454afe2012-01-25 00:19:56 +00003332 // We have a new signature for an existing method - add it.
3333 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
Douglas Gregore1716012012-01-25 00:49:42 +00003334 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
Manman Ren71224532016-04-09 18:59:48 +00003335
Manman Ren051d0b62016-04-13 23:43:56 +00003336 // We insert it right before ListWithSameDeclaration.
3337 if (ListWithSameDeclaration) {
3338 auto *List = new (Mem) ObjCMethodList(*ListWithSameDeclaration);
3339 // FIXME: should we clear the other bits in ListWithSameDeclaration?
3340 ListWithSameDeclaration->setMethod(Method);
3341 ListWithSameDeclaration->setNext(List);
Manman Ren71224532016-04-09 18:59:48 +00003342 return;
3343 }
3344
Nico Weber2e0c8f72014-12-27 03:58:08 +00003345 Previous->setNext(new (Mem) ObjCMethodList(Method));
Douglas Gregorc454afe2012-01-25 00:19:56 +00003346}
3347
Sebastian Redl75d8a322010-08-02 23:18:59 +00003348/// \brief Read the contents of the method pool for a given selector from
3349/// external storage.
Douglas Gregore1716012012-01-25 00:49:42 +00003350void Sema::ReadMethodPool(Selector Sel) {
Douglas Gregorc78d3462009-04-24 21:10:55 +00003351 assert(ExternalSource && "We need an external AST source");
Douglas Gregore1716012012-01-25 00:49:42 +00003352 ExternalSource->ReadMethodPool(Sel);
Douglas Gregorc78d3462009-04-24 21:10:55 +00003353}
3354
Manman Rena0f31a02016-04-29 19:04:05 +00003355void Sema::updateOutOfDateSelector(Selector Sel) {
3356 if (!ExternalSource)
3357 return;
3358 ExternalSource->updateOutOfDateSelector(Sel);
3359}
3360
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003361void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
Sebastian Redl75d8a322010-08-02 23:18:59 +00003362 bool instance) {
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003363 // Ignore methods of invalid containers.
3364 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003365 return;
Argyrios Kyrtzidisb15def22012-03-12 18:34:26 +00003366
Douglas Gregor70f449b2012-01-25 00:59:09 +00003367 if (ExternalSource)
3368 ReadMethodPool(Method->getSelector());
3369
Sebastian Redl75d8a322010-08-02 23:18:59 +00003370 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
Douglas Gregor70f449b2012-01-25 00:59:09 +00003371 if (Pos == MethodPool.end())
3372 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
3373 GlobalMethods())).first;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003374
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003375 Method->setDefined(impl);
Douglas Gregorc454afe2012-01-25 00:19:56 +00003376
Sebastian Redl75d8a322010-08-02 23:18:59 +00003377 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003378 addMethodToGlobalList(&Entry, Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003379}
3380
John McCall31168b02011-06-15 23:02:42 +00003381/// Determines if this is an "acceptable" loose mismatch in the global
3382/// method pool. This exists mostly as a hack to get around certain
3383/// global mismatches which we can't afford to make warnings / errors.
3384/// Really, what we want is a way to take a method out of the global
3385/// method pool.
3386static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
3387 ObjCMethodDecl *other) {
3388 if (!chosen->isInstanceMethod())
3389 return false;
3390
3391 Selector sel = chosen->getSelector();
3392 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
3393 return false;
3394
3395 // Don't complain about mismatches for -length if the method we
3396 // chose has an integral result type.
Alp Toker314cc812014-01-25 16:55:45 +00003397 return (chosen->getReturnType()->isIntegerType());
John McCall31168b02011-06-15 23:02:42 +00003398}
3399
Manman Ren7ed4f982016-04-07 19:32:24 +00003400/// Return true if the given method is wthin the type bound.
3401static bool FilterMethodsByTypeBound(ObjCMethodDecl *Method,
3402 const ObjCObjectType *TypeBound) {
3403 if (!TypeBound)
3404 return true;
3405
3406 if (TypeBound->isObjCId())
3407 // FIXME: should we handle the case of bounding to id<A, B> differently?
3408 return true;
3409
3410 auto *BoundInterface = TypeBound->getInterface();
3411 assert(BoundInterface && "unexpected object type!");
3412
3413 // Check if the Method belongs to a protocol. We should allow any method
3414 // defined in any protocol, because any subclass could adopt the protocol.
3415 auto *MethodProtocol = dyn_cast<ObjCProtocolDecl>(Method->getDeclContext());
3416 if (MethodProtocol) {
3417 return true;
3418 }
3419
3420 // If the Method belongs to a class, check if it belongs to the class
3421 // hierarchy of the class bound.
3422 if (ObjCInterfaceDecl *MethodInterface = Method->getClassInterface()) {
3423 // We allow methods declared within classes that are part of the hierarchy
3424 // of the class bound (superclass of, subclass of, or the same as the class
3425 // bound).
3426 return MethodInterface == BoundInterface ||
3427 MethodInterface->isSuperClassOf(BoundInterface) ||
3428 BoundInterface->isSuperClassOf(MethodInterface);
3429 }
3430 llvm_unreachable("unknow method context");
3431}
3432
Manman Rend2a3cd72016-04-07 19:30:20 +00003433/// We first select the type of the method: Instance or Factory, then collect
3434/// all methods with that type.
Nico Weber2e0c8f72014-12-27 03:58:08 +00003435bool Sema::CollectMultipleMethodsInGlobalPool(
Manman Rend2a3cd72016-04-07 19:30:20 +00003436 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods,
Manman Ren7ed4f982016-04-07 19:32:24 +00003437 bool InstanceFirst, bool CheckTheOther,
3438 const ObjCObjectType *TypeBound) {
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003439 if (ExternalSource)
3440 ReadMethodPool(Sel);
3441
3442 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3443 if (Pos == MethodPool.end())
3444 return false;
Manman Rend2a3cd72016-04-07 19:30:20 +00003445
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003446 // Gather the non-hidden methods.
Manman Rend2a3cd72016-04-07 19:30:20 +00003447 ObjCMethodList &MethList = InstanceFirst ? Pos->second.first :
3448 Pos->second.second;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003449 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003450 if (M->getMethod() && !M->getMethod()->isHidden()) {
3451 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3452 Methods.push_back(M->getMethod());
3453 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003454
3455 // Return if we find any method with the desired kind.
3456 if (!Methods.empty())
3457 return Methods.size() > 1;
3458
3459 if (!CheckTheOther)
3460 return false;
3461
3462 // Gather the other kind.
3463 ObjCMethodList &MethList2 = InstanceFirst ? Pos->second.second :
3464 Pos->second.first;
3465 for (ObjCMethodList *M = &MethList2; M; M = M->getNext())
Manman Ren7ed4f982016-04-07 19:32:24 +00003466 if (M->getMethod() && !M->getMethod()->isHidden()) {
3467 if (FilterMethodsByTypeBound(M->getMethod(), TypeBound))
3468 Methods.push_back(M->getMethod());
3469 }
Manman Rend2a3cd72016-04-07 19:30:20 +00003470
Nico Weber2e0c8f72014-12-27 03:58:08 +00003471 return Methods.size() > 1;
Fariborz Jahanian30ae8d42014-08-13 21:07:35 +00003472}
3473
Manman Rend2a3cd72016-04-07 19:30:20 +00003474bool Sema::AreMultipleMethodsInGlobalPool(
3475 Selector Sel, ObjCMethodDecl *BestMethod, SourceRange R,
3476 bool receiverIdOrClass, SmallVectorImpl<ObjCMethodDecl *> &Methods) {
3477 // Diagnose finding more than one method in global pool.
3478 SmallVector<ObjCMethodDecl *, 4> FilteredMethods;
3479 FilteredMethods.push_back(BestMethod);
3480
3481 for (auto *M : Methods)
3482 if (M != BestMethod && !M->hasAttr<UnavailableAttr>())
3483 FilteredMethods.push_back(M);
3484
3485 if (FilteredMethods.size() > 1)
3486 DiagnoseMultipleMethodInGlobalPool(FilteredMethods, Sel, R,
3487 receiverIdOrClass);
3488
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003489 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Nico Weber2e0c8f72014-12-27 03:58:08 +00003490 // Test for no method in the pool which should not trigger any warning by
3491 // caller.
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003492 if (Pos == MethodPool.end())
3493 return true;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003494 ObjCMethodList &MethList =
3495 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00003496 return MethList.hasMoreThanOneDecl();
Fariborz Jahanianc62d16f2014-11-13 22:27:05 +00003497}
3498
Sebastian Redl75d8a322010-08-02 23:18:59 +00003499ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
Fariborz Jahanian3337b2e2010-08-09 23:27:58 +00003500 bool receiverIdOrClass,
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003501 bool instance) {
Douglas Gregor70f449b2012-01-25 00:59:09 +00003502 if (ExternalSource)
3503 ReadMethodPool(Sel);
3504
Sebastian Redl75d8a322010-08-02 23:18:59 +00003505 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
Douglas Gregor70f449b2012-01-25 00:59:09 +00003506 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003507 return nullptr;
Douglas Gregorc78d3462009-04-24 21:10:55 +00003508
Douglas Gregor77f49a42013-01-16 18:47:38 +00003509 // Gather the non-hidden methods.
Sebastian Redl75d8a322010-08-02 23:18:59 +00003510 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
Robert Wilhelmb869a8f2013-08-10 12:33:24 +00003511 SmallVector<ObjCMethodDecl *, 4> Methods;
Argyrios Kyrtzidisd3da6e02013-04-17 00:08:58 +00003512 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003513 if (M->getMethod() && !M->getMethod()->isHidden())
3514 return M->getMethod();
Douglas Gregorc78d3462009-04-24 21:10:55 +00003515 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003516 return nullptr;
3517}
Douglas Gregor77f49a42013-01-16 18:47:38 +00003518
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003519void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
3520 Selector Sel, SourceRange R,
3521 bool receiverIdOrClass) {
Douglas Gregor77f49a42013-01-16 18:47:38 +00003522 // We found multiple methods, so we may have to complain.
3523 bool issueDiagnostic = false, issueError = false;
Jonathan Roelofs74411362015-04-28 18:04:44 +00003524
Douglas Gregor77f49a42013-01-16 18:47:38 +00003525 // We support a warning which complains about *any* difference in
3526 // method signature.
3527 bool strictSelectorMatch =
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003528 receiverIdOrClass &&
3529 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
Douglas Gregor77f49a42013-01-16 18:47:38 +00003530 if (strictSelectorMatch) {
3531 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3532 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
3533 issueDiagnostic = true;
3534 break;
3535 }
3536 }
3537 }
Jonathan Roelofs74411362015-04-28 18:04:44 +00003538
Douglas Gregor77f49a42013-01-16 18:47:38 +00003539 // If we didn't see any strict differences, we won't see any loose
3540 // differences. In ARC, however, we also need to check for loose
3541 // mismatches, because most of them are errors.
3542 if (!strictSelectorMatch ||
3543 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
3544 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3545 // This checks if the methods differ in type mismatch.
3546 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
3547 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
3548 issueDiagnostic = true;
3549 if (getLangOpts().ObjCAutoRefCount)
3550 issueError = true;
3551 break;
3552 }
3553 }
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003554
Douglas Gregor77f49a42013-01-16 18:47:38 +00003555 if (issueDiagnostic) {
3556 if (issueError)
3557 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
3558 else if (strictSelectorMatch)
3559 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
3560 else
3561 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003562
Douglas Gregor77f49a42013-01-16 18:47:38 +00003563 Diag(Methods[0]->getLocStart(),
3564 issueError ? diag::note_possibility : diag::note_using)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003565 << Methods[0]->getSourceRange();
Douglas Gregor77f49a42013-01-16 18:47:38 +00003566 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
3567 Diag(Methods[I]->getLocStart(), diag::note_also_found)
Fariborz Jahanian890803f2015-04-15 17:26:21 +00003568 << Methods[I]->getSourceRange();
3569 }
Douglas Gregor77f49a42013-01-16 18:47:38 +00003570 }
Douglas Gregorc78d3462009-04-24 21:10:55 +00003571}
3572
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003573ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
Sebastian Redl75d8a322010-08-02 23:18:59 +00003574 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
3575 if (Pos == MethodPool.end())
Craig Topperc3ec1492014-05-26 06:22:03 +00003576 return nullptr;
Sebastian Redl75d8a322010-08-02 23:18:59 +00003577
3578 GlobalMethods &Methods = Pos->second;
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003579 for (const ObjCMethodList *Method = &Methods.first; Method;
3580 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003581 if (Method->getMethod() &&
3582 (Method->getMethod()->isDefined() ||
3583 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003584 return Method->getMethod();
Fariborz Jahanianec762bd2014-03-26 20:59:26 +00003585
3586 for (const ObjCMethodList *Method = &Methods.second; Method;
3587 Method = Method->getNext())
Fariborz Jahanian4019c7f2015-02-19 21:52:41 +00003588 if (Method->getMethod() &&
3589 (Method->getMethod()->isDefined() ||
3590 Method->getMethod()->isPropertyAccessor()))
Nico Weber2e0c8f72014-12-27 03:58:08 +00003591 return Method->getMethod();
Craig Topperc3ec1492014-05-26 06:22:03 +00003592 return nullptr;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00003593}
3594
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003595static void
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003596HelperSelectorsForTypoCorrection(
3597 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
3598 StringRef Typo, const ObjCMethodDecl * Method) {
3599 const unsigned MaxEditDistance = 1;
3600 unsigned BestEditDistance = MaxEditDistance + 1;
Richard Trieuea8d3702013-06-06 02:22:29 +00003601 std::string MethodName = Method->getSelector().getAsString();
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003602
3603 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
3604 if (MinPossibleEditDistance > 0 &&
3605 Typo.size() / MinPossibleEditDistance < 1)
3606 return;
3607 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
3608 if (EditDistance > MaxEditDistance)
3609 return;
3610 if (EditDistance == BestEditDistance)
3611 BestMethod.push_back(Method);
3612 else if (EditDistance < BestEditDistance) {
3613 BestMethod.clear();
3614 BestMethod.push_back(Method);
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003615 }
3616}
3617
Fariborz Jahanian75481672013-06-17 17:10:54 +00003618static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
3619 QualType ObjectType) {
3620 if (ObjectType.isNull())
3621 return true;
3622 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
3623 return true;
Craig Topperc3ec1492014-05-26 06:22:03 +00003624 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
3625 nullptr;
Fariborz Jahanian75481672013-06-17 17:10:54 +00003626}
3627
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003628const ObjCMethodDecl *
Fariborz Jahanian75481672013-06-17 17:10:54 +00003629Sema::SelectorsForTypoCorrection(Selector Sel,
3630 QualType ObjectType) {
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003631 unsigned NumArgs = Sel.getNumArgs();
3632 SmallVector<const ObjCMethodDecl *, 8> Methods;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003633 bool ObjectIsId = true, ObjectIsClass = true;
3634 if (ObjectType.isNull())
3635 ObjectIsId = ObjectIsClass = false;
3636 else if (!ObjectType->isObjCObjectPointerType())
Craig Topperc3ec1492014-05-26 06:22:03 +00003637 return nullptr;
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003638 else if (const ObjCObjectPointerType *ObjCPtr =
3639 ObjectType->getAsObjCInterfacePointerType()) {
3640 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
3641 ObjectIsId = ObjectIsClass = false;
3642 }
3643 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
3644 ObjectIsClass = false;
3645 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
3646 ObjectIsId = false;
3647 else
Craig Topperc3ec1492014-05-26 06:22:03 +00003648 return nullptr;
3649
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003650 for (GlobalMethodPool::iterator b = MethodPool.begin(),
3651 e = MethodPool.end(); b != e; b++) {
3652 // instance methods
3653 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003654 if (M->getMethod() &&
3655 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3656 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003657 if (ObjectIsId)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003658 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003659 else if (!ObjectIsClass &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003660 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3661 ObjectType))
3662 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003663 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003664 // class methods
3665 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
Nico Weber2e0c8f72014-12-27 03:58:08 +00003666 if (M->getMethod() &&
3667 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
3668 (M->getMethod()->getSelector() != Sel)) {
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003669 if (ObjectIsClass)
Nico Weber2e0c8f72014-12-27 03:58:08 +00003670 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003671 else if (!ObjectIsId &&
Nico Weber2e0c8f72014-12-27 03:58:08 +00003672 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
3673 ObjectType))
3674 Methods.push_back(M->getMethod());
Fariborz Jahanian4cc55522013-06-18 15:31:36 +00003675 }
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003676 }
3677
3678 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
3679 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
3680 HelperSelectorsForTypoCorrection(SelectedMethods,
3681 Sel.getAsString(), Methods[i]);
3682 }
Craig Topperc3ec1492014-05-26 06:22:03 +00003683 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
Fariborz Jahanian0c0fc9e2013-06-05 18:46:14 +00003684}
3685
Fariborz Jahanian42f89382013-05-30 21:48:58 +00003686/// DiagnoseDuplicateIvars -
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003687/// Check for duplicate ivars in the entire class at the start of
James Dennett634962f2012-06-14 21:40:34 +00003688/// \@implementation. This becomes necesssary because class extension can
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003689/// add ivars to a class in random order which will not be known until
James Dennett634962f2012-06-14 21:40:34 +00003690/// class's \@implementation is seen.
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003691void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
3692 ObjCInterfaceDecl *SID) {
Aaron Ballman59abbd42014-03-13 21:09:43 +00003693 for (auto *Ivar : ID->ivars()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003694 if (Ivar->isInvalidDecl())
3695 continue;
3696 if (IdentifierInfo *II = Ivar->getIdentifier()) {
3697 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
3698 if (prevIvar) {
3699 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3700 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
3701 Ivar->setInvalidDecl();
3702 }
3703 }
3704 }
3705}
3706
John McCallb61e14e2015-10-27 04:54:50 +00003707/// Diagnose attempts to define ARC-__weak ivars when __weak is disabled.
3708static void DiagnoseWeakIvars(Sema &S, ObjCImplementationDecl *ID) {
3709 if (S.getLangOpts().ObjCWeak) return;
3710
3711 for (auto ivar = ID->getClassInterface()->all_declared_ivar_begin();
3712 ivar; ivar = ivar->getNextIvar()) {
3713 if (ivar->isInvalidDecl()) continue;
3714 if (ivar->getType().getObjCLifetime() == Qualifiers::OCL_Weak) {
3715 if (S.getLangOpts().ObjCWeakRuntime) {
3716 S.Diag(ivar->getLocation(), diag::err_arc_weak_disabled);
3717 } else {
3718 S.Diag(ivar->getLocation(), diag::err_arc_weak_no_runtime);
3719 }
3720 }
3721 }
3722}
3723
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003724Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
3725 switch (CurContext->getDeclKind()) {
3726 case Decl::ObjCInterface:
3727 return Sema::OCK_Interface;
3728 case Decl::ObjCProtocol:
3729 return Sema::OCK_Protocol;
3730 case Decl::ObjCCategory:
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003731 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003732 return Sema::OCK_ClassExtension;
Benjamin Kramera008d3a2015-04-10 11:37:55 +00003733 return Sema::OCK_Category;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003734 case Decl::ObjCImplementation:
3735 return Sema::OCK_Implementation;
3736 case Decl::ObjCCategoryImpl:
3737 return Sema::OCK_CategoryImplementation;
3738
3739 default:
3740 return Sema::OCK_None;
3741 }
3742}
3743
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003744// Note: For class/category implementations, allMethods is always null.
Robert Wilhelm57c67112013-07-17 21:14:35 +00003745Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
Fariborz Jahaniandfb76872013-07-17 00:05:08 +00003746 ArrayRef<DeclGroupPtrTy> allTUVars) {
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003747 if (getObjCContainerKind() == Sema::OCK_None)
Craig Topperc3ec1492014-05-26 06:22:03 +00003748 return nullptr;
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003749
3750 assert(AtEnd.isValid() && "Invalid location for '@end'");
3751
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00003752 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3753 Decl *ClassDecl = cast<Decl>(OCD);
Fariborz Jahanian9290ede2009-11-16 18:57:01 +00003754
Mike Stump11289f42009-09-09 15:08:12 +00003755 bool isInterfaceDeclKind =
Chris Lattner219b3e92008-03-16 21:17:37 +00003756 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
3757 || isa<ObjCProtocolDecl>(ClassDecl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003758 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
Steve Naroffb3a87982009-01-09 15:36:25 +00003759
Steve Naroff35c62ae2009-01-08 17:28:14 +00003760 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
3761 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
3762 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
3763
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003764 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003765 ObjCMethodDecl *Method =
John McCall48871652010-08-21 09:40:31 +00003766 cast_or_null<ObjCMethodDecl>(allMethods[i]);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003767
3768 if (!Method) continue; // Already issued a diagnostic.
Douglas Gregorffca3a22009-01-09 17:18:27 +00003769 if (Method->isInstanceMethod()) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003770 /// Check for instance method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003771 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003772 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003773 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003774 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003775 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003776 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003777 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003778 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003779 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003780 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003781 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003782 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003783 if (!Context.getSourceManager().isInSystemHeader(
3784 Method->getLocation()))
3785 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3786 << Method->getDeclName();
3787 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3788 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003789 InsMap[Method->getSelector()] = Method;
3790 /// The following allows us to typecheck messages to "id".
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003791 AddInstanceMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003792 }
Mike Stump12b8ce12009-08-04 21:02:39 +00003793 } else {
Chris Lattnerda463fe2007-12-12 07:09:47 +00003794 /// Check for class method of the same name with incompatible types
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003795 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
Mike Stump11289f42009-09-09 15:08:12 +00003796 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
Chris Lattnerda463fe2007-12-12 07:09:47 +00003797 : false;
Mike Stump11289f42009-09-09 15:08:12 +00003798 if ((isInterfaceDeclKind && PrevMethod && !match)
Eli Friedman42b1e9e2008-12-16 20:15:50 +00003799 || (checkIdenticalMethods && match)) {
Chris Lattner0369c572008-11-23 23:12:31 +00003800 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00003801 << Method->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00003802 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Douglas Gregor87e92752010-12-21 17:34:17 +00003803 Method->setInvalidDecl();
Chris Lattnerda463fe2007-12-12 07:09:47 +00003804 } else {
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003805 if (PrevMethod) {
Argyrios Kyrtzidisdcaaa212011-10-14 08:02:31 +00003806 Method->setAsRedeclaration(PrevMethod);
Fariborz Jahanianc17c86b2011-12-13 19:40:34 +00003807 if (!Context.getSourceManager().isInSystemHeader(
3808 Method->getLocation()))
3809 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
3810 << Method->getDeclName();
3811 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3812 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003813 ClsMap[Method->getSelector()] = Method;
Douglas Gregor0e6fc1a2012-05-01 23:37:00 +00003814 AddFactoryMethodToGlobalPool(Method);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003815 }
3816 }
3817 }
Douglas Gregorb8982092013-01-21 19:42:21 +00003818 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
3819 // Nothing to do here.
Steve Naroffb3a87982009-01-09 15:36:25 +00003820 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003821 // Categories are used to extend the class by declaring new methods.
Mike Stump11289f42009-09-09 15:08:12 +00003822 // By the same token, they are also used to add new properties. No
Fariborz Jahanian62293f42008-12-06 19:59:02 +00003823 // need to compare the added property to those in the class.
Daniel Dunbar4684f372008-08-27 05:40:03 +00003824
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003825 if (C->IsClassExtension()) {
3826 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
3827 DiagnoseClassExtensionDupMethods(C, CCPrimary);
Fariborz Jahanianc21f5432010-12-10 23:36:33 +00003828 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003829 }
Steve Naroffb3a87982009-01-09 15:36:25 +00003830 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
Fariborz Jahanian30a42922010-02-15 21:55:26 +00003831 if (CDecl->getIdentifier())
3832 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
3833 // user-defined setter/getter. It also synthesizes setter/getter methods
3834 // and adds them to the DeclContext and global method pools.
Manman Renefe1bac2016-01-27 20:00:32 +00003835 for (auto *I : CDecl->properties())
Douglas Gregore17765e2015-11-03 17:02:34 +00003836 ProcessPropertyDecl(I);
Ted Kremenekc7c64312010-01-07 01:20:12 +00003837 CDecl->setAtEndRange(AtEnd);
Steve Naroffb3a87982009-01-09 15:36:25 +00003838 }
3839 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003840 IC->setAtEndRange(AtEnd);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003841 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003842 // Any property declared in a class extension might have user
3843 // declared setter or getter in current class extension or one
3844 // of the other class extensions. Mark them as synthesized as
3845 // property will be synthesized when property with same name is
3846 // seen in the @implementation.
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003847 for (const auto *Ext : IDecl->visible_extensions()) {
Manman Rena7a8b1f2016-01-26 18:05:23 +00003848 for (const auto *Property : Ext->instance_properties()) {
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003849 // Skip over properties declared @dynamic
3850 if (const ObjCPropertyImplDecl *PIDecl
Manman Ren5b786402016-01-28 18:49:28 +00003851 = IC->FindPropertyImplDecl(Property->getIdentifier(),
3852 Property->getQueryKind()))
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003853 if (PIDecl->getPropertyImplementation()
3854 == ObjCPropertyImplDecl::Dynamic)
3855 continue;
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003856
Aaron Ballmanf53d8dd2014-03-13 21:47:07 +00003857 for (const auto *Ext : IDecl->visible_extensions()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003858 if (ObjCMethodDecl *GetterMethod
3859 = Ext->getInstanceMethod(Property->getGetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003860 GetterMethod->setPropertyAccessor(true);
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003861 if (!Property->isReadOnly())
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003862 if (ObjCMethodDecl *SetterMethod
3863 = Ext->getInstanceMethod(Property->getSetterName()))
Jordan Rosed01e83a2012-10-10 16:42:25 +00003864 SetterMethod->setPropertyAccessor(true);
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003865 }
Fariborz Jahanian5d7e9162010-12-11 18:39:37 +00003866 }
3867 }
Fariborz Jahanian25491a22010-05-05 21:52:17 +00003868 ImplMethodsVsClassMethods(S, IC, IDecl);
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003869 AtomicPropertySetterGetterRules(IC, IDecl);
John McCall31168b02011-06-15 23:02:42 +00003870 DiagnoseOwningPropertyGetterSynthesis(IC);
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00003871 DiagnoseUnusedBackingIvarInAccessor(S, IC);
Fariborz Jahanian20cfff32015-03-11 16:59:48 +00003872 if (IDecl->hasDesignatedInitializers())
3873 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
John McCallb61e14e2015-10-27 04:54:50 +00003874 DiagnoseWeakIvars(*this, IC);
Argyrios Kyrtzidisdb5ce0f2013-12-03 21:11:54 +00003875
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003876 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
Craig Topperc3ec1492014-05-26 06:22:03 +00003877 if (IDecl->getSuperClass() == nullptr) {
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003878 // This class has no superclass, so check that it has been marked with
3879 // __attribute((objc_root_class)).
3880 if (!HasRootClassAttr) {
3881 SourceLocation DeclLoc(IDecl->getLocation());
Alp Tokerb6cc5922014-05-03 03:45:55 +00003882 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003883 Diag(DeclLoc, diag::warn_objc_root_class_missing)
3884 << IDecl->getIdentifier();
3885 // See if NSObject is in the current scope, and if it is, suggest
3886 // adding " : NSObject " to the class declaration.
3887 NamedDecl *IF = LookupSingleName(TUScope,
3888 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
3889 DeclLoc, LookupOrdinaryName);
3890 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
3891 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
3892 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
3893 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
3894 } else {
3895 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
3896 }
3897 }
3898 } else if (HasRootClassAttr) {
3899 // Complain that only root classes may have this attribute.
3900 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
3901 }
3902
Alex Lorenza8c44ba2016-10-28 10:25:10 +00003903 if (const ObjCInterfaceDecl *Super = IDecl->getSuperClass()) {
3904 // An interface can subclass another interface with a
3905 // objc_subclassing_restricted attribute when it has that attribute as
3906 // well (because of interfaces imported from Swift). Therefore we have
3907 // to check if we can subclass in the implementation as well.
3908 if (IDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
3909 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
3910 Diag(IC->getLocation(), diag::err_restricted_superclass_mismatch);
3911 Diag(Super->getLocation(), diag::note_class_declared);
3912 }
3913 }
3914
John McCall5fb5df92012-06-20 06:18:46 +00003915 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian545643c2010-02-23 23:41:11 +00003916 while (IDecl->getSuperClass()) {
3917 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
3918 IDecl = IDecl->getSuperClass();
3919 }
Patrick Beardacfbe9e2012-04-06 18:12:22 +00003920 }
Fariborz Jahanian13e0c902009-11-11 22:40:11 +00003921 }
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00003922 SetIvarInitializers(IC);
Mike Stump11289f42009-09-09 15:08:12 +00003923 } else if (ObjCCategoryImplDecl* CatImplClass =
Steve Naroffb3a87982009-01-09 15:36:25 +00003924 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
Ted Kremenekc7c64312010-01-07 01:20:12 +00003925 CatImplClass->setAtEndRange(AtEnd);
Mike Stump11289f42009-09-09 15:08:12 +00003926
Chris Lattnerda463fe2007-12-12 07:09:47 +00003927 // Find category interface decl and then check that all methods declared
Daniel Dunbar4684f372008-08-27 05:40:03 +00003928 // in this interface are implemented in the category @implementation.
Chris Lattner41fd42e2009-02-16 18:32:47 +00003929 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
Douglas Gregor048fbfa2013-01-16 23:00:23 +00003930 if (ObjCCategoryDecl *Cat
3931 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
3932 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
Chris Lattnerda463fe2007-12-12 07:09:47 +00003933 }
3934 }
Alex Lorenza8c44ba2016-10-28 10:25:10 +00003935 } else if (const auto *IntfDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
3936 if (const ObjCInterfaceDecl *Super = IntfDecl->getSuperClass()) {
3937 if (!IntfDecl->hasAttr<ObjCSubclassingRestrictedAttr>() &&
3938 Super->hasAttr<ObjCSubclassingRestrictedAttr>()) {
3939 Diag(IntfDecl->getLocation(), diag::err_restricted_superclass_mismatch);
3940 Diag(Super->getLocation(), diag::note_class_declared);
3941 }
3942 }
Chris Lattnerda463fe2007-12-12 07:09:47 +00003943 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003944 if (isInterfaceDeclKind) {
3945 // Reject invalid vardecls.
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003946 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003947 DeclGroupRef DG = allTUVars[i].get();
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003948 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3949 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
Daniel Dunbar0ca16602009-04-14 02:25:56 +00003950 if (!VDecl->hasExternalStorage())
Steve Naroff42959b22009-04-13 17:58:46 +00003951 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
Fariborz Jahanian629aed92009-03-21 18:06:45 +00003952 }
Chris Lattner5bbb3c82009-03-29 16:50:03 +00003953 }
Fariborz Jahanian3654e652009-03-18 22:33:24 +00003954 }
Fariborz Jahanian4327b322011-08-29 17:33:12 +00003955 ActOnObjCContainerFinishDefinition();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003956
Fariborz Jahanian0080fb52013-07-16 15:33:19 +00003957 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
Serge Pavlov9ddb76e2013-08-27 13:15:56 +00003958 DeclGroupRef DG = allTUVars[i].get();
Argyrios Kyrtzidis8ad3bab2011-11-23 20:27:36 +00003959 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
3960 (*I)->setTopLevelDeclInObjCContainer();
Argyrios Kyrtzidisbd8b1502011-10-17 19:48:13 +00003961 Consumer.HandleTopLevelDeclInObjCContainer(DG);
3962 }
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003963
Dmitri Gribenkoe7bb9442012-07-13 01:06:46 +00003964 ActOnDocumentableDecl(ClassDecl);
Erik Verbruggenc6c8d932011-12-06 09:25:23 +00003965 return ClassDecl;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003966}
3967
Chris Lattnerda463fe2007-12-12 07:09:47 +00003968/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
3969/// objective-c's type qualifier from the parser version of the same info.
Mike Stump11289f42009-09-09 15:08:12 +00003970static Decl::ObjCDeclQualifier
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003971CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
John McCallca872902011-05-01 03:04:29 +00003972 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
Chris Lattnerda463fe2007-12-12 07:09:47 +00003973}
3974
Douglas Gregor33823722011-06-11 01:09:30 +00003975/// \brief Check whether the declared result type of the given Objective-C
3976/// method declaration is compatible with the method's class.
3977///
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003978static Sema::ResultTypeCompatibilityKind
Douglas Gregor33823722011-06-11 01:09:30 +00003979CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
3980 ObjCInterfaceDecl *CurrentClass) {
Alp Toker314cc812014-01-25 16:55:45 +00003981 QualType ResultType = Method->getReturnType();
3982
Douglas Gregor33823722011-06-11 01:09:30 +00003983 // If an Objective-C method inherits its related result type, then its
3984 // declared result type must be compatible with its own class type. The
3985 // declared result type is compatible if:
3986 if (const ObjCObjectPointerType *ResultObjectType
3987 = ResultType->getAs<ObjCObjectPointerType>()) {
3988 // - it is id or qualified id, or
3989 if (ResultObjectType->isObjCIdType() ||
3990 ResultObjectType->isObjCQualifiedIdType())
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003991 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003992
3993 if (CurrentClass) {
3994 if (ObjCInterfaceDecl *ResultClass
3995 = ResultObjectType->getInterfaceDecl()) {
3996 // - it is the same as the method's class type, or
Douglas Gregor0b144e12011-12-15 00:29:59 +00003997 if (declaresSameEntity(CurrentClass, ResultClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00003998 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00003999
4000 // - it is a superclass of the method's class type
4001 if (ResultClass->isSuperClassOf(CurrentClass))
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004002 return Sema::RTC_Compatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004003 }
Douglas Gregorbab8a962011-09-08 01:46:34 +00004004 } else {
4005 // Any Objective-C pointer type might be acceptable for a protocol
4006 // method; we just don't know.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004007 return Sema::RTC_Unknown;
Douglas Gregor33823722011-06-11 01:09:30 +00004008 }
4009 }
4010
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004011 return Sema::RTC_Incompatible;
Douglas Gregor33823722011-06-11 01:09:30 +00004012}
4013
John McCalld2930c22011-07-22 02:45:48 +00004014namespace {
4015/// A helper class for searching for methods which a particular method
4016/// overrides.
4017class OverrideSearch {
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004018public:
John McCalld2930c22011-07-22 02:45:48 +00004019 Sema &S;
4020 ObjCMethodDecl *Method;
Daniel Dunbard6d74c32012-02-29 03:04:05 +00004021 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
John McCalld2930c22011-07-22 02:45:48 +00004022 bool Recursive;
4023
4024public:
4025 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
4026 Selector selector = method->getSelector();
4027
4028 // Bypass this search if we've never seen an instance/class method
4029 // with this selector before.
4030 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
4031 if (it == S.MethodPool.end()) {
Axel Naumanndd433f02012-10-18 19:05:02 +00004032 if (!S.getExternalSource()) return;
Douglas Gregore1716012012-01-25 00:49:42 +00004033 S.ReadMethodPool(selector);
4034
4035 it = S.MethodPool.find(selector);
4036 if (it == S.MethodPool.end())
4037 return;
John McCalld2930c22011-07-22 02:45:48 +00004038 }
4039 ObjCMethodList &list =
4040 method->isInstanceMethod() ? it->second.first : it->second.second;
Nico Weber2e0c8f72014-12-27 03:58:08 +00004041 if (!list.getMethod()) return;
John McCalld2930c22011-07-22 02:45:48 +00004042
4043 ObjCContainerDecl *container
4044 = cast<ObjCContainerDecl>(method->getDeclContext());
4045
4046 // Prevent the search from reaching this container again. This is
4047 // important with categories, which override methods from the
4048 // interface and each other.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004049 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
4050 searchFromContainer(container);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004051 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
4052 searchFromContainer(Interface);
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004053 } else {
4054 searchFromContainer(container);
4055 }
Douglas Gregor33823722011-06-11 01:09:30 +00004056 }
John McCalld2930c22011-07-22 02:45:48 +00004057
Matthias Braun1d030072016-01-30 01:27:06 +00004058 typedef llvm::SmallPtrSetImpl<ObjCMethodDecl*>::iterator iterator;
John McCalld2930c22011-07-22 02:45:48 +00004059 iterator begin() const { return Overridden.begin(); }
4060 iterator end() const { return Overridden.end(); }
4061
4062private:
4063 void searchFromContainer(ObjCContainerDecl *container) {
4064 if (container->isInvalidDecl()) return;
4065
4066 switch (container->getDeclKind()) {
4067#define OBJCCONTAINER(type, base) \
4068 case Decl::type: \
4069 searchFrom(cast<type##Decl>(container)); \
4070 break;
4071#define ABSTRACT_DECL(expansion)
4072#define DECL(type, base) \
4073 case Decl::type:
4074#include "clang/AST/DeclNodes.inc"
4075 llvm_unreachable("not an ObjC container!");
4076 }
4077 }
4078
4079 void searchFrom(ObjCProtocolDecl *protocol) {
Douglas Gregore6e48b12012-01-01 19:29:29 +00004080 if (!protocol->hasDefinition())
4081 return;
4082
John McCalld2930c22011-07-22 02:45:48 +00004083 // A method in a protocol declaration overrides declarations from
4084 // referenced ("parent") protocols.
4085 search(protocol->getReferencedProtocols());
4086 }
4087
4088 void searchFrom(ObjCCategoryDecl *category) {
4089 // A method in a category declaration overrides declarations from
4090 // the main class and from protocols the category references.
Douglas Gregorcf4ac442012-05-03 21:25:24 +00004091 // The main class is handled in the constructor.
John McCalld2930c22011-07-22 02:45:48 +00004092 search(category->getReferencedProtocols());
4093 }
4094
4095 void searchFrom(ObjCCategoryImplDecl *impl) {
4096 // A method in a category definition that has a category
4097 // declaration overrides declarations from the category
4098 // declaration.
4099 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
4100 search(category);
Douglas Gregorc5928af2012-05-17 22:39:14 +00004101 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
4102 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004103
4104 // Otherwise it overrides declarations from the class.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004105 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
4106 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004107 }
4108 }
4109
4110 void searchFrom(ObjCInterfaceDecl *iface) {
4111 // A method in a class declaration overrides declarations from
Douglas Gregorc0ac7d62011-12-15 05:27:12 +00004112 if (!iface->hasDefinition())
4113 return;
4114
John McCalld2930c22011-07-22 02:45:48 +00004115 // - categories,
Aaron Ballman15063e12014-03-13 21:35:02 +00004116 for (auto *Cat : iface->known_categories())
4117 search(Cat);
John McCalld2930c22011-07-22 02:45:48 +00004118
4119 // - the super class, and
4120 if (ObjCInterfaceDecl *super = iface->getSuperClass())
4121 search(super);
4122
4123 // - any referenced protocols.
4124 search(iface->getReferencedProtocols());
4125 }
4126
4127 void searchFrom(ObjCImplementationDecl *impl) {
4128 // A method in a class implementation overrides declarations from
4129 // the class interface.
Douglas Gregorc5928af2012-05-17 22:39:14 +00004130 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
4131 search(Interface);
John McCalld2930c22011-07-22 02:45:48 +00004132 }
4133
John McCalld2930c22011-07-22 02:45:48 +00004134 void search(const ObjCProtocolList &protocols) {
4135 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
4136 i != e; ++i)
4137 search(*i);
4138 }
4139
4140 void search(ObjCContainerDecl *container) {
John McCalld2930c22011-07-22 02:45:48 +00004141 // Check for a method in this container which matches this selector.
4142 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
Argyrios Kyrtzidisbd8cd3e2013-03-29 21:51:48 +00004143 Method->isInstanceMethod(),
4144 /*AllowHidden=*/true);
John McCalld2930c22011-07-22 02:45:48 +00004145
4146 // If we find one, record it and bail out.
4147 if (meth) {
4148 Overridden.insert(meth);
4149 return;
4150 }
4151
4152 // Otherwise, search for methods that a hypothetical method here
4153 // would have overridden.
4154
4155 // Note that we're now in a recursive case.
4156 Recursive = true;
4157
4158 searchFromContainer(container);
4159 }
4160};
Hans Wennborgdcfba332015-10-06 23:40:43 +00004161} // end anonymous namespace
Douglas Gregor33823722011-06-11 01:09:30 +00004162
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004163void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
4164 ObjCInterfaceDecl *CurrentClass,
4165 ResultTypeCompatibilityKind RTC) {
4166 // Search for overridden methods and merge information down from them.
4167 OverrideSearch overrides(*this, ObjCMethod);
4168 // Keep track if the method overrides any method in the class's base classes,
4169 // its protocols, or its categories' protocols; we will keep that info
4170 // in the ObjCMethodDecl.
4171 // For this info, a method in an implementation is not considered as
4172 // overriding the same method in the interface or its categories.
4173 bool hasOverriddenMethodsInBaseOrProtocol = false;
4174 for (OverrideSearch::iterator
4175 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
4176 ObjCMethodDecl *overridden = *i;
4177
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004178 if (!hasOverriddenMethodsInBaseOrProtocol) {
4179 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
4180 CurrentClass != overridden->getClassInterface() ||
4181 overridden->isOverriding()) {
4182 hasOverriddenMethodsInBaseOrProtocol = true;
4183
4184 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
4185 // OverrideSearch will return as "overridden" the same method in the
4186 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
4187 // check whether a category of a base class introduced a method with the
4188 // same selector, after the interface method declaration.
4189 // To avoid unnecessary lookups in the majority of cases, we use the
4190 // extra info bits in GlobalMethodPool to check whether there were any
4191 // category methods with this selector.
4192 GlobalMethodPool::iterator It =
4193 MethodPool.find(ObjCMethod->getSelector());
4194 if (It != MethodPool.end()) {
4195 ObjCMethodList &List =
4196 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
4197 unsigned CategCount = List.getBits();
4198 if (CategCount > 0) {
4199 // If the method is in a category we'll do lookup if there were at
4200 // least 2 category methods recorded, otherwise only one will do.
4201 if (CategCount > 1 ||
4202 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
4203 OverrideSearch overrides(*this, overridden);
4204 for (OverrideSearch::iterator
4205 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
4206 ObjCMethodDecl *SuperOverridden = *OI;
Argyrios Kyrtzidis04703a62013-04-27 00:10:12 +00004207 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
4208 CurrentClass != SuperOverridden->getClassInterface()) {
Argyrios Kyrtzidisc2091d52013-04-17 00:09:08 +00004209 hasOverriddenMethodsInBaseOrProtocol = true;
4210 overridden->setOverriding(true);
4211 break;
4212 }
4213 }
4214 }
4215 }
4216 }
4217 }
4218 }
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004219
4220 // Propagate down the 'related result type' bit from overridden methods.
4221 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
4222 ObjCMethod->SetRelatedResultType();
4223
4224 // Then merge the declarations.
4225 mergeObjCMethodDecls(ObjCMethod, overridden);
4226
4227 if (ObjCMethod->isImplicit() && overridden->isImplicit())
4228 continue; // Conflicting properties are detected elsewhere.
4229
4230 // Check for overriding methods
4231 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
4232 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
4233 CheckConflictingOverridingMethod(ObjCMethod, overridden,
4234 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
4235
4236 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
Fariborz Jahanian31a25682012-07-05 22:26:07 +00004237 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
4238 !overridden->isImplicit() /* not meant for properties */) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004239 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
4240 E = ObjCMethod->param_end();
Douglas Gregor0bf70f42012-05-17 23:13:29 +00004241 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
4242 PrevE = overridden->param_end();
4243 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004244 assert(PrevI != overridden->param_end() && "Param mismatch");
4245 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
4246 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
4247 // If type of argument of method in this class does not match its
4248 // respective argument type in the super class method, issue warning;
4249 if (!Context.typesAreCompatible(T1, T2)) {
4250 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
4251 << T1 << T2;
4252 Diag(overridden->getLocation(), diag::note_previous_declaration);
4253 break;
4254 }
4255 }
4256 }
4257 }
4258
4259 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
4260}
4261
Douglas Gregor813a0662015-06-19 18:14:38 +00004262/// Merge type nullability from for a redeclaration of the same entity,
4263/// producing the updated type of the redeclared entity.
4264static QualType mergeTypeNullabilityForRedecl(Sema &S, SourceLocation loc,
4265 QualType type,
4266 bool usesCSKeyword,
4267 SourceLocation prevLoc,
4268 QualType prevType,
4269 bool prevUsesCSKeyword) {
4270 // Determine the nullability of both types.
4271 auto nullability = type->getNullability(S.Context);
4272 auto prevNullability = prevType->getNullability(S.Context);
4273
4274 // Easy case: both have nullability.
4275 if (nullability.hasValue() == prevNullability.hasValue()) {
4276 // Neither has nullability; continue.
4277 if (!nullability)
4278 return type;
4279
4280 // The nullabilities are equivalent; do nothing.
4281 if (*nullability == *prevNullability)
4282 return type;
4283
4284 // Complain about mismatched nullability.
4285 S.Diag(loc, diag::err_nullability_conflicting)
Douglas Gregoraea7afd2015-06-24 22:02:08 +00004286 << DiagNullabilityKind(*nullability, usesCSKeyword)
4287 << DiagNullabilityKind(*prevNullability, prevUsesCSKeyword);
Douglas Gregor813a0662015-06-19 18:14:38 +00004288 return type;
4289 }
4290
4291 // If it's the redeclaration that has nullability, don't change anything.
4292 if (nullability)
4293 return type;
4294
4295 // Otherwise, provide the result with the same nullability.
4296 return S.Context.getAttributedType(
4297 AttributedType::getNullabilityAttrKind(*prevNullability),
4298 type, type);
4299}
4300
NAKAMURA Takumi2df5c3c2015-06-20 03:52:52 +00004301/// Merge information from the declaration of a method in the \@interface
Douglas Gregor813a0662015-06-19 18:14:38 +00004302/// (or a category/extension) into the corresponding method in the
4303/// @implementation (for a class or category).
4304static void mergeInterfaceMethodToImpl(Sema &S,
4305 ObjCMethodDecl *method,
4306 ObjCMethodDecl *prevMethod) {
4307 // Merge the objc_requires_super attribute.
4308 if (prevMethod->hasAttr<ObjCRequiresSuperAttr>() &&
4309 !method->hasAttr<ObjCRequiresSuperAttr>()) {
4310 // merge the attribute into implementation.
4311 method->addAttr(
4312 ObjCRequiresSuperAttr::CreateImplicit(S.Context,
4313 method->getLocation()));
4314 }
4315
4316 // Merge nullability of the result type.
4317 QualType newReturnType
4318 = mergeTypeNullabilityForRedecl(
4319 S, method->getReturnTypeSourceRange().getBegin(),
4320 method->getReturnType(),
4321 method->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4322 prevMethod->getReturnTypeSourceRange().getBegin(),
4323 prevMethod->getReturnType(),
4324 prevMethod->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4325 method->setReturnType(newReturnType);
4326
4327 // Handle each of the parameters.
4328 unsigned numParams = method->param_size();
4329 unsigned numPrevParams = prevMethod->param_size();
4330 for (unsigned i = 0, n = std::min(numParams, numPrevParams); i != n; ++i) {
4331 ParmVarDecl *param = method->param_begin()[i];
4332 ParmVarDecl *prevParam = prevMethod->param_begin()[i];
4333
4334 // Merge nullability.
4335 QualType newParamType
4336 = mergeTypeNullabilityForRedecl(
4337 S, param->getLocation(), param->getType(),
4338 param->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability,
4339 prevParam->getLocation(), prevParam->getType(),
4340 prevParam->getObjCDeclQualifier() & Decl::OBJC_TQ_CSNullability);
4341 param->setType(newParamType);
4342 }
4343}
4344
Alex Lorenza8a372d2017-04-27 10:43:48 +00004345/// Verify that the method parameters/return value have types that are supported
4346/// by the x86 target.
4347static void checkObjCMethodX86VectorTypes(Sema &SemaRef,
4348 const ObjCMethodDecl *Method) {
4349 assert(SemaRef.getASTContext().getTargetInfo().getTriple().getArch() ==
4350 llvm::Triple::x86 &&
4351 "x86-specific check invoked for a different target");
4352 SourceLocation Loc;
4353 QualType T;
4354 for (const ParmVarDecl *P : Method->parameters()) {
4355 if (P->getType()->isVectorType()) {
4356 Loc = P->getLocStart();
4357 T = P->getType();
4358 break;
4359 }
4360 }
4361 if (Loc.isInvalid()) {
4362 if (Method->getReturnType()->isVectorType()) {
4363 Loc = Method->getReturnTypeSourceRange().getBegin();
4364 T = Method->getReturnType();
4365 } else
4366 return;
4367 }
4368
4369 // Vector parameters/return values are not supported by objc_msgSend on x86 in
4370 // iOS < 9 and macOS < 10.11.
4371 const auto &Triple = SemaRef.getASTContext().getTargetInfo().getTriple();
4372 VersionTuple AcceptedInVersion;
4373 if (Triple.getOS() == llvm::Triple::IOS)
4374 AcceptedInVersion = VersionTuple(/*Major=*/9);
4375 else if (Triple.isMacOSX())
4376 AcceptedInVersion = VersionTuple(/*Major=*/10, /*Minor=*/11);
4377 else
4378 return;
Alex Lorenza8a372d2017-04-27 10:43:48 +00004379 if (SemaRef.getASTContext().getTargetInfo().getPlatformMinVersion() >=
Alex Lorenz92824832017-05-05 16:15:17 +00004380 AcceptedInVersion)
Alex Lorenza8a372d2017-04-27 10:43:48 +00004381 return;
4382 SemaRef.Diag(Loc, diag::err_objc_method_unsupported_param_ret_type)
4383 << T << (Method->getReturnType()->isVectorType() ? /*return value*/ 1
4384 : /*parameter*/ 0)
4385 << (Triple.isMacOSX() ? "macOS 10.11" : "iOS 9");
4386}
4387
John McCall48871652010-08-21 09:40:31 +00004388Decl *Sema::ActOnMethodDeclaration(
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004389 Scope *S,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004390 SourceLocation MethodLoc, SourceLocation EndLoc,
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004391 tok::TokenKind MethodType,
John McCallba7bf592010-08-24 05:47:05 +00004392 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004393 ArrayRef<SourceLocation> SelectorLocs,
Chris Lattnerda463fe2007-12-12 07:09:47 +00004394 Selector Sel,
4395 // optional arguments. The number of types/arguments is obtained
4396 // from the Sel.getNumArgs().
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004397 ObjCArgInfo *ArgInfo,
Fariborz Jahanian60462092010-04-08 00:30:06 +00004398 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
Chris Lattnerda463fe2007-12-12 07:09:47 +00004399 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004400 bool isVariadic, bool MethodDefinition) {
Steve Naroff83777fe2008-02-29 21:48:07 +00004401 // Make sure we can establish a context for the method.
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004402 if (!CurContext->isObjCContainer()) {
Richard Smithf8812672016-12-02 22:38:31 +00004403 Diag(MethodLoc, diag::err_missing_method_context);
Craig Topperc3ec1492014-05-26 06:22:03 +00004404 return nullptr;
Steve Naroff83777fe2008-02-29 21:48:07 +00004405 }
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004406 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
4407 Decl *ClassDecl = cast<Decl>(OCD);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004408 QualType resultDeclType;
Mike Stump11289f42009-09-09 15:08:12 +00004409
Douglas Gregorbab8a962011-09-08 01:46:34 +00004410 bool HasRelatedResultType = false;
Craig Topperc3ec1492014-05-26 06:22:03 +00004411 TypeSourceInfo *ReturnTInfo = nullptr;
Steve Naroff32606412009-02-20 22:59:16 +00004412 if (ReturnType) {
Alp Toker314cc812014-01-25 16:55:45 +00004413 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
Mike Stump11289f42009-09-09 15:08:12 +00004414
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004415 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
Craig Topperc3ec1492014-05-26 06:22:03 +00004416 return nullptr;
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004417
Douglas Gregor813a0662015-06-19 18:14:38 +00004418 QualType bareResultType = resultDeclType;
4419 (void)AttributedType::stripOuterNullability(bareResultType);
4420 HasRelatedResultType = (bareResultType == Context.getObjCInstanceType());
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004421 } else { // get the type for "id".
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004422 resultDeclType = Context.getObjCIdType();
Fariborz Jahanianb21138f2011-07-21 17:38:14 +00004423 Diag(MethodLoc, diag::warn_missing_method_return_type)
Argyrios Kyrtzidisdfd65702011-10-03 06:36:36 +00004424 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
Fariborz Jahanianb5a52ca2011-07-21 17:00:47 +00004425 }
Mike Stump11289f42009-09-09 15:08:12 +00004426
Alp Toker314cc812014-01-25 16:55:45 +00004427 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
4428 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
4429 MethodType == tok::minus, isVariadic,
4430 /*isPropertyAccessor=*/false,
4431 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
4432 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
4433 : ObjCMethodDecl::Required,
4434 HasRelatedResultType);
Mike Stump11289f42009-09-09 15:08:12 +00004435
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004436 SmallVector<ParmVarDecl*, 16> Params;
Mike Stump11289f42009-09-09 15:08:12 +00004437
Chris Lattner23b0faf2009-04-11 19:42:43 +00004438 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
John McCall856bbea2009-10-23 21:48:59 +00004439 QualType ArgType;
John McCallbcd03502009-12-07 02:54:59 +00004440 TypeSourceInfo *DI;
Mike Stump11289f42009-09-09 15:08:12 +00004441
David Blaikie7d170102013-05-15 07:37:26 +00004442 if (!ArgInfo[i].Type) {
John McCall856bbea2009-10-23 21:48:59 +00004443 ArgType = Context.getObjCIdType();
Craig Topperc3ec1492014-05-26 06:22:03 +00004444 DI = nullptr;
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004445 } else {
John McCall856bbea2009-10-23 21:48:59 +00004446 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004447 }
Mike Stump11289f42009-09-09 15:08:12 +00004448
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004449 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
Richard Smithbecb92d2017-10-10 22:33:17 +00004450 LookupOrdinaryName, forRedeclarationInCurContext());
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004451 LookupName(R, S);
4452 if (R.isSingleResult()) {
4453 NamedDecl *PrevDecl = R.getFoundDecl();
4454 if (S->isDeclScope(PrevDecl)) {
Fariborz Jahanianc677f692011-03-12 18:54:30 +00004455 Diag(ArgInfo[i].NameLoc,
4456 (MethodDefinition ? diag::warn_method_param_redefinition
4457 : diag::warn_method_param_declaration))
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004458 << ArgInfo[i].Name;
4459 Diag(PrevDecl->getLocation(),
4460 diag::note_previous_declaration);
4461 }
4462 }
4463
Abramo Bagnaradff19302011-03-08 08:55:46 +00004464 SourceLocation StartLoc = DI
4465 ? DI->getTypeLoc().getBeginLoc()
4466 : ArgInfo[i].NameLoc;
4467
John McCalld44f4d72011-04-23 02:46:06 +00004468 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
4469 ArgInfo[i].NameLoc, ArgInfo[i].Name,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004470 ArgType, DI, SC_None);
Mike Stump11289f42009-09-09 15:08:12 +00004471
John McCall82490832011-05-02 00:30:12 +00004472 Param->setObjCMethodScopeInfo(i);
4473
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004474 Param->setObjCDeclQualifier(
Chris Lattnerd8626fd2009-04-11 18:57:04 +00004475 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
Mike Stump11289f42009-09-09 15:08:12 +00004476
Chris Lattner9713a1c2009-04-11 19:34:56 +00004477 // Apply the attributes to the parameter.
Douglas Gregor758a8692009-06-17 21:51:59 +00004478 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004479 AddPragmaAttributes(TUScope, Param);
Mike Stump11289f42009-09-09 15:08:12 +00004480
Fariborz Jahanian52d02f62012-01-14 18:44:35 +00004481 if (Param->hasAttr<BlocksAttr>()) {
4482 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
4483 Param->setInvalidDecl();
4484 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004485 S->AddDecl(Param);
4486 IdResolver.AddDecl(Param);
4487
Chris Lattnerc5ffed42008-04-04 06:12:32 +00004488 Params.push_back(Param);
4489 }
Fariborz Jahanianca3566f2011-02-09 22:20:01 +00004490
Fariborz Jahanian60462092010-04-08 00:30:06 +00004491 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
John McCall48871652010-08-21 09:40:31 +00004492 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004493 QualType ArgType = Param->getType();
4494 if (ArgType.isNull())
4495 ArgType = Context.getObjCIdType();
4496 else
4497 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
Douglas Gregor84280642011-07-12 04:42:08 +00004498 ArgType = Context.getAdjustedParameterType(ArgType);
Eli Friedman31a5bcc2013-06-14 21:14:10 +00004499
Fariborz Jahanian60462092010-04-08 00:30:06 +00004500 Param->setDeclContext(ObjCMethod);
Fariborz Jahanian60462092010-04-08 00:30:06 +00004501 Params.push_back(Param);
4502 }
4503
Argyrios Kyrtzidisb8c3aaf2011-10-03 06:37:04 +00004504 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00004505 ObjCMethod->setObjCDeclQualifier(
4506 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
Daniel Dunbarc136e0c2008-09-26 04:12:28 +00004507
4508 if (AttrList)
Douglas Gregor758a8692009-06-17 21:51:59 +00004509 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
Alex Lorenz9e7bf162017-04-18 14:33:39 +00004510 AddPragmaAttributes(TUScope, ObjCMethod);
Mike Stump11289f42009-09-09 15:08:12 +00004511
Douglas Gregor87e92752010-12-21 17:34:17 +00004512 // Add the method now.
Craig Topperc3ec1492014-05-26 06:22:03 +00004513 const ObjCMethodDecl *PrevMethod = nullptr;
John McCalld2930c22011-07-22 02:45:48 +00004514 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
Chris Lattnerda463fe2007-12-12 07:09:47 +00004515 if (MethodType == tok::minus) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004516 PrevMethod = ImpDecl->getInstanceMethod(Sel);
4517 ImpDecl->addInstanceMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004518 } else {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004519 PrevMethod = ImpDecl->getClassMethod(Sel);
4520 ImpDecl->addClassMethod(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004521 }
Douglas Gregor33823722011-06-11 01:09:30 +00004522
Douglas Gregor813a0662015-06-19 18:14:38 +00004523 // Merge information from the @interface declaration into the
4524 // @implementation.
4525 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface()) {
4526 if (auto *IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
4527 ObjCMethod->isInstanceMethod())) {
4528 mergeInterfaceMethodToImpl(*this, ObjCMethod, IMD);
4529
4530 // Warn about defining -dealloc in a category.
4531 if (isa<ObjCCategoryImplDecl>(ImpDecl) && IMD->isOverriding() &&
4532 ObjCMethod->getSelector().getMethodFamily() == OMF_dealloc) {
4533 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
4534 << ObjCMethod->getDeclName();
4535 }
4536 }
Fariborz Jahanian7e350d22013-12-17 22:44:28 +00004537 }
Douglas Gregor87e92752010-12-21 17:34:17 +00004538 } else {
4539 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
Chris Lattnerda463fe2007-12-12 07:09:47 +00004540 }
John McCalld2930c22011-07-22 02:45:48 +00004541
Chris Lattnerda463fe2007-12-12 07:09:47 +00004542 if (PrevMethod) {
4543 // You can never have two method definitions with the same name.
Chris Lattner0369c572008-11-23 23:12:31 +00004544 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
Chris Lattnere4b95692008-11-24 03:33:13 +00004545 << ObjCMethod->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00004546 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian096f7c12013-05-13 17:27:00 +00004547 ObjCMethod->setInvalidDecl();
4548 return ObjCMethod;
Mike Stump11289f42009-09-09 15:08:12 +00004549 }
John McCall28a6aea2009-11-04 02:18:39 +00004550
Douglas Gregor33823722011-06-11 01:09:30 +00004551 // If this Objective-C method does not have a related result type, but we
4552 // are allowed to infer related result types, try to do so based on the
4553 // method family.
4554 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
4555 if (!CurrentClass) {
4556 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
4557 CurrentClass = Cat->getClassInterface();
4558 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
4559 CurrentClass = Impl->getClassInterface();
4560 else if (ObjCCategoryImplDecl *CatImpl
4561 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
4562 CurrentClass = CatImpl->getClassInterface();
4563 }
John McCalld2930c22011-07-22 02:45:48 +00004564
Douglas Gregorbab8a962011-09-08 01:46:34 +00004565 ResultTypeCompatibilityKind RTC
4566 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
John McCalld2930c22011-07-22 02:45:48 +00004567
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004568 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
John McCalld2930c22011-07-22 02:45:48 +00004569
John McCall31168b02011-06-15 23:02:42 +00004570 bool ARCError = false;
David Blaikiebbafb8a2012-03-11 07:00:24 +00004571 if (getLangOpts().ObjCAutoRefCount)
John McCalle48f3892013-04-04 01:38:37 +00004572 ARCError = CheckARCMethodDecl(ObjCMethod);
John McCall31168b02011-06-15 23:02:42 +00004573
Douglas Gregorbab8a962011-09-08 01:46:34 +00004574 // Infer the related result type when possible.
Argyrios Kyrtzidis08f96a92012-05-09 16:12:57 +00004575 if (!ARCError && RTC == Sema::RTC_Compatible &&
Douglas Gregorbab8a962011-09-08 01:46:34 +00004576 !ObjCMethod->hasRelatedResultType() &&
4577 LangOpts.ObjCInferRelatedResultType) {
Douglas Gregor33823722011-06-11 01:09:30 +00004578 bool InferRelatedResultType = false;
4579 switch (ObjCMethod->getMethodFamily()) {
4580 case OMF_None:
4581 case OMF_copy:
4582 case OMF_dealloc:
Nico Weber1fb82662011-08-28 22:35:17 +00004583 case OMF_finalize:
Douglas Gregor33823722011-06-11 01:09:30 +00004584 case OMF_mutableCopy:
4585 case OMF_release:
4586 case OMF_retainCount:
Fariborz Jahanian78e9deb2014-08-22 16:57:26 +00004587 case OMF_initialize:
Fariborz Jahanianb7a77362011-07-05 22:38:59 +00004588 case OMF_performSelector:
Douglas Gregor33823722011-06-11 01:09:30 +00004589 break;
4590
4591 case OMF_alloc:
4592 case OMF_new:
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004593 InferRelatedResultType = ObjCMethod->isClassMethod();
Douglas Gregor33823722011-06-11 01:09:30 +00004594 break;
4595
4596 case OMF_init:
4597 case OMF_autorelease:
4598 case OMF_retain:
4599 case OMF_self:
4600 InferRelatedResultType = ObjCMethod->isInstanceMethod();
4601 break;
4602 }
4603
Fariborz Jahanian7a60b6d2015-04-16 18:38:44 +00004604 if (InferRelatedResultType &&
4605 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
Douglas Gregor33823722011-06-11 01:09:30 +00004606 ObjCMethod->SetRelatedResultType();
Douglas Gregor33823722011-06-11 01:09:30 +00004607 }
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004608
Alex Lorenza8a372d2017-04-27 10:43:48 +00004609 if (MethodDefinition &&
4610 Context.getTargetInfo().getTriple().getArch() == llvm::Triple::x86)
4611 checkObjCMethodX86VectorTypes(*this, ObjCMethod);
4612
Dmitri Gribenkof26054f2012-07-11 21:38:39 +00004613 ActOnDocumentableDecl(ObjCMethod);
4614
John McCall48871652010-08-21 09:40:31 +00004615 return ObjCMethod;
Chris Lattnerda463fe2007-12-12 07:09:47 +00004616}
4617
Chris Lattner438e5012008-12-17 07:13:27 +00004618bool Sema::CheckObjCDeclScope(Decl *D) {
Fariborz Jahanianf36734d2011-08-22 18:34:22 +00004619 // Following is also an error. But it is caused by a missing @end
4620 // and diagnostic is issued elsewhere.
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004621 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004622 return false;
Argyrios Kyrtzidis822c4332012-03-23 23:24:23 +00004623
4624 // If we switched context to translation unit while we are still lexically in
4625 // an objc container, it means the parser missed emitting an error.
4626 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
4627 return false;
Fariborz Jahanian8d382dc2011-08-22 15:54:49 +00004628
Anders Carlssona6b508a2008-11-04 16:57:32 +00004629 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
4630 D->setInvalidDecl();
Mike Stump11289f42009-09-09 15:08:12 +00004631
Anders Carlssona6b508a2008-11-04 16:57:32 +00004632 return true;
4633}
Chris Lattner438e5012008-12-17 07:13:27 +00004634
James Dennett634962f2012-06-14 21:40:34 +00004635/// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
Chris Lattner438e5012008-12-17 07:13:27 +00004636/// instance variables of ClassName into Decls.
John McCall48871652010-08-21 09:40:31 +00004637void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
Chris Lattner438e5012008-12-17 07:13:27 +00004638 IdentifierInfo *ClassName,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004639 SmallVectorImpl<Decl*> &Decls) {
Chris Lattner438e5012008-12-17 07:13:27 +00004640 // Check that ClassName is a valid class
Douglas Gregorb2ccf012010-04-15 22:33:43 +00004641 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
Chris Lattner438e5012008-12-17 07:13:27 +00004642 if (!Class) {
4643 Diag(DeclStart, diag::err_undef_interface) << ClassName;
4644 return;
4645 }
John McCall5fb5df92012-06-20 06:18:46 +00004646 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanianece1b2b2009-04-21 20:28:41 +00004647 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
4648 return;
4649 }
Mike Stump11289f42009-09-09 15:08:12 +00004650
Chris Lattner438e5012008-12-17 07:13:27 +00004651 // Collect the instance variables
Jordy Rosea91768e2011-07-22 02:08:32 +00004652 SmallVector<const ObjCIvarDecl*, 32> Ivars;
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004653 Context.DeepCollectObjCIvars(Class, true, Ivars);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004654 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004655 for (unsigned i = 0; i < Ivars.size(); i++) {
Jordy Rosea91768e2011-07-22 02:08:32 +00004656 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
John McCall48871652010-08-21 09:40:31 +00004657 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
Abramo Bagnaradff19302011-03-08 08:55:46 +00004658 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
4659 /*FIXME: StartL=*/ID->getLocation(),
4660 ID->getLocation(),
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004661 ID->getIdentifier(), ID->getType(),
4662 ID->getBitWidth());
John McCall48871652010-08-21 09:40:31 +00004663 Decls.push_back(FD);
Fariborz Jahanian7dae1142009-06-04 17:08:55 +00004664 }
Mike Stump11289f42009-09-09 15:08:12 +00004665
Chris Lattner438e5012008-12-17 07:13:27 +00004666 // Introduce all of these fields into the appropriate scope.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004667 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
Chris Lattner438e5012008-12-17 07:13:27 +00004668 D != Decls.end(); ++D) {
John McCall48871652010-08-21 09:40:31 +00004669 FieldDecl *FD = cast<FieldDecl>(*D);
David Blaikiebbafb8a2012-03-11 07:00:24 +00004670 if (getLangOpts().CPlusPlus)
Chris Lattner438e5012008-12-17 07:13:27 +00004671 PushOnScopeChains(cast<FieldDecl>(FD), S);
John McCall48871652010-08-21 09:40:31 +00004672 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00004673 Record->addDecl(FD);
Chris Lattner438e5012008-12-17 07:13:27 +00004674 }
4675}
4676
Douglas Gregorf3564192010-04-26 17:32:49 +00004677/// \brief Build a type-check a new Objective-C exception variable declaration.
Abramo Bagnaradff19302011-03-08 08:55:46 +00004678VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
4679 SourceLocation StartLoc,
4680 SourceLocation IdLoc,
4681 IdentifierInfo *Id,
Douglas Gregorf3564192010-04-26 17:32:49 +00004682 bool Invalid) {
4683 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
4684 // duration shall not be qualified by an address-space qualifier."
4685 // Since all parameters have automatic store duration, they can not have
4686 // an address space.
4687 if (T.getAddressSpace() != 0) {
Abramo Bagnaradff19302011-03-08 08:55:46 +00004688 Diag(IdLoc, diag::err_arg_with_address_space);
Douglas Gregorf3564192010-04-26 17:32:49 +00004689 Invalid = true;
4690 }
4691
4692 // An @catch parameter must be an unqualified object pointer type;
4693 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
4694 if (Invalid) {
4695 // Don't do any further checking.
Douglas Gregorf4e837f2010-04-26 17:57:08 +00004696 } else if (T->isDependentType()) {
4697 // Okay: we don't know what this type will instantiate to.
Douglas Gregorf3564192010-04-26 17:32:49 +00004698 } else if (!T->isObjCObjectPointerType()) {
4699 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004700 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
Douglas Gregorf3564192010-04-26 17:32:49 +00004701 } else if (T->isObjCQualifiedIdType()) {
4702 Invalid = true;
Abramo Bagnaradff19302011-03-08 08:55:46 +00004703 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
Douglas Gregorf3564192010-04-26 17:32:49 +00004704 }
4705
Abramo Bagnaradff19302011-03-08 08:55:46 +00004706 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00004707 T, TInfo, SC_None);
Douglas Gregor3f324d562010-05-03 18:51:14 +00004708 New->setExceptionVariable(true);
4709
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004710 // In ARC, infer 'retaining' for variables of retainable type.
David Blaikiebbafb8a2012-03-11 07:00:24 +00004711 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
Douglas Gregor8ca0c642011-12-10 01:22:52 +00004712 Invalid = true;
4713
Douglas Gregorf3564192010-04-26 17:32:49 +00004714 if (Invalid)
4715 New->setInvalidDecl();
4716 return New;
4717}
4718
John McCall48871652010-08-21 09:40:31 +00004719Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004720 const DeclSpec &DS = D.getDeclSpec();
4721
4722 // We allow the "register" storage class on exception variables because
4723 // GCC did, but we drop it completely. Any other storage class is an error.
4724 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
4725 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
4726 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
Richard Smithb4a9e862013-04-12 22:46:28 +00004727 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
Douglas Gregorf3564192010-04-26 17:32:49 +00004728 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
Richard Smithb4a9e862013-04-12 22:46:28 +00004729 << DeclSpec::getSpecifierName(SCS);
4730 }
Richard Smith62f19e72016-06-25 00:15:56 +00004731 if (DS.isInlineSpecified())
4732 Diag(DS.getInlineSpecLoc(), diag::err_inline_non_function)
4733 << getLangOpts().CPlusPlus1z;
Richard Smithb4a9e862013-04-12 22:46:28 +00004734 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
4735 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
4736 diag::err_invalid_thread)
4737 << DeclSpec::getSpecifierName(TSCS);
Douglas Gregorf3564192010-04-26 17:32:49 +00004738 D.getMutableDeclSpec().ClearStorageClassSpecs();
4739
Richard Smithb1402ae2013-03-18 22:52:47 +00004740 DiagnoseFunctionSpecifiers(D.getDeclSpec());
Douglas Gregorf3564192010-04-26 17:32:49 +00004741
4742 // Check that there are no default arguments inside the type of this
4743 // exception object (C++ only).
David Blaikiebbafb8a2012-03-11 07:00:24 +00004744 if (getLangOpts().CPlusPlus)
Douglas Gregorf3564192010-04-26 17:32:49 +00004745 CheckExtraCXXDefaultArguments(D);
4746
Argyrios Kyrtzidisef7022f2011-06-28 03:01:15 +00004747 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
John McCall8cb7bdf2010-06-04 23:28:52 +00004748 QualType ExceptionType = TInfo->getType();
Douglas Gregorf3564192010-04-26 17:32:49 +00004749
Abramo Bagnaradff19302011-03-08 08:55:46 +00004750 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
4751 D.getSourceRange().getBegin(),
4752 D.getIdentifierLoc(),
4753 D.getIdentifier(),
Douglas Gregorf3564192010-04-26 17:32:49 +00004754 D.isInvalidType());
4755
4756 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
4757 if (D.getCXXScopeSpec().isSet()) {
4758 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
4759 << D.getCXXScopeSpec().getRange();
4760 New->setInvalidDecl();
4761 }
4762
4763 // Add the parameter declaration into this scope.
John McCall48871652010-08-21 09:40:31 +00004764 S->AddDecl(New);
Douglas Gregorf3564192010-04-26 17:32:49 +00004765 if (D.getIdentifier())
4766 IdResolver.AddDecl(New);
4767
4768 ProcessDeclAttributes(S, New, D);
4769
4770 if (New->hasAttr<BlocksAttr>())
4771 Diag(New->getLocation(), diag::err_block_on_nonlocal);
John McCall48871652010-08-21 09:40:31 +00004772 return New;
Douglas Gregore11ee112010-04-23 23:01:43 +00004773}
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004774
4775/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004776/// initialization.
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004777void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004778 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004779 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
4780 Iv= Iv->getNextIvar()) {
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004781 QualType QT = Context.getBaseElementType(Iv->getType());
Douglas Gregor527786e2010-05-20 02:24:22 +00004782 if (QT->isRecordType())
Fariborz Jahaniana50b3a22010-08-20 21:21:08 +00004783 Ivars.push_back(Iv);
Fariborz Jahanian38b77a92010-04-27 17:18:58 +00004784 }
4785}
Fariborz Jahanianc83726e2010-04-28 16:11:27 +00004786
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004787void Sema::DiagnoseUseOfUnimplementedSelectors() {
Douglas Gregor72e357f2011-07-28 14:54:22 +00004788 // Load referenced selectors from the external source.
4789 if (ExternalSource) {
4790 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
4791 ExternalSource->ReadReferencedSelectors(Sels);
4792 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
4793 ReferencedSelectors[Sels[I].first] = Sels[I].second;
4794 }
4795
Fariborz Jahanianc9b7c202011-02-04 23:19:27 +00004796 // Warning will be issued only when selector table is
4797 // generated (which means there is at lease one implementation
4798 // in the TU). This is to match gcc's behavior.
4799 if (ReferencedSelectors.empty() ||
4800 !Context.AnyObjCImplementation())
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004801 return;
Chandler Carruth12c8f652015-03-27 00:55:05 +00004802 for (auto &SelectorAndLocation : ReferencedSelectors) {
4803 Selector Sel = SelectorAndLocation.first;
4804 SourceLocation Loc = SelectorAndLocation.second;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004805 if (!LookupImplementedMethodInGlobalPool(Sel))
Chandler Carruth12c8f652015-03-27 00:55:05 +00004806 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004807 }
Fariborz Jahanian6e7e8cc2010-07-22 18:24:20 +00004808}
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004809
4810ObjCIvarDecl *
4811Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
4812 const ObjCPropertyDecl *&PDecl) const {
Fariborz Jahanian1cc7ae12014-01-02 17:24:32 +00004813 if (Method->isClassMethod())
Craig Topperc3ec1492014-05-26 06:22:03 +00004814 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004815 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
4816 if (!IDecl)
Craig Topperc3ec1492014-05-26 06:22:03 +00004817 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004818 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
4819 /*shallowCategoryLookup=*/false,
4820 /*followSuper=*/false);
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004821 if (!Method || !Method->isPropertyAccessor())
Craig Topperc3ec1492014-05-26 06:22:03 +00004822 return nullptr;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004823 if ((PDecl = Method->findPropertyDecl()))
Fariborz Jahanian122d94f2014-01-27 22:27:43 +00004824 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
4825 // property backing ivar must belong to property's class
4826 // or be a private ivar in class's implementation.
4827 // FIXME. fix the const-ness issue.
4828 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
4829 IV->getIdentifier());
4830 return IV;
4831 }
Craig Topperc3ec1492014-05-26 06:22:03 +00004832 return nullptr;
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004833}
4834
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004835namespace {
4836 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
4837 /// accessor references the backing ivar.
Argyrios Kyrtzidis98045c12014-01-03 19:53:09 +00004838 class UnusedBackingIvarChecker :
Richard Smith50668452015-11-24 03:55:01 +00004839 public RecursiveASTVisitor<UnusedBackingIvarChecker> {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004840 public:
4841 Sema &S;
4842 const ObjCMethodDecl *Method;
4843 const ObjCIvarDecl *IvarD;
4844 bool AccessedIvar;
4845 bool InvokedSelfMethod;
4846
4847 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
4848 const ObjCIvarDecl *IvarD)
4849 : S(S), Method(Method), IvarD(IvarD),
4850 AccessedIvar(false), InvokedSelfMethod(false) {
4851 assert(IvarD);
4852 }
4853
4854 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
4855 if (E->getDecl() == IvarD) {
4856 AccessedIvar = true;
4857 return false;
4858 }
4859 return true;
4860 }
4861
4862 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
4863 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
4864 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
4865 InvokedSelfMethod = true;
4866 }
4867 return true;
4868 }
4869 };
Hans Wennborgdcfba332015-10-06 23:40:43 +00004870} // end anonymous namespace
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004871
4872void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
4873 const ObjCImplementationDecl *ImplD) {
4874 if (S->hasUnrecoverableErrorOccurred())
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004875 return;
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004876
Aaron Ballmanf26acce2014-03-13 19:50:17 +00004877 for (const auto *CurMethod : ImplD->instance_methods()) {
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004878 unsigned DIAG = diag::warn_unused_property_backing_ivar;
4879 SourceLocation Loc = CurMethod->getLocation();
Alp Tokerd4a3f0e2014-06-15 23:30:39 +00004880 if (Diags.isIgnored(DIAG, Loc))
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004881 continue;
4882
4883 const ObjCPropertyDecl *PDecl;
4884 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
4885 if (!IV)
4886 continue;
4887
4888 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
4889 Checker.TraverseStmt(CurMethod->getBody());
4890 if (Checker.AccessedIvar)
4891 continue;
4892
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004893 // Do not issue this warning if backing ivar is used somewhere and accessor
Argyrios Kyrtzidis2080d902014-01-03 18:32:18 +00004894 // implementation makes a self call. This is to prevent false positive in
4895 // cases where the ivar is accessed by another method that the accessor
4896 // delegates to.
4897 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
Argyrios Kyrtzidisd8a35322014-01-03 19:39:23 +00004898 Diag(Loc, DIAG) << IV;
Fariborz Jahanian5b3105d2014-01-02 22:42:09 +00004899 Diag(PDecl->getLocation(), diag::note_property_declare);
4900 }
Fariborz Jahanian5e3429c2013-10-25 21:44:50 +00004901 }
4902}