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