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