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