1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements semantic analysis for Objective C declarations.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DataRecursiveASTVisitor.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ExternalSemaSource.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/DenseSet.h"
29
30 using namespace clang;
31
32 /// Check whether the given method, which must be in the 'init'
33 /// family, is a valid member of that family.
34 ///
35 /// \param receiverTypeIfCall - if null, check this as if declaring it;
36 /// if non-null, check this as if making a call to it with the given
37 /// receiver type
38 ///
39 /// \return true to indicate that there was an error and appropriate
40 /// actions were taken
checkInitMethod(ObjCMethodDecl * method,QualType receiverTypeIfCall)41 bool Sema::checkInitMethod(ObjCMethodDecl *method,
42 QualType receiverTypeIfCall) {
43 if (method->isInvalidDecl()) return true;
44
45 // This castAs is safe: methods that don't return an object
46 // pointer won't be inferred as inits and will reject an explicit
47 // objc_method_family(init).
48
49 // We ignore protocols here. Should we? What about Class?
50
51 const ObjCObjectType *result =
52 method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
53
54 if (result->isObjCId()) {
55 return false;
56 } else if (result->isObjCClass()) {
57 // fall through: always an error
58 } else {
59 ObjCInterfaceDecl *resultClass = result->getInterface();
60 assert(resultClass && "unexpected object type!");
61
62 // It's okay for the result type to still be a forward declaration
63 // if we're checking an interface declaration.
64 if (!resultClass->hasDefinition()) {
65 if (receiverTypeIfCall.isNull() &&
66 !isa<ObjCImplementationDecl>(method->getDeclContext()))
67 return false;
68
69 // Otherwise, we try to compare class types.
70 } else {
71 // If this method was declared in a protocol, we can't check
72 // anything unless we have a receiver type that's an interface.
73 const ObjCInterfaceDecl *receiverClass = nullptr;
74 if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75 if (receiverTypeIfCall.isNull())
76 return false;
77
78 receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
79 ->getInterfaceDecl();
80
81 // This can be null for calls to e.g. id<Foo>.
82 if (!receiverClass) return false;
83 } else {
84 receiverClass = method->getClassInterface();
85 assert(receiverClass && "method not associated with a class!");
86 }
87
88 // If either class is a subclass of the other, it's fine.
89 if (receiverClass->isSuperClassOf(resultClass) ||
90 resultClass->isSuperClassOf(receiverClass))
91 return false;
92 }
93 }
94
95 SourceLocation loc = method->getLocation();
96
97 // If we're in a system header, and this is not a call, just make
98 // the method unusable.
99 if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
100 method->addAttr(UnavailableAttr::CreateImplicit(Context,
101 "init method returns a type unrelated to its receiver type",
102 loc));
103 return true;
104 }
105
106 // Otherwise, it's an error.
107 Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108 method->setInvalidDecl();
109 return true;
110 }
111
CheckObjCMethodOverride(ObjCMethodDecl * NewMethod,const ObjCMethodDecl * Overridden)112 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
113 const ObjCMethodDecl *Overridden) {
114 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.
120 QualType ResultType = NewMethod->getReturnType();
121 SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
122
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
150 if (ObjCMethodFamily Family = Overridden->getMethodFamily())
151 Diag(Overridden->getLocation(),
152 diag::note_related_result_type_family)
153 << /*overridden method*/ 0
154 << Family;
155 else
156 Diag(Overridden->getLocation(),
157 diag::note_related_result_type_overridden);
158 }
159 if (getLangOpts().ObjCAutoRefCount) {
160 if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161 Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162 Diag(NewMethod->getLocation(),
163 diag::err_nsreturns_retained_attribute_mismatch) << 1;
164 Diag(Overridden->getLocation(), diag::note_previous_decl)
165 << "method";
166 }
167 if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
168 Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
169 Diag(NewMethod->getLocation(),
170 diag::err_nsreturns_retained_attribute_mismatch) << 0;
171 Diag(Overridden->getLocation(), diag::note_previous_decl)
172 << "method";
173 }
174 ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
175 oe = Overridden->param_end();
176 for (ObjCMethodDecl::param_iterator
177 ni = NewMethod->param_begin(), ne = NewMethod->param_end();
178 ni != ne && oi != oe; ++ni, ++oi) {
179 const ParmVarDecl *oldDecl = (*oi);
180 ParmVarDecl *newDecl = (*ni);
181 if (newDecl->hasAttr<NSConsumedAttr>() !=
182 oldDecl->hasAttr<NSConsumedAttr>()) {
183 Diag(newDecl->getLocation(),
184 diag::err_nsconsumed_attribute_mismatch);
185 Diag(oldDecl->getLocation(), diag::note_previous_decl)
186 << "parameter";
187 }
188 }
189 }
190 }
191
192 /// \brief Check a method declaration for compatibility with the Objective-C
193 /// ARC conventions.
CheckARCMethodDecl(ObjCMethodDecl * method)194 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
195 ObjCMethodFamily family = method->getMethodFamily();
196 switch (family) {
197 case OMF_None:
198 case OMF_finalize:
199 case OMF_retain:
200 case OMF_release:
201 case OMF_autorelease:
202 case OMF_retainCount:
203 case OMF_self:
204 case OMF_initialize:
205 case OMF_performSelector:
206 return false;
207
208 case OMF_dealloc:
209 if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
210 SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
211 if (ResultTypeRange.isInvalid())
212 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
213 << method->getReturnType()
214 << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
215 else
216 Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
217 << method->getReturnType()
218 << FixItHint::CreateReplacement(ResultTypeRange, "void");
219 return true;
220 }
221 return false;
222
223 case OMF_init:
224 // If the method doesn't obey the init rules, don't bother annotating it.
225 if (checkInitMethod(method, QualType()))
226 return true;
227
228 method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
229
230 // Don't add a second copy of this attribute, but otherwise don't
231 // let it be suppressed.
232 if (method->hasAttr<NSReturnsRetainedAttr>())
233 return false;
234 break;
235
236 case OMF_alloc:
237 case OMF_copy:
238 case OMF_mutableCopy:
239 case OMF_new:
240 if (method->hasAttr<NSReturnsRetainedAttr>() ||
241 method->hasAttr<NSReturnsNotRetainedAttr>() ||
242 method->hasAttr<NSReturnsAutoreleasedAttr>())
243 return false;
244 break;
245 }
246
247 method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
248 return false;
249 }
250
DiagnoseObjCImplementedDeprecations(Sema & S,NamedDecl * ND,SourceLocation ImplLoc,int select)251 static void DiagnoseObjCImplementedDeprecations(Sema &S,
252 NamedDecl *ND,
253 SourceLocation ImplLoc,
254 int select) {
255 if (ND && ND->isDeprecated()) {
256 S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
257 if (select == 0)
258 S.Diag(ND->getLocation(), diag::note_method_declared_at)
259 << ND->getDeclName();
260 else
261 S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
262 }
263 }
264
265 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
266 /// pool.
AddAnyMethodToGlobalPool(Decl * D)267 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
268 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
269
270 // If we don't have a valid method decl, simply return.
271 if (!MDecl)
272 return;
273 if (MDecl->isInstanceMethod())
274 AddInstanceMethodToGlobalPool(MDecl, true);
275 else
276 AddFactoryMethodToGlobalPool(MDecl, true);
277 }
278
279 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
280 /// has explicit ownership attribute; false otherwise.
281 static bool
HasExplicitOwnershipAttr(Sema & S,ParmVarDecl * Param)282 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
283 QualType T = Param->getType();
284
285 if (const PointerType *PT = T->getAs<PointerType>()) {
286 T = PT->getPointeeType();
287 } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
288 T = RT->getPointeeType();
289 } else {
290 return true;
291 }
292
293 // If we have a lifetime qualifier, but it's local, we must have
294 // inferred it. So, it is implicit.
295 return !T.getLocalQualifiers().hasObjCLifetime();
296 }
297
298 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
299 /// and user declared, in the method definition's AST.
ActOnStartOfObjCMethodDef(Scope * FnBodyScope,Decl * D)300 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
301 assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
302 ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
303
304 // If we don't have a valid method decl, simply return.
305 if (!MDecl)
306 return;
307
308 // Allow all of Sema to see that we are entering a method definition.
309 PushDeclContext(FnBodyScope, MDecl);
310 PushFunctionScope();
311
312 // Create Decl objects for each parameter, entrring them in the scope for
313 // binding to their use.
314
315 // Insert the invisible arguments, self and _cmd!
316 MDecl->createImplicitParams(Context, MDecl->getClassInterface());
317
318 PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
319 PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
320
321 // The ObjC parser requires parameter names so there's no need to check.
322 CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
323 /*CheckParameterNames=*/false);
324
325 // Introduce all of the other parameters into this scope.
326 for (auto *Param : MDecl->params()) {
327 if (!Param->isInvalidDecl() &&
328 getLangOpts().ObjCAutoRefCount &&
329 !HasExplicitOwnershipAttr(*this, Param))
330 Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
331 Param->getType();
332
333 if (Param->getIdentifier())
334 PushOnScopeChains(Param, FnBodyScope);
335 }
336
337 // In ARC, disallow definition of retain/release/autorelease/retainCount
338 if (getLangOpts().ObjCAutoRefCount) {
339 switch (MDecl->getMethodFamily()) {
340 case OMF_retain:
341 case OMF_retainCount:
342 case OMF_release:
343 case OMF_autorelease:
344 Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
345 << 0 << MDecl->getSelector();
346 break;
347
348 case OMF_None:
349 case OMF_dealloc:
350 case OMF_finalize:
351 case OMF_alloc:
352 case OMF_init:
353 case OMF_mutableCopy:
354 case OMF_copy:
355 case OMF_new:
356 case OMF_self:
357 case OMF_initialize:
358 case OMF_performSelector:
359 break;
360 }
361 }
362
363 // Warn on deprecated methods under -Wdeprecated-implementations,
364 // and prepare for warning on missing super calls.
365 if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
366 ObjCMethodDecl *IMD =
367 IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
368
369 if (IMD) {
370 ObjCImplDecl *ImplDeclOfMethodDef =
371 dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
372 ObjCContainerDecl *ContDeclOfMethodDecl =
373 dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
374 ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
375 if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
376 ImplDeclOfMethodDecl = OID->getImplementation();
377 else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
378 if (CD->IsClassExtension()) {
379 if (ObjCInterfaceDecl *OID = CD->getClassInterface())
380 ImplDeclOfMethodDecl = OID->getImplementation();
381 } else
382 ImplDeclOfMethodDecl = CD->getImplementation();
383 }
384 // No need to issue deprecated warning if deprecated mehod in class/category
385 // is being implemented in its own implementation (no overriding is involved).
386 if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
387 DiagnoseObjCImplementedDeprecations(*this,
388 dyn_cast<NamedDecl>(IMD),
389 MDecl->getLocation(), 0);
390 }
391
392 if (MDecl->getMethodFamily() == OMF_init) {
393 if (MDecl->isDesignatedInitializerForTheInterface()) {
394 getCurFunction()->ObjCIsDesignatedInit = true;
395 getCurFunction()->ObjCWarnForNoDesignatedInitChain =
396 IC->getSuperClass() != nullptr;
397 } else if (IC->hasDesignatedInitializers()) {
398 getCurFunction()->ObjCIsSecondaryInit = true;
399 getCurFunction()->ObjCWarnForNoInitDelegation = true;
400 }
401 }
402
403 // If this is "dealloc" or "finalize", set some bit here.
404 // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
405 // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
406 // Only do this if the current class actually has a superclass.
407 if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
408 ObjCMethodFamily Family = MDecl->getMethodFamily();
409 if (Family == OMF_dealloc) {
410 if (!(getLangOpts().ObjCAutoRefCount ||
411 getLangOpts().getGC() == LangOptions::GCOnly))
412 getCurFunction()->ObjCShouldCallSuper = true;
413
414 } else if (Family == OMF_finalize) {
415 if (Context.getLangOpts().getGC() != LangOptions::NonGC)
416 getCurFunction()->ObjCShouldCallSuper = true;
417
418 } else {
419 const ObjCMethodDecl *SuperMethod =
420 SuperClass->lookupMethod(MDecl->getSelector(),
421 MDecl->isInstanceMethod());
422 getCurFunction()->ObjCShouldCallSuper =
423 (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
424 }
425 }
426 }
427 }
428
429 namespace {
430
431 // Callback to only accept typo corrections that are Objective-C classes.
432 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
433 // function will reject corrections to that class.
434 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
435 public:
ObjCInterfaceValidatorCCC()436 ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
ObjCInterfaceValidatorCCC(ObjCInterfaceDecl * IDecl)437 explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
438 : CurrentIDecl(IDecl) {}
439
ValidateCandidate(const TypoCorrection & candidate)440 bool ValidateCandidate(const TypoCorrection &candidate) override {
441 ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
442 return ID && !declaresSameEntity(ID, CurrentIDecl);
443 }
444
445 private:
446 ObjCInterfaceDecl *CurrentIDecl;
447 };
448
449 }
450
451 Decl *Sema::
ActOnStartClassInterface(SourceLocation AtInterfaceLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * SuperName,SourceLocation SuperLoc,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc,AttributeList * AttrList)452 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
453 IdentifierInfo *ClassName, SourceLocation ClassLoc,
454 IdentifierInfo *SuperName, SourceLocation SuperLoc,
455 Decl * const *ProtoRefs, unsigned NumProtoRefs,
456 const SourceLocation *ProtoLocs,
457 SourceLocation EndProtoLoc, AttributeList *AttrList) {
458 assert(ClassName && "Missing class identifier");
459
460 // Check for another declaration kind with the same name.
461 NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
462 LookupOrdinaryName, ForRedeclaration);
463
464 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
465 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
466 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
467 }
468
469 // Create a declaration to describe this @interface.
470 ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
471
472 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
473 // A previous decl with a different name is because of
474 // @compatibility_alias, for example:
475 // \code
476 // @class NewImage;
477 // @compatibility_alias OldImage NewImage;
478 // \endcode
479 // A lookup for 'OldImage' will return the 'NewImage' decl.
480 //
481 // In such a case use the real declaration name, instead of the alias one,
482 // otherwise we will break IdentifierResolver and redecls-chain invariants.
483 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
484 // has been aliased.
485 ClassName = PrevIDecl->getIdentifier();
486 }
487
488 ObjCInterfaceDecl *IDecl
489 = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
490 PrevIDecl, ClassLoc);
491
492 if (PrevIDecl) {
493 // Class already seen. Was it a definition?
494 if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
495 Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
496 << PrevIDecl->getDeclName();
497 Diag(Def->getLocation(), diag::note_previous_definition);
498 IDecl->setInvalidDecl();
499 }
500 }
501
502 if (AttrList)
503 ProcessDeclAttributeList(TUScope, IDecl, AttrList);
504 PushOnScopeChains(IDecl, TUScope);
505
506 // Start the definition of this class. If we're in a redefinition case, there
507 // may already be a definition, so we'll end up adding to it.
508 if (!IDecl->hasDefinition())
509 IDecl->startDefinition();
510
511 if (SuperName) {
512 // Check if a different kind of symbol declared in this scope.
513 PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
514 LookupOrdinaryName);
515
516 if (!PrevDecl) {
517 // Try to correct for a typo in the superclass name without correcting
518 // to the class we're defining.
519 if (TypoCorrection Corrected =
520 CorrectTypo(DeclarationNameInfo(SuperName, SuperLoc),
521 LookupOrdinaryName, TUScope, nullptr,
522 llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
523 CTK_ErrorRecovery)) {
524 diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
525 << SuperName << ClassName);
526 PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
527 }
528 }
529
530 if (declaresSameEntity(PrevDecl, IDecl)) {
531 Diag(SuperLoc, diag::err_recursive_superclass)
532 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
533 IDecl->setEndOfDefinitionLoc(ClassLoc);
534 } else {
535 ObjCInterfaceDecl *SuperClassDecl =
536 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
537
538 // Diagnose classes that inherit from deprecated classes.
539 if (SuperClassDecl)
540 (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
541
542 if (PrevDecl && !SuperClassDecl) {
543 // The previous declaration was not a class decl. Check if we have a
544 // typedef. If we do, get the underlying class type.
545 if (const TypedefNameDecl *TDecl =
546 dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
547 QualType T = TDecl->getUnderlyingType();
548 if (T->isObjCObjectType()) {
549 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
550 SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
551 // This handles the following case:
552 // @interface NewI @end
553 // typedef NewI DeprI __attribute__((deprecated("blah")))
554 // @interface SI : DeprI /* warn here */ @end
555 (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
556 }
557 }
558 }
559
560 // This handles the following case:
561 //
562 // typedef int SuperClass;
563 // @interface MyClass : SuperClass {} @end
564 //
565 if (!SuperClassDecl) {
566 Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
567 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
568 }
569 }
570
571 if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
572 if (!SuperClassDecl)
573 Diag(SuperLoc, diag::err_undef_superclass)
574 << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
575 else if (RequireCompleteType(SuperLoc,
576 Context.getObjCInterfaceType(SuperClassDecl),
577 diag::err_forward_superclass,
578 SuperClassDecl->getDeclName(),
579 ClassName,
580 SourceRange(AtInterfaceLoc, ClassLoc))) {
581 SuperClassDecl = nullptr;
582 }
583 }
584 IDecl->setSuperClass(SuperClassDecl);
585 IDecl->setSuperClassLoc(SuperLoc);
586 IDecl->setEndOfDefinitionLoc(SuperLoc);
587 }
588 } else { // we have a root class.
589 IDecl->setEndOfDefinitionLoc(ClassLoc);
590 }
591
592 // Check then save referenced protocols.
593 if (NumProtoRefs) {
594 IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
595 ProtoLocs, Context);
596 IDecl->setEndOfDefinitionLoc(EndProtoLoc);
597 }
598
599 CheckObjCDeclScope(IDecl);
600 return ActOnObjCContainerStartDefinition(IDecl);
601 }
602
603 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
604 /// typedef'ed use for a qualified super class and adds them to the list
605 /// of the protocols.
ActOnTypedefedProtocols(SmallVectorImpl<Decl * > & ProtocolRefs,IdentifierInfo * SuperName,SourceLocation SuperLoc)606 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
607 IdentifierInfo *SuperName,
608 SourceLocation SuperLoc) {
609 if (!SuperName)
610 return;
611 NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
612 LookupOrdinaryName);
613 if (!IDecl)
614 return;
615
616 if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
617 QualType T = TDecl->getUnderlyingType();
618 if (T->isObjCObjectType())
619 if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
620 ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
621 }
622 }
623
624 /// ActOnCompatibilityAlias - this action is called after complete parsing of
625 /// a \@compatibility_alias declaration. It sets up the alias relationships.
ActOnCompatibilityAlias(SourceLocation AtLoc,IdentifierInfo * AliasName,SourceLocation AliasLocation,IdentifierInfo * ClassName,SourceLocation ClassLocation)626 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
627 IdentifierInfo *AliasName,
628 SourceLocation AliasLocation,
629 IdentifierInfo *ClassName,
630 SourceLocation ClassLocation) {
631 // Look for previous declaration of alias name
632 NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
633 LookupOrdinaryName, ForRedeclaration);
634 if (ADecl) {
635 Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
636 Diag(ADecl->getLocation(), diag::note_previous_declaration);
637 return nullptr;
638 }
639 // Check for class declaration
640 NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
641 LookupOrdinaryName, ForRedeclaration);
642 if (const TypedefNameDecl *TDecl =
643 dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
644 QualType T = TDecl->getUnderlyingType();
645 if (T->isObjCObjectType()) {
646 if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
647 ClassName = IDecl->getIdentifier();
648 CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
649 LookupOrdinaryName, ForRedeclaration);
650 }
651 }
652 }
653 ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
654 if (!CDecl) {
655 Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
656 if (CDeclU)
657 Diag(CDeclU->getLocation(), diag::note_previous_declaration);
658 return nullptr;
659 }
660
661 // Everything checked out, instantiate a new alias declaration AST.
662 ObjCCompatibleAliasDecl *AliasDecl =
663 ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
664
665 if (!CheckObjCDeclScope(AliasDecl))
666 PushOnScopeChains(AliasDecl, TUScope);
667
668 return AliasDecl;
669 }
670
CheckForwardProtocolDeclarationForCircularDependency(IdentifierInfo * PName,SourceLocation & Ploc,SourceLocation PrevLoc,const ObjCList<ObjCProtocolDecl> & PList)671 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
672 IdentifierInfo *PName,
673 SourceLocation &Ploc, SourceLocation PrevLoc,
674 const ObjCList<ObjCProtocolDecl> &PList) {
675
676 bool res = false;
677 for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
678 E = PList.end(); I != E; ++I) {
679 if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
680 Ploc)) {
681 if (PDecl->getIdentifier() == PName) {
682 Diag(Ploc, diag::err_protocol_has_circular_dependency);
683 Diag(PrevLoc, diag::note_previous_definition);
684 res = true;
685 }
686
687 if (!PDecl->hasDefinition())
688 continue;
689
690 if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
691 PDecl->getLocation(), PDecl->getReferencedProtocols()))
692 res = true;
693 }
694 }
695 return res;
696 }
697
698 Decl *
ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,IdentifierInfo * ProtocolName,SourceLocation ProtocolLoc,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc,AttributeList * AttrList)699 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
700 IdentifierInfo *ProtocolName,
701 SourceLocation ProtocolLoc,
702 Decl * const *ProtoRefs,
703 unsigned NumProtoRefs,
704 const SourceLocation *ProtoLocs,
705 SourceLocation EndProtoLoc,
706 AttributeList *AttrList) {
707 bool err = false;
708 // FIXME: Deal with AttrList.
709 assert(ProtocolName && "Missing protocol identifier");
710 ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
711 ForRedeclaration);
712 ObjCProtocolDecl *PDecl = nullptr;
713 if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
714 // If we already have a definition, complain.
715 Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
716 Diag(Def->getLocation(), diag::note_previous_definition);
717
718 // Create a new protocol that is completely distinct from previous
719 // declarations, and do not make this protocol available for name lookup.
720 // That way, we'll end up completely ignoring the duplicate.
721 // FIXME: Can we turn this into an error?
722 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
723 ProtocolLoc, AtProtoInterfaceLoc,
724 /*PrevDecl=*/nullptr);
725 PDecl->startDefinition();
726 } else {
727 if (PrevDecl) {
728 // Check for circular dependencies among protocol declarations. This can
729 // only happen if this protocol was forward-declared.
730 ObjCList<ObjCProtocolDecl> PList;
731 PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
732 err = CheckForwardProtocolDeclarationForCircularDependency(
733 ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
734 }
735
736 // Create the new declaration.
737 PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
738 ProtocolLoc, AtProtoInterfaceLoc,
739 /*PrevDecl=*/PrevDecl);
740
741 PushOnScopeChains(PDecl, TUScope);
742 PDecl->startDefinition();
743 }
744
745 if (AttrList)
746 ProcessDeclAttributeList(TUScope, PDecl, AttrList);
747
748 // Merge attributes from previous declarations.
749 if (PrevDecl)
750 mergeDeclAttributes(PDecl, PrevDecl);
751
752 if (!err && NumProtoRefs ) {
753 /// Check then save referenced protocols.
754 PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
755 ProtoLocs, Context);
756 }
757
758 CheckObjCDeclScope(PDecl);
759 return ActOnObjCContainerStartDefinition(PDecl);
760 }
761
NestedProtocolHasNoDefinition(ObjCProtocolDecl * PDecl,ObjCProtocolDecl * & UndefinedProtocol)762 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
763 ObjCProtocolDecl *&UndefinedProtocol) {
764 if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
765 UndefinedProtocol = PDecl;
766 return true;
767 }
768
769 for (auto *PI : PDecl->protocols())
770 if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
771 UndefinedProtocol = PI;
772 return true;
773 }
774 return false;
775 }
776
777 /// FindProtocolDeclaration - This routine looks up protocols and
778 /// issues an error if they are not declared. It returns list of
779 /// protocol declarations in its 'Protocols' argument.
780 void
FindProtocolDeclaration(bool WarnOnDeclarations,const IdentifierLocPair * ProtocolId,unsigned NumProtocols,SmallVectorImpl<Decl * > & Protocols)781 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
782 const IdentifierLocPair *ProtocolId,
783 unsigned NumProtocols,
784 SmallVectorImpl<Decl *> &Protocols) {
785 for (unsigned i = 0; i != NumProtocols; ++i) {
786 ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
787 ProtocolId[i].second);
788 if (!PDecl) {
789 TypoCorrection Corrected = CorrectTypo(
790 DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
791 LookupObjCProtocolName, TUScope, nullptr,
792 llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
793 CTK_ErrorRecovery);
794 if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
795 diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
796 << ProtocolId[i].first);
797 }
798
799 if (!PDecl) {
800 Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
801 << ProtocolId[i].first;
802 continue;
803 }
804 // If this is a forward protocol declaration, get its definition.
805 if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
806 PDecl = PDecl->getDefinition();
807
808 (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
809
810 // If this is a forward declaration and we are supposed to warn in this
811 // case, do it.
812 // FIXME: Recover nicely in the hidden case.
813 ObjCProtocolDecl *UndefinedProtocol;
814
815 if (WarnOnDeclarations &&
816 NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
817 Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
818 << ProtocolId[i].first;
819 Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
820 << UndefinedProtocol;
821 }
822 Protocols.push_back(PDecl);
823 }
824 }
825
826 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
827 /// a class method in its extension.
828 ///
DiagnoseClassExtensionDupMethods(ObjCCategoryDecl * CAT,ObjCInterfaceDecl * ID)829 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
830 ObjCInterfaceDecl *ID) {
831 if (!ID)
832 return; // Possibly due to previous error
833
834 llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
835 for (auto *MD : ID->methods())
836 MethodMap[MD->getSelector()] = MD;
837
838 if (MethodMap.empty())
839 return;
840 for (const auto *Method : CAT->methods()) {
841 const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
842 if (PrevMethod &&
843 (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
844 !MatchTwoMethodDeclarations(Method, PrevMethod)) {
845 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
846 << Method->getDeclName();
847 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
848 }
849 }
850 }
851
852 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
853 Sema::DeclGroupPtrTy
ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,const IdentifierLocPair * IdentList,unsigned NumElts,AttributeList * attrList)854 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
855 const IdentifierLocPair *IdentList,
856 unsigned NumElts,
857 AttributeList *attrList) {
858 SmallVector<Decl *, 8> DeclsInGroup;
859 for (unsigned i = 0; i != NumElts; ++i) {
860 IdentifierInfo *Ident = IdentList[i].first;
861 ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
862 ForRedeclaration);
863 ObjCProtocolDecl *PDecl
864 = ObjCProtocolDecl::Create(Context, CurContext, Ident,
865 IdentList[i].second, AtProtocolLoc,
866 PrevDecl);
867
868 PushOnScopeChains(PDecl, TUScope);
869 CheckObjCDeclScope(PDecl);
870
871 if (attrList)
872 ProcessDeclAttributeList(TUScope, PDecl, attrList);
873
874 if (PrevDecl)
875 mergeDeclAttributes(PDecl, PrevDecl);
876
877 DeclsInGroup.push_back(PDecl);
878 }
879
880 return BuildDeclaratorGroup(DeclsInGroup, false);
881 }
882
883 Decl *Sema::
ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * CategoryName,SourceLocation CategoryLoc,Decl * const * ProtoRefs,unsigned NumProtoRefs,const SourceLocation * ProtoLocs,SourceLocation EndProtoLoc)884 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
885 IdentifierInfo *ClassName, SourceLocation ClassLoc,
886 IdentifierInfo *CategoryName,
887 SourceLocation CategoryLoc,
888 Decl * const *ProtoRefs,
889 unsigned NumProtoRefs,
890 const SourceLocation *ProtoLocs,
891 SourceLocation EndProtoLoc) {
892 ObjCCategoryDecl *CDecl;
893 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
894
895 /// Check that class of this category is already completely declared.
896
897 if (!IDecl
898 || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
899 diag::err_category_forward_interface,
900 CategoryName == nullptr)) {
901 // Create an invalid ObjCCategoryDecl to serve as context for
902 // the enclosing method declarations. We mark the decl invalid
903 // to make it clear that this isn't a valid AST.
904 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
905 ClassLoc, CategoryLoc, CategoryName,IDecl);
906 CDecl->setInvalidDecl();
907 CurContext->addDecl(CDecl);
908
909 if (!IDecl)
910 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
911 return ActOnObjCContainerStartDefinition(CDecl);
912 }
913
914 if (!CategoryName && IDecl->getImplementation()) {
915 Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
916 Diag(IDecl->getImplementation()->getLocation(),
917 diag::note_implementation_declared);
918 }
919
920 if (CategoryName) {
921 /// Check for duplicate interface declaration for this category
922 if (ObjCCategoryDecl *Previous
923 = IDecl->FindCategoryDeclaration(CategoryName)) {
924 // Class extensions can be declared multiple times, categories cannot.
925 Diag(CategoryLoc, diag::warn_dup_category_def)
926 << ClassName << CategoryName;
927 Diag(Previous->getLocation(), diag::note_previous_definition);
928 }
929 }
930
931 CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
932 ClassLoc, CategoryLoc, CategoryName, IDecl);
933 // FIXME: PushOnScopeChains?
934 CurContext->addDecl(CDecl);
935
936 if (NumProtoRefs) {
937 CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
938 ProtoLocs, Context);
939 // Protocols in the class extension belong to the class.
940 if (CDecl->IsClassExtension())
941 IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
942 NumProtoRefs, Context);
943 }
944
945 CheckObjCDeclScope(CDecl);
946 return ActOnObjCContainerStartDefinition(CDecl);
947 }
948
949 /// ActOnStartCategoryImplementation - Perform semantic checks on the
950 /// category implementation declaration and build an ObjCCategoryImplDecl
951 /// object.
ActOnStartCategoryImplementation(SourceLocation AtCatImplLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * CatName,SourceLocation CatLoc)952 Decl *Sema::ActOnStartCategoryImplementation(
953 SourceLocation AtCatImplLoc,
954 IdentifierInfo *ClassName, SourceLocation ClassLoc,
955 IdentifierInfo *CatName, SourceLocation CatLoc) {
956 ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
957 ObjCCategoryDecl *CatIDecl = nullptr;
958 if (IDecl && IDecl->hasDefinition()) {
959 CatIDecl = IDecl->FindCategoryDeclaration(CatName);
960 if (!CatIDecl) {
961 // Category @implementation with no corresponding @interface.
962 // Create and install one.
963 CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
964 ClassLoc, CatLoc,
965 CatName, IDecl);
966 CatIDecl->setImplicit();
967 }
968 }
969
970 ObjCCategoryImplDecl *CDecl =
971 ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
972 ClassLoc, AtCatImplLoc, CatLoc);
973 /// Check that class of this category is already completely declared.
974 if (!IDecl) {
975 Diag(ClassLoc, diag::err_undef_interface) << ClassName;
976 CDecl->setInvalidDecl();
977 } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
978 diag::err_undef_interface)) {
979 CDecl->setInvalidDecl();
980 }
981
982 // FIXME: PushOnScopeChains?
983 CurContext->addDecl(CDecl);
984
985 // If the interface is deprecated/unavailable, warn/error about it.
986 if (IDecl)
987 DiagnoseUseOfDecl(IDecl, ClassLoc);
988
989 /// Check that CatName, category name, is not used in another implementation.
990 if (CatIDecl) {
991 if (CatIDecl->getImplementation()) {
992 Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
993 << CatName;
994 Diag(CatIDecl->getImplementation()->getLocation(),
995 diag::note_previous_definition);
996 CDecl->setInvalidDecl();
997 } else {
998 CatIDecl->setImplementation(CDecl);
999 // Warn on implementating category of deprecated class under
1000 // -Wdeprecated-implementations flag.
1001 DiagnoseObjCImplementedDeprecations(*this,
1002 dyn_cast<NamedDecl>(IDecl),
1003 CDecl->getLocation(), 2);
1004 }
1005 }
1006
1007 CheckObjCDeclScope(CDecl);
1008 return ActOnObjCContainerStartDefinition(CDecl);
1009 }
1010
ActOnStartClassImplementation(SourceLocation AtClassImplLoc,IdentifierInfo * ClassName,SourceLocation ClassLoc,IdentifierInfo * SuperClassname,SourceLocation SuperClassLoc)1011 Decl *Sema::ActOnStartClassImplementation(
1012 SourceLocation AtClassImplLoc,
1013 IdentifierInfo *ClassName, SourceLocation ClassLoc,
1014 IdentifierInfo *SuperClassname,
1015 SourceLocation SuperClassLoc) {
1016 ObjCInterfaceDecl *IDecl = nullptr;
1017 // Check for another declaration kind with the same name.
1018 NamedDecl *PrevDecl
1019 = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1020 ForRedeclaration);
1021 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1022 Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1023 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1024 } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1025 RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1026 diag::warn_undef_interface);
1027 } else {
1028 // We did not find anything with the name ClassName; try to correct for
1029 // typos in the class name.
1030 TypoCorrection Corrected = CorrectTypo(
1031 DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1032 nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
1033 if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1034 // Suggest the (potentially) correct interface name. Don't provide a
1035 // code-modification hint or use the typo name for recovery, because
1036 // this is just a warning. The program may actually be correct.
1037 diagnoseTypo(Corrected,
1038 PDiag(diag::warn_undef_interface_suggest) << ClassName,
1039 /*ErrorRecovery*/false);
1040 } else {
1041 Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1042 }
1043 }
1044
1045 // Check that super class name is valid class name
1046 ObjCInterfaceDecl *SDecl = nullptr;
1047 if (SuperClassname) {
1048 // Check if a different kind of symbol declared in this scope.
1049 PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1050 LookupOrdinaryName);
1051 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1052 Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1053 << SuperClassname;
1054 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1055 } else {
1056 SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1057 if (SDecl && !SDecl->hasDefinition())
1058 SDecl = nullptr;
1059 if (!SDecl)
1060 Diag(SuperClassLoc, diag::err_undef_superclass)
1061 << SuperClassname << ClassName;
1062 else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1063 // This implementation and its interface do not have the same
1064 // super class.
1065 Diag(SuperClassLoc, diag::err_conflicting_super_class)
1066 << SDecl->getDeclName();
1067 Diag(SDecl->getLocation(), diag::note_previous_definition);
1068 }
1069 }
1070 }
1071
1072 if (!IDecl) {
1073 // Legacy case of @implementation with no corresponding @interface.
1074 // Build, chain & install the interface decl into the identifier.
1075
1076 // FIXME: Do we support attributes on the @implementation? If so we should
1077 // copy them over.
1078 IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1079 ClassName, /*PrevDecl=*/nullptr, ClassLoc,
1080 true);
1081 IDecl->startDefinition();
1082 if (SDecl) {
1083 IDecl->setSuperClass(SDecl);
1084 IDecl->setSuperClassLoc(SuperClassLoc);
1085 IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1086 } else {
1087 IDecl->setEndOfDefinitionLoc(ClassLoc);
1088 }
1089
1090 PushOnScopeChains(IDecl, TUScope);
1091 } else {
1092 // Mark the interface as being completed, even if it was just as
1093 // @class ....;
1094 // declaration; the user cannot reopen it.
1095 if (!IDecl->hasDefinition())
1096 IDecl->startDefinition();
1097 }
1098
1099 ObjCImplementationDecl* IMPDecl =
1100 ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1101 ClassLoc, AtClassImplLoc, SuperClassLoc);
1102
1103 if (CheckObjCDeclScope(IMPDecl))
1104 return ActOnObjCContainerStartDefinition(IMPDecl);
1105
1106 // Check that there is no duplicate implementation of this class.
1107 if (IDecl->getImplementation()) {
1108 // FIXME: Don't leak everything!
1109 Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1110 Diag(IDecl->getImplementation()->getLocation(),
1111 diag::note_previous_definition);
1112 IMPDecl->setInvalidDecl();
1113 } else { // add it to the list.
1114 IDecl->setImplementation(IMPDecl);
1115 PushOnScopeChains(IMPDecl, TUScope);
1116 // Warn on implementating deprecated class under
1117 // -Wdeprecated-implementations flag.
1118 DiagnoseObjCImplementedDeprecations(*this,
1119 dyn_cast<NamedDecl>(IDecl),
1120 IMPDecl->getLocation(), 1);
1121 }
1122 return ActOnObjCContainerStartDefinition(IMPDecl);
1123 }
1124
1125 Sema::DeclGroupPtrTy
ActOnFinishObjCImplementation(Decl * ObjCImpDecl,ArrayRef<Decl * > Decls)1126 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1127 SmallVector<Decl *, 64> DeclsInGroup;
1128 DeclsInGroup.reserve(Decls.size() + 1);
1129
1130 for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1131 Decl *Dcl = Decls[i];
1132 if (!Dcl)
1133 continue;
1134 if (Dcl->getDeclContext()->isFileContext())
1135 Dcl->setTopLevelDeclInObjCContainer();
1136 DeclsInGroup.push_back(Dcl);
1137 }
1138
1139 DeclsInGroup.push_back(ObjCImpDecl);
1140
1141 return BuildDeclaratorGroup(DeclsInGroup, false);
1142 }
1143
CheckImplementationIvars(ObjCImplementationDecl * ImpDecl,ObjCIvarDecl ** ivars,unsigned numIvars,SourceLocation RBrace)1144 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1145 ObjCIvarDecl **ivars, unsigned numIvars,
1146 SourceLocation RBrace) {
1147 assert(ImpDecl && "missing implementation decl");
1148 ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
1149 if (!IDecl)
1150 return;
1151 /// Check case of non-existing \@interface decl.
1152 /// (legacy objective-c \@implementation decl without an \@interface decl).
1153 /// Add implementations's ivar to the synthesize class's ivar list.
1154 if (IDecl->isImplicitInterfaceDecl()) {
1155 IDecl->setEndOfDefinitionLoc(RBrace);
1156 // Add ivar's to class's DeclContext.
1157 for (unsigned i = 0, e = numIvars; i != e; ++i) {
1158 ivars[i]->setLexicalDeclContext(ImpDecl);
1159 IDecl->makeDeclVisibleInContext(ivars[i]);
1160 ImpDecl->addDecl(ivars[i]);
1161 }
1162
1163 return;
1164 }
1165 // If implementation has empty ivar list, just return.
1166 if (numIvars == 0)
1167 return;
1168
1169 assert(ivars && "missing @implementation ivars");
1170 if (LangOpts.ObjCRuntime.isNonFragile()) {
1171 if (ImpDecl->getSuperClass())
1172 Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1173 for (unsigned i = 0; i < numIvars; i++) {
1174 ObjCIvarDecl* ImplIvar = ivars[i];
1175 if (const ObjCIvarDecl *ClsIvar =
1176 IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1177 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1178 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1179 continue;
1180 }
1181 // Check class extensions (unnamed categories) for duplicate ivars.
1182 for (const auto *CDecl : IDecl->visible_extensions()) {
1183 if (const ObjCIvarDecl *ClsExtIvar =
1184 CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1185 Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1186 Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
1187 continue;
1188 }
1189 }
1190 // Instance ivar to Implementation's DeclContext.
1191 ImplIvar->setLexicalDeclContext(ImpDecl);
1192 IDecl->makeDeclVisibleInContext(ImplIvar);
1193 ImpDecl->addDecl(ImplIvar);
1194 }
1195 return;
1196 }
1197 // Check interface's Ivar list against those in the implementation.
1198 // names and types must match.
1199 //
1200 unsigned j = 0;
1201 ObjCInterfaceDecl::ivar_iterator
1202 IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1203 for (; numIvars > 0 && IVI != IVE; ++IVI) {
1204 ObjCIvarDecl* ImplIvar = ivars[j++];
1205 ObjCIvarDecl* ClsIvar = *IVI;
1206 assert (ImplIvar && "missing implementation ivar");
1207 assert (ClsIvar && "missing class ivar");
1208
1209 // First, make sure the types match.
1210 if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1211 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1212 << ImplIvar->getIdentifier()
1213 << ImplIvar->getType() << ClsIvar->getType();
1214 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1215 } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1216 ImplIvar->getBitWidthValue(Context) !=
1217 ClsIvar->getBitWidthValue(Context)) {
1218 Diag(ImplIvar->getBitWidth()->getLocStart(),
1219 diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1220 Diag(ClsIvar->getBitWidth()->getLocStart(),
1221 diag::note_previous_definition);
1222 }
1223 // Make sure the names are identical.
1224 if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1225 Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1226 << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1227 Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1228 }
1229 --numIvars;
1230 }
1231
1232 if (numIvars > 0)
1233 Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
1234 else if (IVI != IVE)
1235 Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
1236 }
1237
WarnUndefinedMethod(Sema & S,SourceLocation ImpLoc,ObjCMethodDecl * method,bool & IncompleteImpl,unsigned DiagID,NamedDecl * NeededFor=nullptr)1238 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
1239 ObjCMethodDecl *method,
1240 bool &IncompleteImpl,
1241 unsigned DiagID,
1242 NamedDecl *NeededFor = nullptr) {
1243 // No point warning no definition of method which is 'unavailable'.
1244 switch (method->getAvailability()) {
1245 case AR_Available:
1246 case AR_Deprecated:
1247 break;
1248
1249 // Don't warn about unavailable or not-yet-introduced methods.
1250 case AR_NotYetIntroduced:
1251 case AR_Unavailable:
1252 return;
1253 }
1254
1255 // FIXME: For now ignore 'IncompleteImpl'.
1256 // Previously we grouped all unimplemented methods under a single
1257 // warning, but some users strongly voiced that they would prefer
1258 // separate warnings. We will give that approach a try, as that
1259 // matches what we do with protocols.
1260 {
1261 const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
1262 B << method;
1263 if (NeededFor)
1264 B << NeededFor;
1265 }
1266
1267 // Issue a note to the original declaration.
1268 SourceLocation MethodLoc = method->getLocStart();
1269 if (MethodLoc.isValid())
1270 S.Diag(MethodLoc, diag::note_method_declared_at) << method;
1271 }
1272
1273 /// Determines if type B can be substituted for type A. Returns true if we can
1274 /// guarantee that anything that the user will do to an object of type A can
1275 /// also be done to an object of type B. This is trivially true if the two
1276 /// types are the same, or if B is a subclass of A. It becomes more complex
1277 /// in cases where protocols are involved.
1278 ///
1279 /// Object types in Objective-C describe the minimum requirements for an
1280 /// object, rather than providing a complete description of a type. For
1281 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1282 /// The principle of substitutability means that we may use an instance of A
1283 /// anywhere that we may use an instance of B - it will implement all of the
1284 /// ivars of B and all of the methods of B.
1285 ///
1286 /// This substitutability is important when type checking methods, because
1287 /// the implementation may have stricter type definitions than the interface.
1288 /// The interface specifies minimum requirements, but the implementation may
1289 /// have more accurate ones. For example, a method may privately accept
1290 /// instances of B, but only publish that it accepts instances of A. Any
1291 /// object passed to it will be type checked against B, and so will implicitly
1292 /// by a valid A*. Similarly, a method may return a subclass of the class that
1293 /// it is declared as returning.
1294 ///
1295 /// This is most important when considering subclassing. A method in a
1296 /// subclass must accept any object as an argument that its superclass's
1297 /// implementation accepts. It may, however, accept a more general type
1298 /// without breaking substitutability (i.e. you can still use the subclass
1299 /// anywhere that you can use the superclass, but not vice versa). The
1300 /// converse requirement applies to return types: the return type for a
1301 /// subclass method must be a valid object of the kind that the superclass
1302 /// advertises, but it may be specified more accurately. This avoids the need
1303 /// for explicit down-casting by callers.
1304 ///
1305 /// Note: This is a stricter requirement than for assignment.
isObjCTypeSubstitutable(ASTContext & Context,const ObjCObjectPointerType * A,const ObjCObjectPointerType * B,bool rejectId)1306 static bool isObjCTypeSubstitutable(ASTContext &Context,
1307 const ObjCObjectPointerType *A,
1308 const ObjCObjectPointerType *B,
1309 bool rejectId) {
1310 // Reject a protocol-unqualified id.
1311 if (rejectId && B->isObjCIdType()) return false;
1312
1313 // If B is a qualified id, then A must also be a qualified id and it must
1314 // implement all of the protocols in B. It may not be a qualified class.
1315 // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1316 // stricter definition so it is not substitutable for id<A>.
1317 if (B->isObjCQualifiedIdType()) {
1318 return A->isObjCQualifiedIdType() &&
1319 Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1320 QualType(B,0),
1321 false);
1322 }
1323
1324 /*
1325 // id is a special type that bypasses type checking completely. We want a
1326 // warning when it is used in one place but not another.
1327 if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1328
1329
1330 // If B is a qualified id, then A must also be a qualified id (which it isn't
1331 // if we've got this far)
1332 if (B->isObjCQualifiedIdType()) return false;
1333 */
1334
1335 // Now we know that A and B are (potentially-qualified) class types. The
1336 // normal rules for assignment apply.
1337 return Context.canAssignObjCInterfaces(A, B);
1338 }
1339
getTypeRange(TypeSourceInfo * TSI)1340 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1341 return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1342 }
1343
CheckMethodOverrideReturn(Sema & S,ObjCMethodDecl * MethodImpl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl,bool IsOverridingMode,bool Warn)1344 static bool CheckMethodOverrideReturn(Sema &S,
1345 ObjCMethodDecl *MethodImpl,
1346 ObjCMethodDecl *MethodDecl,
1347 bool IsProtocolMethodDecl,
1348 bool IsOverridingMode,
1349 bool Warn) {
1350 if (IsProtocolMethodDecl &&
1351 (MethodDecl->getObjCDeclQualifier() !=
1352 MethodImpl->getObjCDeclQualifier())) {
1353 if (Warn) {
1354 S.Diag(MethodImpl->getLocation(),
1355 (IsOverridingMode
1356 ? diag::warn_conflicting_overriding_ret_type_modifiers
1357 : diag::warn_conflicting_ret_type_modifiers))
1358 << MethodImpl->getDeclName()
1359 << MethodImpl->getReturnTypeSourceRange();
1360 S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1361 << MethodDecl->getReturnTypeSourceRange();
1362 }
1363 else
1364 return false;
1365 }
1366
1367 if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
1368 MethodDecl->getReturnType()))
1369 return true;
1370 if (!Warn)
1371 return false;
1372
1373 unsigned DiagID =
1374 IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1375 : diag::warn_conflicting_ret_types;
1376
1377 // Mismatches between ObjC pointers go into a different warning
1378 // category, and sometimes they're even completely whitelisted.
1379 if (const ObjCObjectPointerType *ImplPtrTy =
1380 MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1381 if (const ObjCObjectPointerType *IfacePtrTy =
1382 MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1383 // Allow non-matching return types as long as they don't violate
1384 // the principle of substitutability. Specifically, we permit
1385 // return types that are subclasses of the declared return type,
1386 // or that are more-qualified versions of the declared type.
1387 if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1388 return false;
1389
1390 DiagID =
1391 IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1392 : diag::warn_non_covariant_ret_types;
1393 }
1394 }
1395
1396 S.Diag(MethodImpl->getLocation(), DiagID)
1397 << MethodImpl->getDeclName() << MethodDecl->getReturnType()
1398 << MethodImpl->getReturnType()
1399 << MethodImpl->getReturnTypeSourceRange();
1400 S.Diag(MethodDecl->getLocation(), IsOverridingMode
1401 ? diag::note_previous_declaration
1402 : diag::note_previous_definition)
1403 << MethodDecl->getReturnTypeSourceRange();
1404 return false;
1405 }
1406
CheckMethodOverrideParam(Sema & S,ObjCMethodDecl * MethodImpl,ObjCMethodDecl * MethodDecl,ParmVarDecl * ImplVar,ParmVarDecl * IfaceVar,bool IsProtocolMethodDecl,bool IsOverridingMode,bool Warn)1407 static bool CheckMethodOverrideParam(Sema &S,
1408 ObjCMethodDecl *MethodImpl,
1409 ObjCMethodDecl *MethodDecl,
1410 ParmVarDecl *ImplVar,
1411 ParmVarDecl *IfaceVar,
1412 bool IsProtocolMethodDecl,
1413 bool IsOverridingMode,
1414 bool Warn) {
1415 if (IsProtocolMethodDecl &&
1416 (ImplVar->getObjCDeclQualifier() !=
1417 IfaceVar->getObjCDeclQualifier())) {
1418 if (Warn) {
1419 if (IsOverridingMode)
1420 S.Diag(ImplVar->getLocation(),
1421 diag::warn_conflicting_overriding_param_modifiers)
1422 << getTypeRange(ImplVar->getTypeSourceInfo())
1423 << MethodImpl->getDeclName();
1424 else S.Diag(ImplVar->getLocation(),
1425 diag::warn_conflicting_param_modifiers)
1426 << getTypeRange(ImplVar->getTypeSourceInfo())
1427 << MethodImpl->getDeclName();
1428 S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1429 << getTypeRange(IfaceVar->getTypeSourceInfo());
1430 }
1431 else
1432 return false;
1433 }
1434
1435 QualType ImplTy = ImplVar->getType();
1436 QualType IfaceTy = IfaceVar->getType();
1437
1438 if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1439 return true;
1440
1441 if (!Warn)
1442 return false;
1443 unsigned DiagID =
1444 IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1445 : diag::warn_conflicting_param_types;
1446
1447 // Mismatches between ObjC pointers go into a different warning
1448 // category, and sometimes they're even completely whitelisted.
1449 if (const ObjCObjectPointerType *ImplPtrTy =
1450 ImplTy->getAs<ObjCObjectPointerType>()) {
1451 if (const ObjCObjectPointerType *IfacePtrTy =
1452 IfaceTy->getAs<ObjCObjectPointerType>()) {
1453 // Allow non-matching argument types as long as they don't
1454 // violate the principle of substitutability. Specifically, the
1455 // implementation must accept any objects that the superclass
1456 // accepts, however it may also accept others.
1457 if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1458 return false;
1459
1460 DiagID =
1461 IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1462 : diag::warn_non_contravariant_param_types;
1463 }
1464 }
1465
1466 S.Diag(ImplVar->getLocation(), DiagID)
1467 << getTypeRange(ImplVar->getTypeSourceInfo())
1468 << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1469 S.Diag(IfaceVar->getLocation(),
1470 (IsOverridingMode ? diag::note_previous_declaration
1471 : diag::note_previous_definition))
1472 << getTypeRange(IfaceVar->getTypeSourceInfo());
1473 return false;
1474 }
1475
1476 /// In ARC, check whether the conventional meanings of the two methods
1477 /// match. If they don't, it's a hard error.
checkMethodFamilyMismatch(Sema & S,ObjCMethodDecl * impl,ObjCMethodDecl * decl)1478 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1479 ObjCMethodDecl *decl) {
1480 ObjCMethodFamily implFamily = impl->getMethodFamily();
1481 ObjCMethodFamily declFamily = decl->getMethodFamily();
1482 if (implFamily == declFamily) return false;
1483
1484 // Since conventions are sorted by selector, the only possibility is
1485 // that the types differ enough to cause one selector or the other
1486 // to fall out of the family.
1487 assert(implFamily == OMF_None || declFamily == OMF_None);
1488
1489 // No further diagnostics required on invalid declarations.
1490 if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1491
1492 const ObjCMethodDecl *unmatched = impl;
1493 ObjCMethodFamily family = declFamily;
1494 unsigned errorID = diag::err_arc_lost_method_convention;
1495 unsigned noteID = diag::note_arc_lost_method_convention;
1496 if (declFamily == OMF_None) {
1497 unmatched = decl;
1498 family = implFamily;
1499 errorID = diag::err_arc_gained_method_convention;
1500 noteID = diag::note_arc_gained_method_convention;
1501 }
1502
1503 // Indexes into a %select clause in the diagnostic.
1504 enum FamilySelector {
1505 F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1506 };
1507 FamilySelector familySelector = FamilySelector();
1508
1509 switch (family) {
1510 case OMF_None: llvm_unreachable("logic error, no method convention");
1511 case OMF_retain:
1512 case OMF_release:
1513 case OMF_autorelease:
1514 case OMF_dealloc:
1515 case OMF_finalize:
1516 case OMF_retainCount:
1517 case OMF_self:
1518 case OMF_initialize:
1519 case OMF_performSelector:
1520 // Mismatches for these methods don't change ownership
1521 // conventions, so we don't care.
1522 return false;
1523
1524 case OMF_init: familySelector = F_init; break;
1525 case OMF_alloc: familySelector = F_alloc; break;
1526 case OMF_copy: familySelector = F_copy; break;
1527 case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1528 case OMF_new: familySelector = F_new; break;
1529 }
1530
1531 enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1532 ReasonSelector reasonSelector;
1533
1534 // The only reason these methods don't fall within their families is
1535 // due to unusual result types.
1536 if (unmatched->getReturnType()->isObjCObjectPointerType()) {
1537 reasonSelector = R_UnrelatedReturn;
1538 } else {
1539 reasonSelector = R_NonObjectReturn;
1540 }
1541
1542 S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
1543 S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
1544
1545 return true;
1546 }
1547
WarnConflictingTypedMethods(ObjCMethodDecl * ImpMethodDecl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl)1548 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1549 ObjCMethodDecl *MethodDecl,
1550 bool IsProtocolMethodDecl) {
1551 if (getLangOpts().ObjCAutoRefCount &&
1552 checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1553 return;
1554
1555 CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1556 IsProtocolMethodDecl, false,
1557 true);
1558
1559 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1560 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1561 EF = MethodDecl->param_end();
1562 IM != EM && IF != EF; ++IM, ++IF) {
1563 CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1564 IsProtocolMethodDecl, false, true);
1565 }
1566
1567 if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1568 Diag(ImpMethodDecl->getLocation(),
1569 diag::warn_conflicting_variadic);
1570 Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1571 }
1572 }
1573
CheckConflictingOverridingMethod(ObjCMethodDecl * Method,ObjCMethodDecl * Overridden,bool IsProtocolMethodDecl)1574 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1575 ObjCMethodDecl *Overridden,
1576 bool IsProtocolMethodDecl) {
1577
1578 CheckMethodOverrideReturn(*this, Method, Overridden,
1579 IsProtocolMethodDecl, true,
1580 true);
1581
1582 for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1583 IF = Overridden->param_begin(), EM = Method->param_end(),
1584 EF = Overridden->param_end();
1585 IM != EM && IF != EF; ++IM, ++IF) {
1586 CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1587 IsProtocolMethodDecl, true, true);
1588 }
1589
1590 if (Method->isVariadic() != Overridden->isVariadic()) {
1591 Diag(Method->getLocation(),
1592 diag::warn_conflicting_overriding_variadic);
1593 Diag(Overridden->getLocation(), diag::note_previous_declaration);
1594 }
1595 }
1596
1597 /// WarnExactTypedMethods - This routine issues a warning if method
1598 /// implementation declaration matches exactly that of its declaration.
WarnExactTypedMethods(ObjCMethodDecl * ImpMethodDecl,ObjCMethodDecl * MethodDecl,bool IsProtocolMethodDecl)1599 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1600 ObjCMethodDecl *MethodDecl,
1601 bool IsProtocolMethodDecl) {
1602 // don't issue warning when protocol method is optional because primary
1603 // class is not required to implement it and it is safe for protocol
1604 // to implement it.
1605 if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1606 return;
1607 // don't issue warning when primary class's method is
1608 // depecated/unavailable.
1609 if (MethodDecl->hasAttr<UnavailableAttr>() ||
1610 MethodDecl->hasAttr<DeprecatedAttr>())
1611 return;
1612
1613 bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1614 IsProtocolMethodDecl, false, false);
1615 if (match)
1616 for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1617 IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1618 EF = MethodDecl->param_end();
1619 IM != EM && IF != EF; ++IM, ++IF) {
1620 match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1621 *IM, *IF,
1622 IsProtocolMethodDecl, false, false);
1623 if (!match)
1624 break;
1625 }
1626 if (match)
1627 match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1628 if (match)
1629 match = !(MethodDecl->isClassMethod() &&
1630 MethodDecl->getSelector() == GetNullarySelector("load", Context));
1631
1632 if (match) {
1633 Diag(ImpMethodDecl->getLocation(),
1634 diag::warn_category_method_impl_match);
1635 Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1636 << MethodDecl->getDeclName();
1637 }
1638 }
1639
1640 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1641 /// improve the efficiency of selector lookups and type checking by associating
1642 /// with each protocol / interface / category the flattened instance tables. If
1643 /// we used an immutable set to keep the table then it wouldn't add significant
1644 /// memory cost and it would be handy for lookups.
1645
1646 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
1647 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
1648
findProtocolsWithExplicitImpls(const ObjCProtocolDecl * PDecl,ProtocolNameSet & PNS)1649 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
1650 ProtocolNameSet &PNS) {
1651 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
1652 PNS.insert(PDecl->getIdentifier());
1653 for (const auto *PI : PDecl->protocols())
1654 findProtocolsWithExplicitImpls(PI, PNS);
1655 }
1656
1657 /// Recursively populates a set with all conformed protocols in a class
1658 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
1659 /// attribute.
findProtocolsWithExplicitImpls(const ObjCInterfaceDecl * Super,ProtocolNameSet & PNS)1660 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
1661 ProtocolNameSet &PNS) {
1662 if (!Super)
1663 return;
1664
1665 for (const auto *I : Super->all_referenced_protocols())
1666 findProtocolsWithExplicitImpls(I, PNS);
1667
1668 findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
1669 }
1670
1671 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1672 /// Declared in protocol, and those referenced by it.
CheckProtocolMethodDefs(Sema & S,SourceLocation ImpLoc,ObjCProtocolDecl * PDecl,bool & IncompleteImpl,const Sema::SelectorSet & InsMap,const Sema::SelectorSet & ClsMap,ObjCContainerDecl * CDecl,LazyProtocolNameSet & ProtocolsExplictImpl)1673 static void CheckProtocolMethodDefs(Sema &S,
1674 SourceLocation ImpLoc,
1675 ObjCProtocolDecl *PDecl,
1676 bool& IncompleteImpl,
1677 const Sema::SelectorSet &InsMap,
1678 const Sema::SelectorSet &ClsMap,
1679 ObjCContainerDecl *CDecl,
1680 LazyProtocolNameSet &ProtocolsExplictImpl) {
1681 ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1682 ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1683 : dyn_cast<ObjCInterfaceDecl>(CDecl);
1684 assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1685
1686 ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1687 ObjCInterfaceDecl *NSIDecl = nullptr;
1688
1689 // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
1690 // then we should check if any class in the super class hierarchy also
1691 // conforms to this protocol, either directly or via protocol inheritance.
1692 // If so, we can skip checking this protocol completely because we
1693 // know that a parent class already satisfies this protocol.
1694 //
1695 // Note: we could generalize this logic for all protocols, and merely
1696 // add the limit on looking at the super class chain for just
1697 // specially marked protocols. This may be a good optimization. This
1698 // change is restricted to 'objc_protocol_requires_explicit_implementation'
1699 // protocols for now for controlled evaluation.
1700 if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
1701 if (!ProtocolsExplictImpl) {
1702 ProtocolsExplictImpl.reset(new ProtocolNameSet);
1703 findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
1704 }
1705 if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
1706 ProtocolsExplictImpl->end())
1707 return;
1708
1709 // If no super class conforms to the protocol, we should not search
1710 // for methods in the super class to implicitly satisfy the protocol.
1711 Super = nullptr;
1712 }
1713
1714 if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
1715 // check to see if class implements forwardInvocation method and objects
1716 // of this class are derived from 'NSProxy' so that to forward requests
1717 // from one object to another.
1718 // Under such conditions, which means that every method possible is
1719 // implemented in the class, we should not issue "Method definition not
1720 // found" warnings.
1721 // FIXME: Use a general GetUnarySelector method for this.
1722 IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
1723 Selector fISelector = S.Context.Selectors.getSelector(1, &II);
1724 if (InsMap.count(fISelector))
1725 // Is IDecl derived from 'NSProxy'? If so, no instance methods
1726 // need be implemented in the implementation.
1727 NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
1728 }
1729
1730 // If this is a forward protocol declaration, get its definition.
1731 if (!PDecl->isThisDeclarationADefinition() &&
1732 PDecl->getDefinition())
1733 PDecl = PDecl->getDefinition();
1734
1735 // If a method lookup fails locally we still need to look and see if
1736 // the method was implemented by a base class or an inherited
1737 // protocol. This lookup is slow, but occurs rarely in correct code
1738 // and otherwise would terminate in a warning.
1739
1740 // check unimplemented instance methods.
1741 if (!NSIDecl)
1742 for (auto *method : PDecl->instance_methods()) {
1743 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1744 !method->isPropertyAccessor() &&
1745 !InsMap.count(method->getSelector()) &&
1746 (!Super || !Super->lookupMethod(method->getSelector(),
1747 true /* instance */,
1748 false /* shallowCategory */,
1749 true /* followsSuper */,
1750 nullptr /* category */))) {
1751 // If a method is not implemented in the category implementation but
1752 // has been declared in its primary class, superclass,
1753 // or in one of their protocols, no need to issue the warning.
1754 // This is because method will be implemented in the primary class
1755 // or one of its super class implementation.
1756
1757 // Ugly, but necessary. Method declared in protcol might have
1758 // have been synthesized due to a property declared in the class which
1759 // uses the protocol.
1760 if (ObjCMethodDecl *MethodInClass =
1761 IDecl->lookupMethod(method->getSelector(),
1762 true /* instance */,
1763 true /* shallowCategoryLookup */,
1764 false /* followSuper */))
1765 if (C || MethodInClass->isPropertyAccessor())
1766 continue;
1767 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1768 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1769 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
1770 PDecl);
1771 }
1772 }
1773 }
1774 // check unimplemented class methods
1775 for (auto *method : PDecl->class_methods()) {
1776 if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1777 !ClsMap.count(method->getSelector()) &&
1778 (!Super || !Super->lookupMethod(method->getSelector(),
1779 false /* class method */,
1780 false /* shallowCategoryLookup */,
1781 true /* followSuper */,
1782 nullptr /* category */))) {
1783 // See above comment for instance method lookups.
1784 if (C && IDecl->lookupMethod(method->getSelector(),
1785 false /* class */,
1786 true /* shallowCategoryLookup */,
1787 false /* followSuper */))
1788 continue;
1789
1790 unsigned DIAG = diag::warn_unimplemented_protocol_method;
1791 if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1792 WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
1793 }
1794 }
1795 }
1796 // Check on this protocols's referenced protocols, recursively.
1797 for (auto *PI : PDecl->protocols())
1798 CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
1799 CDecl, ProtocolsExplictImpl);
1800 }
1801
1802 /// MatchAllMethodDeclarations - Check methods declared in interface
1803 /// or protocol against those declared in their implementations.
1804 ///
MatchAllMethodDeclarations(const SelectorSet & InsMap,const SelectorSet & ClsMap,SelectorSet & InsMapSeen,SelectorSet & ClsMapSeen,ObjCImplDecl * IMPDecl,ObjCContainerDecl * CDecl,bool & IncompleteImpl,bool ImmediateClass,bool WarnCategoryMethodImpl)1805 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1806 const SelectorSet &ClsMap,
1807 SelectorSet &InsMapSeen,
1808 SelectorSet &ClsMapSeen,
1809 ObjCImplDecl* IMPDecl,
1810 ObjCContainerDecl* CDecl,
1811 bool &IncompleteImpl,
1812 bool ImmediateClass,
1813 bool WarnCategoryMethodImpl) {
1814 // Check and see if instance methods in class interface have been
1815 // implemented in the implementation class. If so, their types match.
1816 for (auto *I : CDecl->instance_methods()) {
1817 if (!InsMapSeen.insert(I->getSelector()).second)
1818 continue;
1819 if (!I->isPropertyAccessor() &&
1820 !InsMap.count(I->getSelector())) {
1821 if (ImmediateClass)
1822 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1823 diag::warn_undef_method_impl);
1824 continue;
1825 } else {
1826 ObjCMethodDecl *ImpMethodDecl =
1827 IMPDecl->getInstanceMethod(I->getSelector());
1828 assert(CDecl->getInstanceMethod(I->getSelector()) &&
1829 "Expected to find the method through lookup as well");
1830 // ImpMethodDecl may be null as in a @dynamic property.
1831 if (ImpMethodDecl) {
1832 if (!WarnCategoryMethodImpl)
1833 WarnConflictingTypedMethods(ImpMethodDecl, I,
1834 isa<ObjCProtocolDecl>(CDecl));
1835 else if (!I->isPropertyAccessor())
1836 WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
1837 }
1838 }
1839 }
1840
1841 // Check and see if class methods in class interface have been
1842 // implemented in the implementation class. If so, their types match.
1843 for (auto *I : CDecl->class_methods()) {
1844 if (!ClsMapSeen.insert(I->getSelector()).second)
1845 continue;
1846 if (!ClsMap.count(I->getSelector())) {
1847 if (ImmediateClass)
1848 WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1849 diag::warn_undef_method_impl);
1850 } else {
1851 ObjCMethodDecl *ImpMethodDecl =
1852 IMPDecl->getClassMethod(I->getSelector());
1853 assert(CDecl->getClassMethod(I->getSelector()) &&
1854 "Expected to find the method through lookup as well");
1855 if (!WarnCategoryMethodImpl)
1856 WarnConflictingTypedMethods(ImpMethodDecl, I,
1857 isa<ObjCProtocolDecl>(CDecl));
1858 else
1859 WarnExactTypedMethods(ImpMethodDecl, I,
1860 isa<ObjCProtocolDecl>(CDecl));
1861 }
1862 }
1863
1864 if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
1865 // Also, check for methods declared in protocols inherited by
1866 // this protocol.
1867 for (auto *PI : PD->protocols())
1868 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1869 IMPDecl, PI, IncompleteImpl, false,
1870 WarnCategoryMethodImpl);
1871 }
1872
1873 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1874 // when checking that methods in implementation match their declaration,
1875 // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1876 // extension; as well as those in categories.
1877 if (!WarnCategoryMethodImpl) {
1878 for (auto *Cat : I->visible_categories())
1879 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1880 IMPDecl, Cat, IncompleteImpl, false,
1881 WarnCategoryMethodImpl);
1882 } else {
1883 // Also methods in class extensions need be looked at next.
1884 for (auto *Ext : I->visible_extensions())
1885 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1886 IMPDecl, Ext, IncompleteImpl, false,
1887 WarnCategoryMethodImpl);
1888 }
1889
1890 // Check for any implementation of a methods declared in protocol.
1891 for (auto *PI : I->all_referenced_protocols())
1892 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1893 IMPDecl, PI, IncompleteImpl, false,
1894 WarnCategoryMethodImpl);
1895
1896 // FIXME. For now, we are not checking for extact match of methods
1897 // in category implementation and its primary class's super class.
1898 if (!WarnCategoryMethodImpl && I->getSuperClass())
1899 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1900 IMPDecl,
1901 I->getSuperClass(), IncompleteImpl, false);
1902 }
1903 }
1904
1905 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1906 /// category matches with those implemented in its primary class and
1907 /// warns each time an exact match is found.
CheckCategoryVsClassMethodMatches(ObjCCategoryImplDecl * CatIMPDecl)1908 void Sema::CheckCategoryVsClassMethodMatches(
1909 ObjCCategoryImplDecl *CatIMPDecl) {
1910 // Get category's primary class.
1911 ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1912 if (!CatDecl)
1913 return;
1914 ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1915 if (!IDecl)
1916 return;
1917 ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
1918 SelectorSet InsMap, ClsMap;
1919
1920 for (const auto *I : CatIMPDecl->instance_methods()) {
1921 Selector Sel = I->getSelector();
1922 // When checking for methods implemented in the category, skip over
1923 // those declared in category class's super class. This is because
1924 // the super class must implement the method.
1925 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
1926 continue;
1927 InsMap.insert(Sel);
1928 }
1929
1930 for (const auto *I : CatIMPDecl->class_methods()) {
1931 Selector Sel = I->getSelector();
1932 if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
1933 continue;
1934 ClsMap.insert(Sel);
1935 }
1936 if (InsMap.empty() && ClsMap.empty())
1937 return;
1938
1939 SelectorSet InsMapSeen, ClsMapSeen;
1940 bool IncompleteImpl = false;
1941 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1942 CatIMPDecl, IDecl,
1943 IncompleteImpl, false,
1944 true /*WarnCategoryMethodImpl*/);
1945 }
1946
ImplMethodsVsClassMethods(Scope * S,ObjCImplDecl * IMPDecl,ObjCContainerDecl * CDecl,bool IncompleteImpl)1947 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1948 ObjCContainerDecl* CDecl,
1949 bool IncompleteImpl) {
1950 SelectorSet InsMap;
1951 // Check and see if instance methods in class interface have been
1952 // implemented in the implementation class.
1953 for (const auto *I : IMPDecl->instance_methods())
1954 InsMap.insert(I->getSelector());
1955
1956 // Check and see if properties declared in the interface have either 1)
1957 // an implementation or 2) there is a @synthesize/@dynamic implementation
1958 // of the property in the @implementation.
1959 if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1960 bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
1961 LangOpts.ObjCRuntime.isNonFragile() &&
1962 !IDecl->isObjCRequiresPropertyDefs();
1963 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
1964 }
1965
1966 SelectorSet ClsMap;
1967 for (const auto *I : IMPDecl->class_methods())
1968 ClsMap.insert(I->getSelector());
1969
1970 // Check for type conflict of methods declared in a class/protocol and
1971 // its implementation; if any.
1972 SelectorSet InsMapSeen, ClsMapSeen;
1973 MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1974 IMPDecl, CDecl,
1975 IncompleteImpl, true);
1976
1977 // check all methods implemented in category against those declared
1978 // in its primary class.
1979 if (ObjCCategoryImplDecl *CatDecl =
1980 dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1981 CheckCategoryVsClassMethodMatches(CatDecl);
1982
1983 // Check the protocol list for unimplemented methods in the @implementation
1984 // class.
1985 // Check and see if class methods in class interface have been
1986 // implemented in the implementation class.
1987
1988 LazyProtocolNameSet ExplicitImplProtocols;
1989
1990 if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1991 for (auto *PI : I->all_referenced_protocols())
1992 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
1993 InsMap, ClsMap, I, ExplicitImplProtocols);
1994 // Check class extensions (unnamed categories)
1995 for (auto *Ext : I->visible_extensions())
1996 ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
1997 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1998 // For extended class, unimplemented methods in its protocols will
1999 // be reported in the primary class.
2000 if (!C->IsClassExtension()) {
2001 for (auto *P : C->protocols())
2002 CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
2003 IncompleteImpl, InsMap, ClsMap, CDecl,
2004 ExplicitImplProtocols);
2005 DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2006 /*SynthesizeProperties=*/false);
2007 }
2008 } else
2009 llvm_unreachable("invalid ObjCContainerDecl type.");
2010 }
2011
2012 Sema::DeclGroupPtrTy
ActOnForwardClassDeclaration(SourceLocation AtClassLoc,IdentifierInfo ** IdentList,SourceLocation * IdentLocs,unsigned NumElts)2013 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
2014 IdentifierInfo **IdentList,
2015 SourceLocation *IdentLocs,
2016 unsigned NumElts) {
2017 SmallVector<Decl *, 8> DeclsInGroup;
2018 for (unsigned i = 0; i != NumElts; ++i) {
2019 // Check for another declaration kind with the same name.
2020 NamedDecl *PrevDecl
2021 = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
2022 LookupOrdinaryName, ForRedeclaration);
2023 if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2024 // GCC apparently allows the following idiom:
2025 //
2026 // typedef NSObject < XCElementTogglerP > XCElementToggler;
2027 // @class XCElementToggler;
2028 //
2029 // Here we have chosen to ignore the forward class declaration
2030 // with a warning. Since this is the implied behavior.
2031 TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
2032 if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
2033 Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
2034 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2035 } else {
2036 // a forward class declaration matching a typedef name of a class refers
2037 // to the underlying class. Just ignore the forward class with a warning
2038 // as this will force the intended behavior which is to lookup the
2039 // typedef name.
2040 if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2041 Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2042 << IdentList[i];
2043 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2044 continue;
2045 }
2046 }
2047 }
2048
2049 // Create a declaration to describe this forward declaration.
2050 ObjCInterfaceDecl *PrevIDecl
2051 = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2052
2053 IdentifierInfo *ClassName = IdentList[i];
2054 if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2055 // A previous decl with a different name is because of
2056 // @compatibility_alias, for example:
2057 // \code
2058 // @class NewImage;
2059 // @compatibility_alias OldImage NewImage;
2060 // \endcode
2061 // A lookup for 'OldImage' will return the 'NewImage' decl.
2062 //
2063 // In such a case use the real declaration name, instead of the alias one,
2064 // otherwise we will break IdentifierResolver and redecls-chain invariants.
2065 // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2066 // has been aliased.
2067 ClassName = PrevIDecl->getIdentifier();
2068 }
2069
2070 ObjCInterfaceDecl *IDecl
2071 = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
2072 ClassName, PrevIDecl, IdentLocs[i]);
2073 IDecl->setAtEndRange(IdentLocs[i]);
2074
2075 PushOnScopeChains(IDecl, TUScope);
2076 CheckObjCDeclScope(IDecl);
2077 DeclsInGroup.push_back(IDecl);
2078 }
2079
2080 return BuildDeclaratorGroup(DeclsInGroup, false);
2081 }
2082
2083 static bool tryMatchRecordTypes(ASTContext &Context,
2084 Sema::MethodMatchStrategy strategy,
2085 const Type *left, const Type *right);
2086
matchTypes(ASTContext & Context,Sema::MethodMatchStrategy strategy,QualType leftQT,QualType rightQT)2087 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2088 QualType leftQT, QualType rightQT) {
2089 const Type *left =
2090 Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2091 const Type *right =
2092 Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2093
2094 if (left == right) return true;
2095
2096 // If we're doing a strict match, the types have to match exactly.
2097 if (strategy == Sema::MMS_strict) return false;
2098
2099 if (left->isIncompleteType() || right->isIncompleteType()) return false;
2100
2101 // Otherwise, use this absurdly complicated algorithm to try to
2102 // validate the basic, low-level compatibility of the two types.
2103
2104 // As a minimum, require the sizes and alignments to match.
2105 TypeInfo LeftTI = Context.getTypeInfo(left);
2106 TypeInfo RightTI = Context.getTypeInfo(right);
2107 if (LeftTI.Width != RightTI.Width)
2108 return false;
2109
2110 if (LeftTI.Align != RightTI.Align)
2111 return false;
2112
2113 // Consider all the kinds of non-dependent canonical types:
2114 // - functions and arrays aren't possible as return and parameter types
2115
2116 // - vector types of equal size can be arbitrarily mixed
2117 if (isa<VectorType>(left)) return isa<VectorType>(right);
2118 if (isa<VectorType>(right)) return false;
2119
2120 // - references should only match references of identical type
2121 // - structs, unions, and Objective-C objects must match more-or-less
2122 // exactly
2123 // - everything else should be a scalar
2124 if (!left->isScalarType() || !right->isScalarType())
2125 return tryMatchRecordTypes(Context, strategy, left, right);
2126
2127 // Make scalars agree in kind, except count bools as chars, and group
2128 // all non-member pointers together.
2129 Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2130 Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2131 if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2132 if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
2133 if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2134 leftSK = Type::STK_ObjCObjectPointer;
2135 if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2136 rightSK = Type::STK_ObjCObjectPointer;
2137
2138 // Note that data member pointers and function member pointers don't
2139 // intermix because of the size differences.
2140
2141 return (leftSK == rightSK);
2142 }
2143
tryMatchRecordTypes(ASTContext & Context,Sema::MethodMatchStrategy strategy,const Type * lt,const Type * rt)2144 static bool tryMatchRecordTypes(ASTContext &Context,
2145 Sema::MethodMatchStrategy strategy,
2146 const Type *lt, const Type *rt) {
2147 assert(lt && rt && lt != rt);
2148
2149 if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2150 RecordDecl *left = cast<RecordType>(lt)->getDecl();
2151 RecordDecl *right = cast<RecordType>(rt)->getDecl();
2152
2153 // Require union-hood to match.
2154 if (left->isUnion() != right->isUnion()) return false;
2155
2156 // Require an exact match if either is non-POD.
2157 if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2158 (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2159 return false;
2160
2161 // Require size and alignment to match.
2162 TypeInfo LeftTI = Context.getTypeInfo(lt);
2163 TypeInfo RightTI = Context.getTypeInfo(rt);
2164 if (LeftTI.Width != RightTI.Width)
2165 return false;
2166
2167 if (LeftTI.Align != RightTI.Align)
2168 return false;
2169
2170 // Require fields to match.
2171 RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2172 RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2173 for (; li != le && ri != re; ++li, ++ri) {
2174 if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2175 return false;
2176 }
2177 return (li == le && ri == re);
2178 }
2179
2180 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2181 /// returns true, or false, accordingly.
2182 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
MatchTwoMethodDeclarations(const ObjCMethodDecl * left,const ObjCMethodDecl * right,MethodMatchStrategy strategy)2183 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2184 const ObjCMethodDecl *right,
2185 MethodMatchStrategy strategy) {
2186 if (!matchTypes(Context, strategy, left->getReturnType(),
2187 right->getReturnType()))
2188 return false;
2189
2190 // If either is hidden, it is not considered to match.
2191 if (left->isHidden() || right->isHidden())
2192 return false;
2193
2194 if (getLangOpts().ObjCAutoRefCount &&
2195 (left->hasAttr<NSReturnsRetainedAttr>()
2196 != right->hasAttr<NSReturnsRetainedAttr>() ||
2197 left->hasAttr<NSConsumesSelfAttr>()
2198 != right->hasAttr<NSConsumesSelfAttr>()))
2199 return false;
2200
2201 ObjCMethodDecl::param_const_iterator
2202 li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2203 re = right->param_end();
2204
2205 for (; li != le && ri != re; ++li, ++ri) {
2206 assert(ri != right->param_end() && "Param mismatch");
2207 const ParmVarDecl *lparm = *li, *rparm = *ri;
2208
2209 if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2210 return false;
2211
2212 if (getLangOpts().ObjCAutoRefCount &&
2213 lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2214 return false;
2215 }
2216 return true;
2217 }
2218
addMethodToGlobalList(ObjCMethodList * List,ObjCMethodDecl * Method)2219 void Sema::addMethodToGlobalList(ObjCMethodList *List,
2220 ObjCMethodDecl *Method) {
2221 // Record at the head of the list whether there were 0, 1, or >= 2 methods
2222 // inside categories.
2223 if (ObjCCategoryDecl *CD =
2224 dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
2225 if (!CD->IsClassExtension() && List->getBits() < 2)
2226 List->setBits(List->getBits() + 1);
2227
2228 // If the list is empty, make it a singleton list.
2229 if (List->getMethod() == nullptr) {
2230 List->setMethod(Method);
2231 List->setNext(nullptr);
2232 return;
2233 }
2234
2235 // We've seen a method with this name, see if we have already seen this type
2236 // signature.
2237 ObjCMethodList *Previous = List;
2238 for (; List; Previous = List, List = List->getNext()) {
2239 // If we are building a module, keep all of the methods.
2240 if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
2241 continue;
2242
2243 if (!MatchTwoMethodDeclarations(Method, List->getMethod())) {
2244 // Even if two method types do not match, we would like to say
2245 // there is more than one declaration so unavailability/deprecated
2246 // warning is not too noisy.
2247 if (!Method->isDefined())
2248 List->setHasMoreThanOneDecl(true);
2249 continue;
2250 }
2251
2252 ObjCMethodDecl *PrevObjCMethod = List->getMethod();
2253
2254 // Propagate the 'defined' bit.
2255 if (Method->isDefined())
2256 PrevObjCMethod->setDefined(true);
2257 else {
2258 // Objective-C doesn't allow an @interface for a class after its
2259 // @implementation. So if Method is not defined and there already is
2260 // an entry for this type signature, Method has to be for a different
2261 // class than PrevObjCMethod.
2262 List->setHasMoreThanOneDecl(true);
2263 }
2264
2265 // If a method is deprecated, push it in the global pool.
2266 // This is used for better diagnostics.
2267 if (Method->isDeprecated()) {
2268 if (!PrevObjCMethod->isDeprecated())
2269 List->setMethod(Method);
2270 }
2271 // If the new method is unavailable, push it into global pool
2272 // unless previous one is deprecated.
2273 if (Method->isUnavailable()) {
2274 if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2275 List->setMethod(Method);
2276 }
2277
2278 return;
2279 }
2280
2281 // We have a new signature for an existing method - add it.
2282 // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2283 ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
2284 Previous->setNext(new (Mem) ObjCMethodList(Method));
2285 }
2286
2287 /// \brief Read the contents of the method pool for a given selector from
2288 /// external storage.
ReadMethodPool(Selector Sel)2289 void Sema::ReadMethodPool(Selector Sel) {
2290 assert(ExternalSource && "We need an external AST source");
2291 ExternalSource->ReadMethodPool(Sel);
2292 }
2293
AddMethodToGlobalPool(ObjCMethodDecl * Method,bool impl,bool instance)2294 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
2295 bool instance) {
2296 // Ignore methods of invalid containers.
2297 if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
2298 return;
2299
2300 if (ExternalSource)
2301 ReadMethodPool(Method->getSelector());
2302
2303 GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
2304 if (Pos == MethodPool.end())
2305 Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2306 GlobalMethods())).first;
2307
2308 Method->setDefined(impl);
2309
2310 ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
2311 addMethodToGlobalList(&Entry, Method);
2312 }
2313
2314 /// Determines if this is an "acceptable" loose mismatch in the global
2315 /// method pool. This exists mostly as a hack to get around certain
2316 /// global mismatches which we can't afford to make warnings / errors.
2317 /// Really, what we want is a way to take a method out of the global
2318 /// method pool.
isAcceptableMethodMismatch(ObjCMethodDecl * chosen,ObjCMethodDecl * other)2319 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2320 ObjCMethodDecl *other) {
2321 if (!chosen->isInstanceMethod())
2322 return false;
2323
2324 Selector sel = chosen->getSelector();
2325 if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2326 return false;
2327
2328 // Don't complain about mismatches for -length if the method we
2329 // chose has an integral result type.
2330 return (chosen->getReturnType()->isIntegerType());
2331 }
2332
CollectMultipleMethodsInGlobalPool(Selector Sel,SmallVectorImpl<ObjCMethodDecl * > & Methods,bool instance)2333 bool Sema::CollectMultipleMethodsInGlobalPool(
2334 Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
2335 if (ExternalSource)
2336 ReadMethodPool(Sel);
2337
2338 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2339 if (Pos == MethodPool.end())
2340 return false;
2341 // Gather the non-hidden methods.
2342 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2343 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
2344 if (M->getMethod() && !M->getMethod()->isHidden())
2345 Methods.push_back(M->getMethod());
2346 return Methods.size() > 1;
2347 }
2348
AreMultipleMethodsInGlobalPool(Selector Sel,ObjCMethodDecl * BestMethod,SourceRange R,bool receiverIdOrClass)2349 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, ObjCMethodDecl *BestMethod,
2350 SourceRange R,
2351 bool receiverIdOrClass) {
2352 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2353 // Test for no method in the pool which should not trigger any warning by
2354 // caller.
2355 if (Pos == MethodPool.end())
2356 return true;
2357 ObjCMethodList &MethList =
2358 BestMethod->isInstanceMethod() ? Pos->second.first : Pos->second.second;
2359
2360 // Diagnose finding more than one method in global pool
2361 SmallVector<ObjCMethodDecl *, 4> Methods;
2362 Methods.push_back(BestMethod);
2363 for (ObjCMethodList *M = &MethList; M; M = M->getNext())
2364 if (M->getMethod() && !M->getMethod()->isHidden() &&
2365 M->getMethod() != BestMethod)
2366 Methods.push_back(M->getMethod());
2367 if (Methods.size() > 1)
2368 DiagnoseMultipleMethodInGlobalPool(Methods, Sel, R, receiverIdOrClass);
2369
2370 return MethList.hasMoreThanOneDecl();
2371 }
2372
LookupMethodInGlobalPool(Selector Sel,SourceRange R,bool receiverIdOrClass,bool instance)2373 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2374 bool receiverIdOrClass,
2375 bool instance) {
2376 if (ExternalSource)
2377 ReadMethodPool(Sel);
2378
2379 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2380 if (Pos == MethodPool.end())
2381 return nullptr;
2382
2383 // Gather the non-hidden methods.
2384 ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2385 SmallVector<ObjCMethodDecl *, 4> Methods;
2386 for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
2387 if (M->getMethod() && !M->getMethod()->isHidden())
2388 return M->getMethod();
2389 }
2390 return nullptr;
2391 }
2392
DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl * > & Methods,Selector Sel,SourceRange R,bool receiverIdOrClass)2393 void Sema::DiagnoseMultipleMethodInGlobalPool(SmallVectorImpl<ObjCMethodDecl*> &Methods,
2394 Selector Sel, SourceRange R,
2395 bool receiverIdOrClass) {
2396 // We found multiple methods, so we may have to complain.
2397 bool issueDiagnostic = false, issueError = false;
2398
2399 // We support a warning which complains about *any* difference in
2400 // method signature.
2401 bool strictSelectorMatch =
2402 receiverIdOrClass &&
2403 !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
2404 if (strictSelectorMatch) {
2405 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2406 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2407 issueDiagnostic = true;
2408 break;
2409 }
2410 }
2411 }
2412
2413 // If we didn't see any strict differences, we won't see any loose
2414 // differences. In ARC, however, we also need to check for loose
2415 // mismatches, because most of them are errors.
2416 if (!strictSelectorMatch ||
2417 (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2418 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2419 // This checks if the methods differ in type mismatch.
2420 if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2421 !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2422 issueDiagnostic = true;
2423 if (getLangOpts().ObjCAutoRefCount)
2424 issueError = true;
2425 break;
2426 }
2427 }
2428
2429 if (issueDiagnostic) {
2430 if (issueError)
2431 Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2432 else if (strictSelectorMatch)
2433 Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2434 else
2435 Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2436
2437 Diag(Methods[0]->getLocStart(),
2438 issueError ? diag::note_possibility : diag::note_using)
2439 << Methods[0]->getSourceRange();
2440 for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2441 Diag(Methods[I]->getLocStart(), diag::note_also_found)
2442 << Methods[I]->getSourceRange();
2443 }
2444 }
2445 }
2446
LookupImplementedMethodInGlobalPool(Selector Sel)2447 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2448 GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2449 if (Pos == MethodPool.end())
2450 return nullptr;
2451
2452 GlobalMethods &Methods = Pos->second;
2453 for (const ObjCMethodList *Method = &Methods.first; Method;
2454 Method = Method->getNext())
2455 if (Method->getMethod() &&
2456 (Method->getMethod()->isDefined() ||
2457 Method->getMethod()->isPropertyAccessor()))
2458 return Method->getMethod();
2459
2460 for (const ObjCMethodList *Method = &Methods.second; Method;
2461 Method = Method->getNext())
2462 if (Method->getMethod() &&
2463 (Method->getMethod()->isDefined() ||
2464 Method->getMethod()->isPropertyAccessor()))
2465 return Method->getMethod();
2466 return nullptr;
2467 }
2468
2469 static void
HelperSelectorsForTypoCorrection(SmallVectorImpl<const ObjCMethodDecl * > & BestMethod,StringRef Typo,const ObjCMethodDecl * Method)2470 HelperSelectorsForTypoCorrection(
2471 SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
2472 StringRef Typo, const ObjCMethodDecl * Method) {
2473 const unsigned MaxEditDistance = 1;
2474 unsigned BestEditDistance = MaxEditDistance + 1;
2475 std::string MethodName = Method->getSelector().getAsString();
2476
2477 unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
2478 if (MinPossibleEditDistance > 0 &&
2479 Typo.size() / MinPossibleEditDistance < 1)
2480 return;
2481 unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
2482 if (EditDistance > MaxEditDistance)
2483 return;
2484 if (EditDistance == BestEditDistance)
2485 BestMethod.push_back(Method);
2486 else if (EditDistance < BestEditDistance) {
2487 BestMethod.clear();
2488 BestMethod.push_back(Method);
2489 }
2490 }
2491
HelperIsMethodInObjCType(Sema & S,Selector Sel,QualType ObjectType)2492 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
2493 QualType ObjectType) {
2494 if (ObjectType.isNull())
2495 return true;
2496 if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
2497 return true;
2498 return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
2499 nullptr;
2500 }
2501
2502 const ObjCMethodDecl *
SelectorsForTypoCorrection(Selector Sel,QualType ObjectType)2503 Sema::SelectorsForTypoCorrection(Selector Sel,
2504 QualType ObjectType) {
2505 unsigned NumArgs = Sel.getNumArgs();
2506 SmallVector<const ObjCMethodDecl *, 8> Methods;
2507 bool ObjectIsId = true, ObjectIsClass = true;
2508 if (ObjectType.isNull())
2509 ObjectIsId = ObjectIsClass = false;
2510 else if (!ObjectType->isObjCObjectPointerType())
2511 return nullptr;
2512 else if (const ObjCObjectPointerType *ObjCPtr =
2513 ObjectType->getAsObjCInterfacePointerType()) {
2514 ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
2515 ObjectIsId = ObjectIsClass = false;
2516 }
2517 else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
2518 ObjectIsClass = false;
2519 else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
2520 ObjectIsId = false;
2521 else
2522 return nullptr;
2523
2524 for (GlobalMethodPool::iterator b = MethodPool.begin(),
2525 e = MethodPool.end(); b != e; b++) {
2526 // instance methods
2527 for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
2528 if (M->getMethod() &&
2529 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
2530 (M->getMethod()->getSelector() != Sel)) {
2531 if (ObjectIsId)
2532 Methods.push_back(M->getMethod());
2533 else if (!ObjectIsClass &&
2534 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
2535 ObjectType))
2536 Methods.push_back(M->getMethod());
2537 }
2538 // class methods
2539 for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
2540 if (M->getMethod() &&
2541 (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
2542 (M->getMethod()->getSelector() != Sel)) {
2543 if (ObjectIsClass)
2544 Methods.push_back(M->getMethod());
2545 else if (!ObjectIsId &&
2546 HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
2547 ObjectType))
2548 Methods.push_back(M->getMethod());
2549 }
2550 }
2551
2552 SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
2553 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
2554 HelperSelectorsForTypoCorrection(SelectedMethods,
2555 Sel.getAsString(), Methods[i]);
2556 }
2557 return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
2558 }
2559
2560 /// DiagnoseDuplicateIvars -
2561 /// Check for duplicate ivars in the entire class at the start of
2562 /// \@implementation. This becomes necesssary because class extension can
2563 /// add ivars to a class in random order which will not be known until
2564 /// class's \@implementation is seen.
DiagnoseDuplicateIvars(ObjCInterfaceDecl * ID,ObjCInterfaceDecl * SID)2565 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2566 ObjCInterfaceDecl *SID) {
2567 for (auto *Ivar : ID->ivars()) {
2568 if (Ivar->isInvalidDecl())
2569 continue;
2570 if (IdentifierInfo *II = Ivar->getIdentifier()) {
2571 ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2572 if (prevIvar) {
2573 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2574 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2575 Ivar->setInvalidDecl();
2576 }
2577 }
2578 }
2579 }
2580
getObjCContainerKind() const2581 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2582 switch (CurContext->getDeclKind()) {
2583 case Decl::ObjCInterface:
2584 return Sema::OCK_Interface;
2585 case Decl::ObjCProtocol:
2586 return Sema::OCK_Protocol;
2587 case Decl::ObjCCategory:
2588 if (cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2589 return Sema::OCK_ClassExtension;
2590 return Sema::OCK_Category;
2591 case Decl::ObjCImplementation:
2592 return Sema::OCK_Implementation;
2593 case Decl::ObjCCategoryImpl:
2594 return Sema::OCK_CategoryImplementation;
2595
2596 default:
2597 return Sema::OCK_None;
2598 }
2599 }
2600
2601 // Note: For class/category implementations, allMethods is always null.
ActOnAtEnd(Scope * S,SourceRange AtEnd,ArrayRef<Decl * > allMethods,ArrayRef<DeclGroupPtrTy> allTUVars)2602 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
2603 ArrayRef<DeclGroupPtrTy> allTUVars) {
2604 if (getObjCContainerKind() == Sema::OCK_None)
2605 return nullptr;
2606
2607 assert(AtEnd.isValid() && "Invalid location for '@end'");
2608
2609 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2610 Decl *ClassDecl = cast<Decl>(OCD);
2611
2612 bool isInterfaceDeclKind =
2613 isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2614 || isa<ObjCProtocolDecl>(ClassDecl);
2615 bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2616
2617 // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2618 llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2619 llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2620
2621 for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
2622 ObjCMethodDecl *Method =
2623 cast_or_null<ObjCMethodDecl>(allMethods[i]);
2624
2625 if (!Method) continue; // Already issued a diagnostic.
2626 if (Method->isInstanceMethod()) {
2627 /// Check for instance method of the same name with incompatible types
2628 const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2629 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2630 : false;
2631 if ((isInterfaceDeclKind && PrevMethod && !match)
2632 || (checkIdenticalMethods && match)) {
2633 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2634 << Method->getDeclName();
2635 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2636 Method->setInvalidDecl();
2637 } else {
2638 if (PrevMethod) {
2639 Method->setAsRedeclaration(PrevMethod);
2640 if (!Context.getSourceManager().isInSystemHeader(
2641 Method->getLocation()))
2642 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2643 << Method->getDeclName();
2644 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2645 }
2646 InsMap[Method->getSelector()] = Method;
2647 /// The following allows us to typecheck messages to "id".
2648 AddInstanceMethodToGlobalPool(Method);
2649 }
2650 } else {
2651 /// Check for class method of the same name with incompatible types
2652 const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2653 bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2654 : false;
2655 if ((isInterfaceDeclKind && PrevMethod && !match)
2656 || (checkIdenticalMethods && match)) {
2657 Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2658 << Method->getDeclName();
2659 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2660 Method->setInvalidDecl();
2661 } else {
2662 if (PrevMethod) {
2663 Method->setAsRedeclaration(PrevMethod);
2664 if (!Context.getSourceManager().isInSystemHeader(
2665 Method->getLocation()))
2666 Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2667 << Method->getDeclName();
2668 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2669 }
2670 ClsMap[Method->getSelector()] = Method;
2671 AddFactoryMethodToGlobalPool(Method);
2672 }
2673 }
2674 }
2675 if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2676 // Nothing to do here.
2677 } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2678 // Categories are used to extend the class by declaring new methods.
2679 // By the same token, they are also used to add new properties. No
2680 // need to compare the added property to those in the class.
2681
2682 if (C->IsClassExtension()) {
2683 ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2684 DiagnoseClassExtensionDupMethods(C, CCPrimary);
2685 }
2686 }
2687 if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2688 if (CDecl->getIdentifier())
2689 // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2690 // user-defined setter/getter. It also synthesizes setter/getter methods
2691 // and adds them to the DeclContext and global method pools.
2692 for (auto *I : CDecl->properties())
2693 ProcessPropertyDecl(I, CDecl);
2694 CDecl->setAtEndRange(AtEnd);
2695 }
2696 if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2697 IC->setAtEndRange(AtEnd);
2698 if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2699 // Any property declared in a class extension might have user
2700 // declared setter or getter in current class extension or one
2701 // of the other class extensions. Mark them as synthesized as
2702 // property will be synthesized when property with same name is
2703 // seen in the @implementation.
2704 for (const auto *Ext : IDecl->visible_extensions()) {
2705 for (const auto *Property : Ext->properties()) {
2706 // Skip over properties declared @dynamic
2707 if (const ObjCPropertyImplDecl *PIDecl
2708 = IC->FindPropertyImplDecl(Property->getIdentifier()))
2709 if (PIDecl->getPropertyImplementation()
2710 == ObjCPropertyImplDecl::Dynamic)
2711 continue;
2712
2713 for (const auto *Ext : IDecl->visible_extensions()) {
2714 if (ObjCMethodDecl *GetterMethod
2715 = Ext->getInstanceMethod(Property->getGetterName()))
2716 GetterMethod->setPropertyAccessor(true);
2717 if (!Property->isReadOnly())
2718 if (ObjCMethodDecl *SetterMethod
2719 = Ext->getInstanceMethod(Property->getSetterName()))
2720 SetterMethod->setPropertyAccessor(true);
2721 }
2722 }
2723 }
2724 ImplMethodsVsClassMethods(S, IC, IDecl);
2725 AtomicPropertySetterGetterRules(IC, IDecl);
2726 DiagnoseOwningPropertyGetterSynthesis(IC);
2727 DiagnoseUnusedBackingIvarInAccessor(S, IC);
2728 if (IDecl->hasDesignatedInitializers())
2729 DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
2730
2731 bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
2732 if (IDecl->getSuperClass() == nullptr) {
2733 // This class has no superclass, so check that it has been marked with
2734 // __attribute((objc_root_class)).
2735 if (!HasRootClassAttr) {
2736 SourceLocation DeclLoc(IDecl->getLocation());
2737 SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
2738 Diag(DeclLoc, diag::warn_objc_root_class_missing)
2739 << IDecl->getIdentifier();
2740 // See if NSObject is in the current scope, and if it is, suggest
2741 // adding " : NSObject " to the class declaration.
2742 NamedDecl *IF = LookupSingleName(TUScope,
2743 NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2744 DeclLoc, LookupOrdinaryName);
2745 ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2746 if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2747 Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2748 << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2749 } else {
2750 Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2751 }
2752 }
2753 } else if (HasRootClassAttr) {
2754 // Complain that only root classes may have this attribute.
2755 Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2756 }
2757
2758 if (LangOpts.ObjCRuntime.isNonFragile()) {
2759 while (IDecl->getSuperClass()) {
2760 DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2761 IDecl = IDecl->getSuperClass();
2762 }
2763 }
2764 }
2765 SetIvarInitializers(IC);
2766 } else if (ObjCCategoryImplDecl* CatImplClass =
2767 dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2768 CatImplClass->setAtEndRange(AtEnd);
2769
2770 // Find category interface decl and then check that all methods declared
2771 // in this interface are implemented in the category @implementation.
2772 if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2773 if (ObjCCategoryDecl *Cat
2774 = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2775 ImplMethodsVsClassMethods(S, CatImplClass, Cat);
2776 }
2777 }
2778 }
2779 if (isInterfaceDeclKind) {
2780 // Reject invalid vardecls.
2781 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2782 DeclGroupRef DG = allTUVars[i].get();
2783 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2784 if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2785 if (!VDecl->hasExternalStorage())
2786 Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2787 }
2788 }
2789 }
2790 ActOnObjCContainerFinishDefinition();
2791
2792 for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2793 DeclGroupRef DG = allTUVars[i].get();
2794 for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2795 (*I)->setTopLevelDeclInObjCContainer();
2796 Consumer.HandleTopLevelDeclInObjCContainer(DG);
2797 }
2798
2799 ActOnDocumentableDecl(ClassDecl);
2800 return ClassDecl;
2801 }
2802
2803
2804 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2805 /// objective-c's type qualifier from the parser version of the same info.
2806 static Decl::ObjCDeclQualifier
CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal)2807 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2808 return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2809 }
2810
2811 /// \brief Check whether the declared result type of the given Objective-C
2812 /// method declaration is compatible with the method's class.
2813 ///
2814 static Sema::ResultTypeCompatibilityKind
CheckRelatedResultTypeCompatibility(Sema & S,ObjCMethodDecl * Method,ObjCInterfaceDecl * CurrentClass)2815 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2816 ObjCInterfaceDecl *CurrentClass) {
2817 QualType ResultType = Method->getReturnType();
2818
2819 // If an Objective-C method inherits its related result type, then its
2820 // declared result type must be compatible with its own class type. The
2821 // declared result type is compatible if:
2822 if (const ObjCObjectPointerType *ResultObjectType
2823 = ResultType->getAs<ObjCObjectPointerType>()) {
2824 // - it is id or qualified id, or
2825 if (ResultObjectType->isObjCIdType() ||
2826 ResultObjectType->isObjCQualifiedIdType())
2827 return Sema::RTC_Compatible;
2828
2829 if (CurrentClass) {
2830 if (ObjCInterfaceDecl *ResultClass
2831 = ResultObjectType->getInterfaceDecl()) {
2832 // - it is the same as the method's class type, or
2833 if (declaresSameEntity(CurrentClass, ResultClass))
2834 return Sema::RTC_Compatible;
2835
2836 // - it is a superclass of the method's class type
2837 if (ResultClass->isSuperClassOf(CurrentClass))
2838 return Sema::RTC_Compatible;
2839 }
2840 } else {
2841 // Any Objective-C pointer type might be acceptable for a protocol
2842 // method; we just don't know.
2843 return Sema::RTC_Unknown;
2844 }
2845 }
2846
2847 return Sema::RTC_Incompatible;
2848 }
2849
2850 namespace {
2851 /// A helper class for searching for methods which a particular method
2852 /// overrides.
2853 class OverrideSearch {
2854 public:
2855 Sema &S;
2856 ObjCMethodDecl *Method;
2857 llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
2858 bool Recursive;
2859
2860 public:
OverrideSearch(Sema & S,ObjCMethodDecl * method)2861 OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2862 Selector selector = method->getSelector();
2863
2864 // Bypass this search if we've never seen an instance/class method
2865 // with this selector before.
2866 Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2867 if (it == S.MethodPool.end()) {
2868 if (!S.getExternalSource()) return;
2869 S.ReadMethodPool(selector);
2870
2871 it = S.MethodPool.find(selector);
2872 if (it == S.MethodPool.end())
2873 return;
2874 }
2875 ObjCMethodList &list =
2876 method->isInstanceMethod() ? it->second.first : it->second.second;
2877 if (!list.getMethod()) return;
2878
2879 ObjCContainerDecl *container
2880 = cast<ObjCContainerDecl>(method->getDeclContext());
2881
2882 // Prevent the search from reaching this container again. This is
2883 // important with categories, which override methods from the
2884 // interface and each other.
2885 if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2886 searchFromContainer(container);
2887 if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2888 searchFromContainer(Interface);
2889 } else {
2890 searchFromContainer(container);
2891 }
2892 }
2893
2894 typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
begin() const2895 iterator begin() const { return Overridden.begin(); }
end() const2896 iterator end() const { return Overridden.end(); }
2897
2898 private:
searchFromContainer(ObjCContainerDecl * container)2899 void searchFromContainer(ObjCContainerDecl *container) {
2900 if (container->isInvalidDecl()) return;
2901
2902 switch (container->getDeclKind()) {
2903 #define OBJCCONTAINER(type, base) \
2904 case Decl::type: \
2905 searchFrom(cast<type##Decl>(container)); \
2906 break;
2907 #define ABSTRACT_DECL(expansion)
2908 #define DECL(type, base) \
2909 case Decl::type:
2910 #include "clang/AST/DeclNodes.inc"
2911 llvm_unreachable("not an ObjC container!");
2912 }
2913 }
2914
searchFrom(ObjCProtocolDecl * protocol)2915 void searchFrom(ObjCProtocolDecl *protocol) {
2916 if (!protocol->hasDefinition())
2917 return;
2918
2919 // A method in a protocol declaration overrides declarations from
2920 // referenced ("parent") protocols.
2921 search(protocol->getReferencedProtocols());
2922 }
2923
searchFrom(ObjCCategoryDecl * category)2924 void searchFrom(ObjCCategoryDecl *category) {
2925 // A method in a category declaration overrides declarations from
2926 // the main class and from protocols the category references.
2927 // The main class is handled in the constructor.
2928 search(category->getReferencedProtocols());
2929 }
2930
searchFrom(ObjCCategoryImplDecl * impl)2931 void searchFrom(ObjCCategoryImplDecl *impl) {
2932 // A method in a category definition that has a category
2933 // declaration overrides declarations from the category
2934 // declaration.
2935 if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2936 search(category);
2937 if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2938 search(Interface);
2939
2940 // Otherwise it overrides declarations from the class.
2941 } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2942 search(Interface);
2943 }
2944 }
2945
searchFrom(ObjCInterfaceDecl * iface)2946 void searchFrom(ObjCInterfaceDecl *iface) {
2947 // A method in a class declaration overrides declarations from
2948 if (!iface->hasDefinition())
2949 return;
2950
2951 // - categories,
2952 for (auto *Cat : iface->known_categories())
2953 search(Cat);
2954
2955 // - the super class, and
2956 if (ObjCInterfaceDecl *super = iface->getSuperClass())
2957 search(super);
2958
2959 // - any referenced protocols.
2960 search(iface->getReferencedProtocols());
2961 }
2962
searchFrom(ObjCImplementationDecl * impl)2963 void searchFrom(ObjCImplementationDecl *impl) {
2964 // A method in a class implementation overrides declarations from
2965 // the class interface.
2966 if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2967 search(Interface);
2968 }
2969
2970
search(const ObjCProtocolList & protocols)2971 void search(const ObjCProtocolList &protocols) {
2972 for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2973 i != e; ++i)
2974 search(*i);
2975 }
2976
search(ObjCContainerDecl * container)2977 void search(ObjCContainerDecl *container) {
2978 // Check for a method in this container which matches this selector.
2979 ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2980 Method->isInstanceMethod(),
2981 /*AllowHidden=*/true);
2982
2983 // If we find one, record it and bail out.
2984 if (meth) {
2985 Overridden.insert(meth);
2986 return;
2987 }
2988
2989 // Otherwise, search for methods that a hypothetical method here
2990 // would have overridden.
2991
2992 // Note that we're now in a recursive case.
2993 Recursive = true;
2994
2995 searchFromContainer(container);
2996 }
2997 };
2998 }
2999
CheckObjCMethodOverrides(ObjCMethodDecl * ObjCMethod,ObjCInterfaceDecl * CurrentClass,ResultTypeCompatibilityKind RTC)3000 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
3001 ObjCInterfaceDecl *CurrentClass,
3002 ResultTypeCompatibilityKind RTC) {
3003 // Search for overridden methods and merge information down from them.
3004 OverrideSearch overrides(*this, ObjCMethod);
3005 // Keep track if the method overrides any method in the class's base classes,
3006 // its protocols, or its categories' protocols; we will keep that info
3007 // in the ObjCMethodDecl.
3008 // For this info, a method in an implementation is not considered as
3009 // overriding the same method in the interface or its categories.
3010 bool hasOverriddenMethodsInBaseOrProtocol = false;
3011 for (OverrideSearch::iterator
3012 i = overrides.begin(), e = overrides.end(); i != e; ++i) {
3013 ObjCMethodDecl *overridden = *i;
3014
3015 if (!hasOverriddenMethodsInBaseOrProtocol) {
3016 if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
3017 CurrentClass != overridden->getClassInterface() ||
3018 overridden->isOverriding()) {
3019 hasOverriddenMethodsInBaseOrProtocol = true;
3020
3021 } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
3022 // OverrideSearch will return as "overridden" the same method in the
3023 // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
3024 // check whether a category of a base class introduced a method with the
3025 // same selector, after the interface method declaration.
3026 // To avoid unnecessary lookups in the majority of cases, we use the
3027 // extra info bits in GlobalMethodPool to check whether there were any
3028 // category methods with this selector.
3029 GlobalMethodPool::iterator It =
3030 MethodPool.find(ObjCMethod->getSelector());
3031 if (It != MethodPool.end()) {
3032 ObjCMethodList &List =
3033 ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3034 unsigned CategCount = List.getBits();
3035 if (CategCount > 0) {
3036 // If the method is in a category we'll do lookup if there were at
3037 // least 2 category methods recorded, otherwise only one will do.
3038 if (CategCount > 1 ||
3039 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3040 OverrideSearch overrides(*this, overridden);
3041 for (OverrideSearch::iterator
3042 OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3043 ObjCMethodDecl *SuperOverridden = *OI;
3044 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3045 CurrentClass != SuperOverridden->getClassInterface()) {
3046 hasOverriddenMethodsInBaseOrProtocol = true;
3047 overridden->setOverriding(true);
3048 break;
3049 }
3050 }
3051 }
3052 }
3053 }
3054 }
3055 }
3056
3057 // Propagate down the 'related result type' bit from overridden methods.
3058 if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3059 ObjCMethod->SetRelatedResultType();
3060
3061 // Then merge the declarations.
3062 mergeObjCMethodDecls(ObjCMethod, overridden);
3063
3064 if (ObjCMethod->isImplicit() && overridden->isImplicit())
3065 continue; // Conflicting properties are detected elsewhere.
3066
3067 // Check for overriding methods
3068 if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3069 isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3070 CheckConflictingOverridingMethod(ObjCMethod, overridden,
3071 isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3072
3073 if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
3074 isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3075 !overridden->isImplicit() /* not meant for properties */) {
3076 ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3077 E = ObjCMethod->param_end();
3078 ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3079 PrevE = overridden->param_end();
3080 for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
3081 assert(PrevI != overridden->param_end() && "Param mismatch");
3082 QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3083 QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3084 // If type of argument of method in this class does not match its
3085 // respective argument type in the super class method, issue warning;
3086 if (!Context.typesAreCompatible(T1, T2)) {
3087 Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3088 << T1 << T2;
3089 Diag(overridden->getLocation(), diag::note_previous_declaration);
3090 break;
3091 }
3092 }
3093 }
3094 }
3095
3096 ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3097 }
3098
ActOnMethodDeclaration(Scope * S,SourceLocation MethodLoc,SourceLocation EndLoc,tok::TokenKind MethodType,ObjCDeclSpec & ReturnQT,ParsedType ReturnType,ArrayRef<SourceLocation> SelectorLocs,Selector Sel,ObjCArgInfo * ArgInfo,DeclaratorChunk::ParamInfo * CParamInfo,unsigned CNumArgs,AttributeList * AttrList,tok::ObjCKeywordKind MethodDeclKind,bool isVariadic,bool MethodDefinition)3099 Decl *Sema::ActOnMethodDeclaration(
3100 Scope *S,
3101 SourceLocation MethodLoc, SourceLocation EndLoc,
3102 tok::TokenKind MethodType,
3103 ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
3104 ArrayRef<SourceLocation> SelectorLocs,
3105 Selector Sel,
3106 // optional arguments. The number of types/arguments is obtained
3107 // from the Sel.getNumArgs().
3108 ObjCArgInfo *ArgInfo,
3109 DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
3110 AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
3111 bool isVariadic, bool MethodDefinition) {
3112 // Make sure we can establish a context for the method.
3113 if (!CurContext->isObjCContainer()) {
3114 Diag(MethodLoc, diag::error_missing_method_context);
3115 return nullptr;
3116 }
3117 ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3118 Decl *ClassDecl = cast<Decl>(OCD);
3119 QualType resultDeclType;
3120
3121 bool HasRelatedResultType = false;
3122 TypeSourceInfo *ReturnTInfo = nullptr;
3123 if (ReturnType) {
3124 resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
3125
3126 if (CheckFunctionReturnType(resultDeclType, MethodLoc))
3127 return nullptr;
3128
3129 HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
3130 } else { // get the type for "id".
3131 resultDeclType = Context.getObjCIdType();
3132 Diag(MethodLoc, diag::warn_missing_method_return_type)
3133 << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
3134 }
3135
3136 ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
3137 Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
3138 MethodType == tok::minus, isVariadic,
3139 /*isPropertyAccessor=*/false,
3140 /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
3141 MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
3142 : ObjCMethodDecl::Required,
3143 HasRelatedResultType);
3144
3145 SmallVector<ParmVarDecl*, 16> Params;
3146
3147 for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
3148 QualType ArgType;
3149 TypeSourceInfo *DI;
3150
3151 if (!ArgInfo[i].Type) {
3152 ArgType = Context.getObjCIdType();
3153 DI = nullptr;
3154 } else {
3155 ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
3156 }
3157
3158 LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
3159 LookupOrdinaryName, ForRedeclaration);
3160 LookupName(R, S);
3161 if (R.isSingleResult()) {
3162 NamedDecl *PrevDecl = R.getFoundDecl();
3163 if (S->isDeclScope(PrevDecl)) {
3164 Diag(ArgInfo[i].NameLoc,
3165 (MethodDefinition ? diag::warn_method_param_redefinition
3166 : diag::warn_method_param_declaration))
3167 << ArgInfo[i].Name;
3168 Diag(PrevDecl->getLocation(),
3169 diag::note_previous_declaration);
3170 }
3171 }
3172
3173 SourceLocation StartLoc = DI
3174 ? DI->getTypeLoc().getBeginLoc()
3175 : ArgInfo[i].NameLoc;
3176
3177 ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
3178 ArgInfo[i].NameLoc, ArgInfo[i].Name,
3179 ArgType, DI, SC_None);
3180
3181 Param->setObjCMethodScopeInfo(i);
3182
3183 Param->setObjCDeclQualifier(
3184 CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
3185
3186 // Apply the attributes to the parameter.
3187 ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
3188
3189 if (Param->hasAttr<BlocksAttr>()) {
3190 Diag(Param->getLocation(), diag::err_block_on_nonlocal);
3191 Param->setInvalidDecl();
3192 }
3193 S->AddDecl(Param);
3194 IdResolver.AddDecl(Param);
3195
3196 Params.push_back(Param);
3197 }
3198
3199 for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
3200 ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
3201 QualType ArgType = Param->getType();
3202 if (ArgType.isNull())
3203 ArgType = Context.getObjCIdType();
3204 else
3205 // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
3206 ArgType = Context.getAdjustedParameterType(ArgType);
3207
3208 Param->setDeclContext(ObjCMethod);
3209 Params.push_back(Param);
3210 }
3211
3212 ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
3213 ObjCMethod->setObjCDeclQualifier(
3214 CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
3215
3216 if (AttrList)
3217 ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
3218
3219 // Add the method now.
3220 const ObjCMethodDecl *PrevMethod = nullptr;
3221 if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
3222 if (MethodType == tok::minus) {
3223 PrevMethod = ImpDecl->getInstanceMethod(Sel);
3224 ImpDecl->addInstanceMethod(ObjCMethod);
3225 } else {
3226 PrevMethod = ImpDecl->getClassMethod(Sel);
3227 ImpDecl->addClassMethod(ObjCMethod);
3228 }
3229
3230 ObjCMethodDecl *IMD = nullptr;
3231 if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
3232 IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
3233 ObjCMethod->isInstanceMethod());
3234 if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
3235 !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
3236 // merge the attribute into implementation.
3237 ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
3238 ObjCMethod->getLocation()));
3239 }
3240 if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
3241 ObjCMethodFamily family =
3242 ObjCMethod->getSelector().getMethodFamily();
3243 if (family == OMF_dealloc && IMD && IMD->isOverriding())
3244 Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
3245 << ObjCMethod->getDeclName();
3246 }
3247 } else {
3248 cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
3249 }
3250
3251 if (PrevMethod) {
3252 // You can never have two method definitions with the same name.
3253 Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
3254 << ObjCMethod->getDeclName();
3255 Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3256 ObjCMethod->setInvalidDecl();
3257 return ObjCMethod;
3258 }
3259
3260 // If this Objective-C method does not have a related result type, but we
3261 // are allowed to infer related result types, try to do so based on the
3262 // method family.
3263 ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3264 if (!CurrentClass) {
3265 if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3266 CurrentClass = Cat->getClassInterface();
3267 else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3268 CurrentClass = Impl->getClassInterface();
3269 else if (ObjCCategoryImplDecl *CatImpl
3270 = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3271 CurrentClass = CatImpl->getClassInterface();
3272 }
3273
3274 ResultTypeCompatibilityKind RTC
3275 = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
3276
3277 CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
3278
3279 bool ARCError = false;
3280 if (getLangOpts().ObjCAutoRefCount)
3281 ARCError = CheckARCMethodDecl(ObjCMethod);
3282
3283 // Infer the related result type when possible.
3284 if (!ARCError && RTC == Sema::RTC_Compatible &&
3285 !ObjCMethod->hasRelatedResultType() &&
3286 LangOpts.ObjCInferRelatedResultType) {
3287 bool InferRelatedResultType = false;
3288 switch (ObjCMethod->getMethodFamily()) {
3289 case OMF_None:
3290 case OMF_copy:
3291 case OMF_dealloc:
3292 case OMF_finalize:
3293 case OMF_mutableCopy:
3294 case OMF_release:
3295 case OMF_retainCount:
3296 case OMF_initialize:
3297 case OMF_performSelector:
3298 break;
3299
3300 case OMF_alloc:
3301 case OMF_new:
3302 InferRelatedResultType = ObjCMethod->isClassMethod();
3303 break;
3304
3305 case OMF_init:
3306 case OMF_autorelease:
3307 case OMF_retain:
3308 case OMF_self:
3309 InferRelatedResultType = ObjCMethod->isInstanceMethod();
3310 break;
3311 }
3312
3313 if (InferRelatedResultType &&
3314 !ObjCMethod->getReturnType()->isObjCIndependentClassType())
3315 ObjCMethod->SetRelatedResultType();
3316 }
3317
3318 ActOnDocumentableDecl(ObjCMethod);
3319
3320 return ObjCMethod;
3321 }
3322
CheckObjCDeclScope(Decl * D)3323 bool Sema::CheckObjCDeclScope(Decl *D) {
3324 // Following is also an error. But it is caused by a missing @end
3325 // and diagnostic is issued elsewhere.
3326 if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
3327 return false;
3328
3329 // If we switched context to translation unit while we are still lexically in
3330 // an objc container, it means the parser missed emitting an error.
3331 if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3332 return false;
3333
3334 Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3335 D->setInvalidDecl();
3336
3337 return true;
3338 }
3339
3340 /// Called whenever \@defs(ClassName) is encountered in the source. Inserts the
3341 /// instance variables of ClassName into Decls.
ActOnDefs(Scope * S,Decl * TagD,SourceLocation DeclStart,IdentifierInfo * ClassName,SmallVectorImpl<Decl * > & Decls)3342 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3343 IdentifierInfo *ClassName,
3344 SmallVectorImpl<Decl*> &Decls) {
3345 // Check that ClassName is a valid class
3346 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
3347 if (!Class) {
3348 Diag(DeclStart, diag::err_undef_interface) << ClassName;
3349 return;
3350 }
3351 if (LangOpts.ObjCRuntime.isNonFragile()) {
3352 Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3353 return;
3354 }
3355
3356 // Collect the instance variables
3357 SmallVector<const ObjCIvarDecl*, 32> Ivars;
3358 Context.DeepCollectObjCIvars(Class, true, Ivars);
3359 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
3360 for (unsigned i = 0; i < Ivars.size(); i++) {
3361 const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
3362 RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
3363 Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3364 /*FIXME: StartL=*/ID->getLocation(),
3365 ID->getLocation(),
3366 ID->getIdentifier(), ID->getType(),
3367 ID->getBitWidth());
3368 Decls.push_back(FD);
3369 }
3370
3371 // Introduce all of these fields into the appropriate scope.
3372 for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
3373 D != Decls.end(); ++D) {
3374 FieldDecl *FD = cast<FieldDecl>(*D);
3375 if (getLangOpts().CPlusPlus)
3376 PushOnScopeChains(cast<FieldDecl>(FD), S);
3377 else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
3378 Record->addDecl(FD);
3379 }
3380 }
3381
3382 /// \brief Build a type-check a new Objective-C exception variable declaration.
BuildObjCExceptionDecl(TypeSourceInfo * TInfo,QualType T,SourceLocation StartLoc,SourceLocation IdLoc,IdentifierInfo * Id,bool Invalid)3383 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3384 SourceLocation StartLoc,
3385 SourceLocation IdLoc,
3386 IdentifierInfo *Id,
3387 bool Invalid) {
3388 // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3389 // duration shall not be qualified by an address-space qualifier."
3390 // Since all parameters have automatic store duration, they can not have
3391 // an address space.
3392 if (T.getAddressSpace() != 0) {
3393 Diag(IdLoc, diag::err_arg_with_address_space);
3394 Invalid = true;
3395 }
3396
3397 // An @catch parameter must be an unqualified object pointer type;
3398 // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3399 if (Invalid) {
3400 // Don't do any further checking.
3401 } else if (T->isDependentType()) {
3402 // Okay: we don't know what this type will instantiate to.
3403 } else if (!T->isObjCObjectPointerType()) {
3404 Invalid = true;
3405 Diag(IdLoc ,diag::err_catch_param_not_objc_type);
3406 } else if (T->isObjCQualifiedIdType()) {
3407 Invalid = true;
3408 Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
3409 }
3410
3411 VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
3412 T, TInfo, SC_None);
3413 New->setExceptionVariable(true);
3414
3415 // In ARC, infer 'retaining' for variables of retainable type.
3416 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
3417 Invalid = true;
3418
3419 if (Invalid)
3420 New->setInvalidDecl();
3421 return New;
3422 }
3423
ActOnObjCExceptionDecl(Scope * S,Declarator & D)3424 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
3425 const DeclSpec &DS = D.getDeclSpec();
3426
3427 // We allow the "register" storage class on exception variables because
3428 // GCC did, but we drop it completely. Any other storage class is an error.
3429 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3430 Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3431 << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
3432 } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3433 Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
3434 << DeclSpec::getSpecifierName(SCS);
3435 }
3436 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
3437 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
3438 diag::err_invalid_thread)
3439 << DeclSpec::getSpecifierName(TSCS);
3440 D.getMutableDeclSpec().ClearStorageClassSpecs();
3441
3442 DiagnoseFunctionSpecifiers(D.getDeclSpec());
3443
3444 // Check that there are no default arguments inside the type of this
3445 // exception object (C++ only).
3446 if (getLangOpts().CPlusPlus)
3447 CheckExtraCXXDefaultArguments(D);
3448
3449 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3450 QualType ExceptionType = TInfo->getType();
3451
3452 VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3453 D.getSourceRange().getBegin(),
3454 D.getIdentifierLoc(),
3455 D.getIdentifier(),
3456 D.isInvalidType());
3457
3458 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3459 if (D.getCXXScopeSpec().isSet()) {
3460 Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3461 << D.getCXXScopeSpec().getRange();
3462 New->setInvalidDecl();
3463 }
3464
3465 // Add the parameter declaration into this scope.
3466 S->AddDecl(New);
3467 if (D.getIdentifier())
3468 IdResolver.AddDecl(New);
3469
3470 ProcessDeclAttributes(S, New, D);
3471
3472 if (New->hasAttr<BlocksAttr>())
3473 Diag(New->getLocation(), diag::err_block_on_nonlocal);
3474 return New;
3475 }
3476
3477 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3478 /// initialization.
CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl * OI,SmallVectorImpl<ObjCIvarDecl * > & Ivars)3479 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3480 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
3481 for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3482 Iv= Iv->getNextIvar()) {
3483 QualType QT = Context.getBaseElementType(Iv->getType());
3484 if (QT->isRecordType())
3485 Ivars.push_back(Iv);
3486 }
3487 }
3488
DiagnoseUseOfUnimplementedSelectors()3489 void Sema::DiagnoseUseOfUnimplementedSelectors() {
3490 // Load referenced selectors from the external source.
3491 if (ExternalSource) {
3492 SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3493 ExternalSource->ReadReferencedSelectors(Sels);
3494 for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3495 ReferencedSelectors[Sels[I].first] = Sels[I].second;
3496 }
3497
3498 // Warning will be issued only when selector table is
3499 // generated (which means there is at lease one implementation
3500 // in the TU). This is to match gcc's behavior.
3501 if (ReferencedSelectors.empty() ||
3502 !Context.AnyObjCImplementation())
3503 return;
3504 for (auto &SelectorAndLocation : ReferencedSelectors) {
3505 Selector Sel = SelectorAndLocation.first;
3506 SourceLocation Loc = SelectorAndLocation.second;
3507 if (!LookupImplementedMethodInGlobalPool(Sel))
3508 Diag(Loc, diag::warn_unimplemented_selector) << Sel;
3509 }
3510 return;
3511 }
3512
3513 ObjCIvarDecl *
GetIvarBackingPropertyAccessor(const ObjCMethodDecl * Method,const ObjCPropertyDecl * & PDecl) const3514 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3515 const ObjCPropertyDecl *&PDecl) const {
3516 if (Method->isClassMethod())
3517 return nullptr;
3518 const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
3519 if (!IDecl)
3520 return nullptr;
3521 Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
3522 /*shallowCategoryLookup=*/false,
3523 /*followSuper=*/false);
3524 if (!Method || !Method->isPropertyAccessor())
3525 return nullptr;
3526 if ((PDecl = Method->findPropertyDecl()))
3527 if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
3528 // property backing ivar must belong to property's class
3529 // or be a private ivar in class's implementation.
3530 // FIXME. fix the const-ness issue.
3531 IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
3532 IV->getIdentifier());
3533 return IV;
3534 }
3535 return nullptr;
3536 }
3537
3538 namespace {
3539 /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
3540 /// accessor references the backing ivar.
3541 class UnusedBackingIvarChecker :
3542 public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
3543 public:
3544 Sema &S;
3545 const ObjCMethodDecl *Method;
3546 const ObjCIvarDecl *IvarD;
3547 bool AccessedIvar;
3548 bool InvokedSelfMethod;
3549
UnusedBackingIvarChecker(Sema & S,const ObjCMethodDecl * Method,const ObjCIvarDecl * IvarD)3550 UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
3551 const ObjCIvarDecl *IvarD)
3552 : S(S), Method(Method), IvarD(IvarD),
3553 AccessedIvar(false), InvokedSelfMethod(false) {
3554 assert(IvarD);
3555 }
3556
VisitObjCIvarRefExpr(ObjCIvarRefExpr * E)3557 bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
3558 if (E->getDecl() == IvarD) {
3559 AccessedIvar = true;
3560 return false;
3561 }
3562 return true;
3563 }
3564
VisitObjCMessageExpr(ObjCMessageExpr * E)3565 bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
3566 if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
3567 S.isSelfExpr(E->getInstanceReceiver(), Method)) {
3568 InvokedSelfMethod = true;
3569 }
3570 return true;
3571 }
3572 };
3573 }
3574
DiagnoseUnusedBackingIvarInAccessor(Scope * S,const ObjCImplementationDecl * ImplD)3575 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3576 const ObjCImplementationDecl *ImplD) {
3577 if (S->hasUnrecoverableErrorOccurred())
3578 return;
3579
3580 for (const auto *CurMethod : ImplD->instance_methods()) {
3581 unsigned DIAG = diag::warn_unused_property_backing_ivar;
3582 SourceLocation Loc = CurMethod->getLocation();
3583 if (Diags.isIgnored(DIAG, Loc))
3584 continue;
3585
3586 const ObjCPropertyDecl *PDecl;
3587 const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
3588 if (!IV)
3589 continue;
3590
3591 UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
3592 Checker.TraverseStmt(CurMethod->getBody());
3593 if (Checker.AccessedIvar)
3594 continue;
3595
3596 // Do not issue this warning if backing ivar is used somewhere and accessor
3597 // implementation makes a self call. This is to prevent false positive in
3598 // cases where the ivar is accessed by another method that the accessor
3599 // delegates to.
3600 if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
3601 Diag(Loc, DIAG) << IV;
3602 Diag(PDecl->getLocation(), diag::note_property_declare);
3603 }
3604 }
3605 }
3606