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