Clang Project

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