clang API Documentation

SemaDeclObjC.cpp
Go to the documentation of this file.
00001 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 //  This file implements semantic analysis for Objective C declarations.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #include "clang/Sema/SemaInternal.h"
00015 #include "clang/AST/ASTConsumer.h"
00016 #include "clang/AST/ASTContext.h"
00017 #include "clang/AST/ASTMutationListener.h"
00018 #include "clang/AST/DataRecursiveASTVisitor.h"
00019 #include "clang/AST/DeclObjC.h"
00020 #include "clang/AST/Expr.h"
00021 #include "clang/AST/ExprObjC.h"
00022 #include "clang/Basic/SourceManager.h"
00023 #include "clang/Sema/DeclSpec.h"
00024 #include "clang/Sema/ExternalSemaSource.h"
00025 #include "clang/Sema/Lookup.h"
00026 #include "clang/Sema/Scope.h"
00027 #include "clang/Sema/ScopeInfo.h"
00028 #include "llvm/ADT/DenseSet.h"
00029 
00030 using namespace clang;
00031 
00032 /// Check whether the given method, which must be in the 'init'
00033 /// family, is a valid member of that family.
00034 ///
00035 /// \param receiverTypeIfCall - if null, check this as if declaring it;
00036 ///   if non-null, check this as if making a call to it with the given
00037 ///   receiver type
00038 ///
00039 /// \return true to indicate that there was an error and appropriate
00040 ///   actions were taken
00041 bool Sema::checkInitMethod(ObjCMethodDecl *method,
00042                            QualType receiverTypeIfCall) {
00043   if (method->isInvalidDecl()) return true;
00044 
00045   // This castAs is safe: methods that don't return an object
00046   // pointer won't be inferred as inits and will reject an explicit
00047   // objc_method_family(init).
00048 
00049   // We ignore protocols here.  Should we?  What about Class?
00050 
00051   const ObjCObjectType *result =
00052       method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
00053 
00054   if (result->isObjCId()) {
00055     return false;
00056   } else if (result->isObjCClass()) {
00057     // fall through: always an error
00058   } else {
00059     ObjCInterfaceDecl *resultClass = result->getInterface();
00060     assert(resultClass && "unexpected object type!");
00061 
00062     // It's okay for the result type to still be a forward declaration
00063     // if we're checking an interface declaration.
00064     if (!resultClass->hasDefinition()) {
00065       if (receiverTypeIfCall.isNull() &&
00066           !isa<ObjCImplementationDecl>(method->getDeclContext()))
00067         return false;
00068 
00069     // Otherwise, we try to compare class types.
00070     } else {
00071       // If this method was declared in a protocol, we can't check
00072       // anything unless we have a receiver type that's an interface.
00073       const ObjCInterfaceDecl *receiverClass = nullptr;
00074       if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
00075         if (receiverTypeIfCall.isNull())
00076           return false;
00077 
00078         receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
00079           ->getInterfaceDecl();
00080 
00081         // This can be null for calls to e.g. id<Foo>.
00082         if (!receiverClass) return false;
00083       } else {
00084         receiverClass = method->getClassInterface();
00085         assert(receiverClass && "method not associated with a class!");
00086       }
00087 
00088       // If either class is a subclass of the other, it's fine.
00089       if (receiverClass->isSuperClassOf(resultClass) ||
00090           resultClass->isSuperClassOf(receiverClass))
00091         return false;
00092     }
00093   }
00094 
00095   SourceLocation loc = method->getLocation();
00096 
00097   // If we're in a system header, and this is not a call, just make
00098   // the method unusable.
00099   if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
00100     method->addAttr(UnavailableAttr::CreateImplicit(Context,
00101                 "init method returns a type unrelated to its receiver type",
00102                 loc));
00103     return true;
00104   }
00105 
00106   // Otherwise, it's an error.
00107   Diag(loc, diag::err_arc_init_method_unrelated_result_type);
00108   method->setInvalidDecl();
00109   return true;
00110 }
00111 
00112 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod, 
00113                                    const ObjCMethodDecl *Overridden) {
00114   if (Overridden->hasRelatedResultType() && 
00115       !NewMethod->hasRelatedResultType()) {
00116     // This can only happen when the method follows a naming convention that
00117     // implies a related result type, and the original (overridden) method has
00118     // a suitable return type, but the new (overriding) method does not have
00119     // a suitable return type.
00120     QualType ResultType = NewMethod->getReturnType();
00121     SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
00122     
00123     // Figure out which class this method is part of, if any.
00124     ObjCInterfaceDecl *CurrentClass 
00125       = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
00126     if (!CurrentClass) {
00127       DeclContext *DC = NewMethod->getDeclContext();
00128       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
00129         CurrentClass = Cat->getClassInterface();
00130       else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
00131         CurrentClass = Impl->getClassInterface();
00132       else if (ObjCCategoryImplDecl *CatImpl
00133                = dyn_cast<ObjCCategoryImplDecl>(DC))
00134         CurrentClass = CatImpl->getClassInterface();
00135     }
00136     
00137     if (CurrentClass) {
00138       Diag(NewMethod->getLocation(), 
00139            diag::warn_related_result_type_compatibility_class)
00140         << Context.getObjCInterfaceType(CurrentClass)
00141         << ResultType
00142         << ResultTypeRange;
00143     } else {
00144       Diag(NewMethod->getLocation(), 
00145            diag::warn_related_result_type_compatibility_protocol)
00146         << ResultType
00147         << ResultTypeRange;
00148     }
00149     
00150     if (ObjCMethodFamily Family = Overridden->getMethodFamily())
00151       Diag(Overridden->getLocation(), 
00152            diag::note_related_result_type_family)
00153         << /*overridden method*/ 0
00154         << Family;
00155     else
00156       Diag(Overridden->getLocation(), 
00157            diag::note_related_result_type_overridden);
00158   }
00159   if (getLangOpts().ObjCAutoRefCount) {
00160     if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
00161          Overridden->hasAttr<NSReturnsRetainedAttr>())) {
00162         Diag(NewMethod->getLocation(),
00163              diag::err_nsreturns_retained_attribute_mismatch) << 1;
00164         Diag(Overridden->getLocation(), diag::note_previous_decl) 
00165         << "method";
00166     }
00167     if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
00168               Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
00169         Diag(NewMethod->getLocation(),
00170              diag::err_nsreturns_retained_attribute_mismatch) << 0;
00171         Diag(Overridden->getLocation(), diag::note_previous_decl) 
00172         << "method";
00173     }
00174     ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
00175                                          oe = Overridden->param_end();
00176     for (ObjCMethodDecl::param_iterator
00177            ni = NewMethod->param_begin(), ne = NewMethod->param_end();
00178          ni != ne && oi != oe; ++ni, ++oi) {
00179       const ParmVarDecl *oldDecl = (*oi);
00180       ParmVarDecl *newDecl = (*ni);
00181       if (newDecl->hasAttr<NSConsumedAttr>() != 
00182           oldDecl->hasAttr<NSConsumedAttr>()) {
00183         Diag(newDecl->getLocation(),
00184              diag::err_nsconsumed_attribute_mismatch);
00185         Diag(oldDecl->getLocation(), diag::note_previous_decl) 
00186           << "parameter";
00187       }
00188     }
00189   }
00190 }
00191 
00192 /// \brief Check a method declaration for compatibility with the Objective-C
00193 /// ARC conventions.
00194 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
00195   ObjCMethodFamily family = method->getMethodFamily();
00196   switch (family) {
00197   case OMF_None:
00198   case OMF_finalize:
00199   case OMF_retain:
00200   case OMF_release:
00201   case OMF_autorelease:
00202   case OMF_retainCount:
00203   case OMF_self:
00204   case OMF_initialize:
00205   case OMF_performSelector:
00206     return false;
00207 
00208   case OMF_dealloc:
00209     if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
00210       SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
00211       if (ResultTypeRange.isInvalid())
00212         Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
00213             << method->getReturnType()
00214             << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
00215       else
00216         Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
00217             << method->getReturnType()
00218             << FixItHint::CreateReplacement(ResultTypeRange, "void");
00219       return true;
00220     }
00221     return false;
00222       
00223   case OMF_init:
00224     // If the method doesn't obey the init rules, don't bother annotating it.
00225     if (checkInitMethod(method, QualType()))
00226       return true;
00227 
00228     method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
00229 
00230     // Don't add a second copy of this attribute, but otherwise don't
00231     // let it be suppressed.
00232     if (method->hasAttr<NSReturnsRetainedAttr>())
00233       return false;
00234     break;
00235 
00236   case OMF_alloc:
00237   case OMF_copy:
00238   case OMF_mutableCopy:
00239   case OMF_new:
00240     if (method->hasAttr<NSReturnsRetainedAttr>() ||
00241         method->hasAttr<NSReturnsNotRetainedAttr>() ||
00242         method->hasAttr<NSReturnsAutoreleasedAttr>())
00243       return false;
00244     break;
00245   }
00246 
00247   method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
00248   return false;
00249 }
00250 
00251 static void DiagnoseObjCImplementedDeprecations(Sema &S,
00252                                                 NamedDecl *ND,
00253                                                 SourceLocation ImplLoc,
00254                                                 int select) {
00255   if (ND && ND->isDeprecated()) {
00256     S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
00257     if (select == 0)
00258       S.Diag(ND->getLocation(), diag::note_method_declared_at)
00259         << ND->getDeclName();
00260     else
00261       S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
00262   }
00263 }
00264 
00265 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
00266 /// pool.
00267 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
00268   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
00269     
00270   // If we don't have a valid method decl, simply return.
00271   if (!MDecl)
00272     return;
00273   if (MDecl->isInstanceMethod())
00274     AddInstanceMethodToGlobalPool(MDecl, true);
00275   else
00276     AddFactoryMethodToGlobalPool(MDecl, true);
00277 }
00278 
00279 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
00280 /// has explicit ownership attribute; false otherwise.
00281 static bool
00282 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
00283   QualType T = Param->getType();
00284   
00285   if (const PointerType *PT = T->getAs<PointerType>()) {
00286     T = PT->getPointeeType();
00287   } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
00288     T = RT->getPointeeType();
00289   } else {
00290     return true;
00291   }
00292   
00293   // If we have a lifetime qualifier, but it's local, we must have 
00294   // inferred it. So, it is implicit.
00295   return !T.getLocalQualifiers().hasObjCLifetime();
00296 }
00297 
00298 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
00299 /// and user declared, in the method definition's AST.
00300 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
00301   assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
00302   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
00303   
00304   // If we don't have a valid method decl, simply return.
00305   if (!MDecl)
00306     return;
00307 
00308   // Allow all of Sema to see that we are entering a method definition.
00309   PushDeclContext(FnBodyScope, MDecl);
00310   PushFunctionScope();
00311   
00312   // Create Decl objects for each parameter, entrring them in the scope for
00313   // binding to their use.
00314 
00315   // Insert the invisible arguments, self and _cmd!
00316   MDecl->createImplicitParams(Context, MDecl->getClassInterface());
00317 
00318   PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
00319   PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
00320 
00321   // The ObjC parser requires parameter names so there's no need to check.
00322   CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
00323                            /*CheckParameterNames=*/false);
00324 
00325   // Introduce all of the other parameters into this scope.
00326   for (auto *Param : MDecl->params()) {
00327     if (!Param->isInvalidDecl() &&
00328         getLangOpts().ObjCAutoRefCount &&
00329         !HasExplicitOwnershipAttr(*this, Param))
00330       Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
00331             Param->getType();
00332     
00333     if (Param->getIdentifier())
00334       PushOnScopeChains(Param, FnBodyScope);
00335   }
00336 
00337   // In ARC, disallow definition of retain/release/autorelease/retainCount
00338   if (getLangOpts().ObjCAutoRefCount) {
00339     switch (MDecl->getMethodFamily()) {
00340     case OMF_retain:
00341     case OMF_retainCount:
00342     case OMF_release:
00343     case OMF_autorelease:
00344       Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
00345         << 0 << MDecl->getSelector();
00346       break;
00347 
00348     case OMF_None:
00349     case OMF_dealloc:
00350     case OMF_finalize:
00351     case OMF_alloc:
00352     case OMF_init:
00353     case OMF_mutableCopy:
00354     case OMF_copy:
00355     case OMF_new:
00356     case OMF_self:
00357     case OMF_initialize:
00358     case OMF_performSelector:
00359       break;
00360     }
00361   }
00362 
00363   // Warn on deprecated methods under -Wdeprecated-implementations,
00364   // and prepare for warning on missing super calls.
00365   if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
00366     ObjCMethodDecl *IMD = 
00367       IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
00368     
00369     if (IMD) {
00370       ObjCImplDecl *ImplDeclOfMethodDef = 
00371         dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
00372       ObjCContainerDecl *ContDeclOfMethodDecl = 
00373         dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
00374       ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
00375       if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
00376         ImplDeclOfMethodDecl = OID->getImplementation();
00377       else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
00378         if (CD->IsClassExtension()) {
00379           if (ObjCInterfaceDecl *OID = CD->getClassInterface())
00380             ImplDeclOfMethodDecl = OID->getImplementation();
00381         } else
00382             ImplDeclOfMethodDecl = CD->getImplementation();
00383       }
00384       // No need to issue deprecated warning if deprecated mehod in class/category
00385       // is being implemented in its own implementation (no overriding is involved).
00386       if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
00387         DiagnoseObjCImplementedDeprecations(*this, 
00388                                           dyn_cast<NamedDecl>(IMD), 
00389                                           MDecl->getLocation(), 0);
00390     }
00391 
00392     if (MDecl->getMethodFamily() == OMF_init) {
00393       if (MDecl->isDesignatedInitializerForTheInterface()) {
00394         getCurFunction()->ObjCIsDesignatedInit = true;
00395         getCurFunction()->ObjCWarnForNoDesignatedInitChain =
00396             IC->getSuperClass() != nullptr;
00397       } else if (IC->hasDesignatedInitializers()) {
00398         getCurFunction()->ObjCIsSecondaryInit = true;
00399         getCurFunction()->ObjCWarnForNoInitDelegation = true;
00400       }
00401     }
00402 
00403     // If this is "dealloc" or "finalize", set some bit here.
00404     // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
00405     // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
00406     // Only do this if the current class actually has a superclass.
00407     if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
00408       ObjCMethodFamily Family = MDecl->getMethodFamily();
00409       if (Family == OMF_dealloc) {
00410         if (!(getLangOpts().ObjCAutoRefCount ||
00411               getLangOpts().getGC() == LangOptions::GCOnly))
00412           getCurFunction()->ObjCShouldCallSuper = true;
00413 
00414       } else if (Family == OMF_finalize) {
00415         if (Context.getLangOpts().getGC() != LangOptions::NonGC)
00416           getCurFunction()->ObjCShouldCallSuper = true;
00417         
00418       } else {
00419         const ObjCMethodDecl *SuperMethod =
00420           SuperClass->lookupMethod(MDecl->getSelector(),
00421                                    MDecl->isInstanceMethod());
00422         getCurFunction()->ObjCShouldCallSuper = 
00423           (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
00424       }
00425     }
00426   }
00427 }
00428 
00429 namespace {
00430 
00431 // Callback to only accept typo corrections that are Objective-C classes.
00432 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
00433 // function will reject corrections to that class.
00434 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
00435  public:
00436   ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
00437   explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
00438       : CurrentIDecl(IDecl) {}
00439 
00440   bool ValidateCandidate(const TypoCorrection &candidate) override {
00441     ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
00442     return ID && !declaresSameEntity(ID, CurrentIDecl);
00443   }
00444 
00445  private:
00446   ObjCInterfaceDecl *CurrentIDecl;
00447 };
00448 
00449 }
00450 
00451 Decl *Sema::
00452 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
00453                          IdentifierInfo *ClassName, SourceLocation ClassLoc,
00454                          IdentifierInfo *SuperName, SourceLocation SuperLoc,
00455                          Decl * const *ProtoRefs, unsigned NumProtoRefs,
00456                          const SourceLocation *ProtoLocs, 
00457                          SourceLocation EndProtoLoc, AttributeList *AttrList) {
00458   assert(ClassName && "Missing class identifier");
00459 
00460   // Check for another declaration kind with the same name.
00461   NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
00462                                          LookupOrdinaryName, ForRedeclaration);
00463 
00464   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
00465     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
00466     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
00467   }
00468 
00469   // Create a declaration to describe this @interface.
00470   ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
00471 
00472   if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
00473     // A previous decl with a different name is because of
00474     // @compatibility_alias, for example:
00475     // \code
00476     //   @class NewImage;
00477     //   @compatibility_alias OldImage NewImage;
00478     // \endcode
00479     // A lookup for 'OldImage' will return the 'NewImage' decl.
00480     //
00481     // In such a case use the real declaration name, instead of the alias one,
00482     // otherwise we will break IdentifierResolver and redecls-chain invariants.
00483     // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
00484     // has been aliased.
00485     ClassName = PrevIDecl->getIdentifier();
00486   }
00487 
00488   ObjCInterfaceDecl *IDecl
00489     = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
00490                                 PrevIDecl, ClassLoc);
00491   
00492   if (PrevIDecl) {
00493     // Class already seen. Was it a definition?
00494     if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
00495       Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
00496         << PrevIDecl->getDeclName();
00497       Diag(Def->getLocation(), diag::note_previous_definition);
00498       IDecl->setInvalidDecl();
00499     }
00500   }
00501   
00502   if (AttrList)
00503     ProcessDeclAttributeList(TUScope, IDecl, AttrList);
00504   PushOnScopeChains(IDecl, TUScope);
00505 
00506   // Start the definition of this class. If we're in a redefinition case, there 
00507   // may already be a definition, so we'll end up adding to it.
00508   if (!IDecl->hasDefinition())
00509     IDecl->startDefinition();
00510   
00511   if (SuperName) {
00512     // Check if a different kind of symbol declared in this scope.
00513     PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
00514                                 LookupOrdinaryName);
00515 
00516     if (!PrevDecl) {
00517       // Try to correct for a typo in the superclass name without correcting
00518       // to the class we're defining.
00519       if (TypoCorrection Corrected =
00520               CorrectTypo(DeclarationNameInfo(SuperName, SuperLoc),
00521                           LookupOrdinaryName, TUScope, nullptr,
00522                           llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
00523                           CTK_ErrorRecovery)) {
00524         diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
00525                                     << SuperName << ClassName);
00526         PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
00527       }
00528     }
00529 
00530     if (declaresSameEntity(PrevDecl, IDecl)) {
00531       Diag(SuperLoc, diag::err_recursive_superclass)
00532         << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
00533       IDecl->setEndOfDefinitionLoc(ClassLoc);
00534     } else {
00535       ObjCInterfaceDecl *SuperClassDecl =
00536                                 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
00537 
00538       // Diagnose classes that inherit from deprecated classes.
00539       if (SuperClassDecl)
00540         (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
00541 
00542       if (PrevDecl && !SuperClassDecl) {
00543         // The previous declaration was not a class decl. Check if we have a
00544         // typedef. If we do, get the underlying class type.
00545         if (const TypedefNameDecl *TDecl =
00546               dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
00547           QualType T = TDecl->getUnderlyingType();
00548           if (T->isObjCObjectType()) {
00549             if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
00550               SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
00551               // This handles the following case:
00552               // @interface NewI @end
00553               // typedef NewI DeprI __attribute__((deprecated("blah")))
00554               // @interface SI : DeprI /* warn here */ @end
00555               (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
00556             }
00557           }
00558         }
00559 
00560         // This handles the following case:
00561         //
00562         // typedef int SuperClass;
00563         // @interface MyClass : SuperClass {} @end
00564         //
00565         if (!SuperClassDecl) {
00566           Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
00567           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
00568         }
00569       }
00570 
00571       if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
00572         if (!SuperClassDecl)
00573           Diag(SuperLoc, diag::err_undef_superclass)
00574             << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
00575         else if (RequireCompleteType(SuperLoc, 
00576                                   Context.getObjCInterfaceType(SuperClassDecl),
00577                                      diag::err_forward_superclass,
00578                                      SuperClassDecl->getDeclName(),
00579                                      ClassName,
00580                                      SourceRange(AtInterfaceLoc, ClassLoc))) {
00581           SuperClassDecl = nullptr;
00582         }
00583       }
00584       IDecl->setSuperClass(SuperClassDecl);
00585       IDecl->setSuperClassLoc(SuperLoc);
00586       IDecl->setEndOfDefinitionLoc(SuperLoc);
00587     }
00588   } else { // we have a root class.
00589     IDecl->setEndOfDefinitionLoc(ClassLoc);
00590   }
00591 
00592   // Check then save referenced protocols.
00593   if (NumProtoRefs) {
00594     IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
00595                            ProtoLocs, Context);
00596     IDecl->setEndOfDefinitionLoc(EndProtoLoc);
00597   }
00598 
00599   CheckObjCDeclScope(IDecl);
00600   return ActOnObjCContainerStartDefinition(IDecl);
00601 }
00602 
00603 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
00604 /// typedef'ed use for a qualified super class and adds them to the list
00605 /// of the protocols.
00606 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
00607                                    IdentifierInfo *SuperName,
00608                                    SourceLocation SuperLoc) {
00609   if (!SuperName)
00610     return;
00611   NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
00612                                       LookupOrdinaryName);
00613   if (!IDecl)
00614     return;
00615   
00616   if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
00617     QualType T = TDecl->getUnderlyingType();
00618     if (T->isObjCObjectType())
00619       if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
00620         for (auto *I : OPT->quals())
00621           ProtocolRefs.push_back(I);
00622   }
00623 }
00624 
00625 /// ActOnCompatibilityAlias - this action is called after complete parsing of
00626 /// a \@compatibility_alias declaration. It sets up the alias relationships.
00627 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
00628                                     IdentifierInfo *AliasName,
00629                                     SourceLocation AliasLocation,
00630                                     IdentifierInfo *ClassName,
00631                                     SourceLocation ClassLocation) {
00632   // Look for previous declaration of alias name
00633   NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
00634                                       LookupOrdinaryName, ForRedeclaration);
00635   if (ADecl) {
00636     Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
00637     Diag(ADecl->getLocation(), diag::note_previous_declaration);
00638     return nullptr;
00639   }
00640   // Check for class declaration
00641   NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
00642                                        LookupOrdinaryName, ForRedeclaration);
00643   if (const TypedefNameDecl *TDecl =
00644         dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
00645     QualType T = TDecl->getUnderlyingType();
00646     if (T->isObjCObjectType()) {
00647       if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
00648         ClassName = IDecl->getIdentifier();
00649         CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
00650                                   LookupOrdinaryName, ForRedeclaration);
00651       }
00652     }
00653   }
00654   ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
00655   if (!CDecl) {
00656     Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
00657     if (CDeclU)
00658       Diag(CDeclU->getLocation(), diag::note_previous_declaration);
00659     return nullptr;
00660   }
00661 
00662   // Everything checked out, instantiate a new alias declaration AST.
00663   ObjCCompatibleAliasDecl *AliasDecl =
00664     ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
00665 
00666   if (!CheckObjCDeclScope(AliasDecl))
00667     PushOnScopeChains(AliasDecl, TUScope);
00668 
00669   return AliasDecl;
00670 }
00671 
00672 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
00673   IdentifierInfo *PName,
00674   SourceLocation &Ploc, SourceLocation PrevLoc,
00675   const ObjCList<ObjCProtocolDecl> &PList) {
00676   
00677   bool res = false;
00678   for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
00679        E = PList.end(); I != E; ++I) {
00680     if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
00681                                                  Ploc)) {
00682       if (PDecl->getIdentifier() == PName) {
00683         Diag(Ploc, diag::err_protocol_has_circular_dependency);
00684         Diag(PrevLoc, diag::note_previous_definition);
00685         res = true;
00686       }
00687       
00688       if (!PDecl->hasDefinition())
00689         continue;
00690       
00691       if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
00692             PDecl->getLocation(), PDecl->getReferencedProtocols()))
00693         res = true;
00694     }
00695   }
00696   return res;
00697 }
00698 
00699 Decl *
00700 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
00701                                   IdentifierInfo *ProtocolName,
00702                                   SourceLocation ProtocolLoc,
00703                                   Decl * const *ProtoRefs,
00704                                   unsigned NumProtoRefs,
00705                                   const SourceLocation *ProtoLocs,
00706                                   SourceLocation EndProtoLoc,
00707                                   AttributeList *AttrList) {
00708   bool err = false;
00709   // FIXME: Deal with AttrList.
00710   assert(ProtocolName && "Missing protocol identifier");
00711   ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
00712                                               ForRedeclaration);
00713   ObjCProtocolDecl *PDecl = nullptr;
00714   if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
00715     // If we already have a definition, complain.
00716     Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
00717     Diag(Def->getLocation(), diag::note_previous_definition);
00718 
00719     // Create a new protocol that is completely distinct from previous
00720     // declarations, and do not make this protocol available for name lookup.
00721     // That way, we'll end up completely ignoring the duplicate.
00722     // FIXME: Can we turn this into an error?
00723     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
00724                                      ProtocolLoc, AtProtoInterfaceLoc,
00725                                      /*PrevDecl=*/nullptr);
00726     PDecl->startDefinition();
00727   } else {
00728     if (PrevDecl) {
00729       // Check for circular dependencies among protocol declarations. This can
00730       // only happen if this protocol was forward-declared.
00731       ObjCList<ObjCProtocolDecl> PList;
00732       PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
00733       err = CheckForwardProtocolDeclarationForCircularDependency(
00734               ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
00735     }
00736 
00737     // Create the new declaration.
00738     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
00739                                      ProtocolLoc, AtProtoInterfaceLoc,
00740                                      /*PrevDecl=*/PrevDecl);
00741     
00742     PushOnScopeChains(PDecl, TUScope);
00743     PDecl->startDefinition();
00744   }
00745   
00746   if (AttrList)
00747     ProcessDeclAttributeList(TUScope, PDecl, AttrList);
00748   
00749   // Merge attributes from previous declarations.
00750   if (PrevDecl)
00751     mergeDeclAttributes(PDecl, PrevDecl);
00752 
00753   if (!err && NumProtoRefs ) {
00754     /// Check then save referenced protocols.
00755     PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
00756                            ProtoLocs, Context);
00757   }
00758 
00759   CheckObjCDeclScope(PDecl);
00760   return ActOnObjCContainerStartDefinition(PDecl);
00761 }
00762 
00763 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
00764                                           ObjCProtocolDecl *&UndefinedProtocol) {
00765   if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
00766     UndefinedProtocol = PDecl;
00767     return true;
00768   }
00769   
00770   for (auto *PI : PDecl->protocols())
00771     if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
00772       UndefinedProtocol = PI;
00773       return true;
00774     }
00775   return false;
00776 }
00777 
00778 /// FindProtocolDeclaration - This routine looks up protocols and
00779 /// issues an error if they are not declared. It returns list of
00780 /// protocol declarations in its 'Protocols' argument.
00781 void
00782 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
00783                               const IdentifierLocPair *ProtocolId,
00784                               unsigned NumProtocols,
00785                               SmallVectorImpl<Decl *> &Protocols) {
00786   for (unsigned i = 0; i != NumProtocols; ++i) {
00787     ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
00788                                              ProtocolId[i].second);
00789     if (!PDecl) {
00790       TypoCorrection Corrected = CorrectTypo(
00791           DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
00792           LookupObjCProtocolName, TUScope, nullptr,
00793           llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
00794           CTK_ErrorRecovery);
00795       if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
00796         diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
00797                                     << ProtocolId[i].first);
00798     }
00799 
00800     if (!PDecl) {
00801       Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
00802         << ProtocolId[i].first;
00803       continue;
00804     }
00805     // If this is a forward protocol declaration, get its definition.
00806     if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
00807       PDecl = PDecl->getDefinition();
00808     
00809     (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
00810 
00811     // If this is a forward declaration and we are supposed to warn in this
00812     // case, do it.
00813     // FIXME: Recover nicely in the hidden case.
00814     ObjCProtocolDecl *UndefinedProtocol;
00815     
00816     if (WarnOnDeclarations &&
00817         NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
00818       Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
00819         << ProtocolId[i].first;
00820       Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
00821         << UndefinedProtocol;
00822     }
00823     Protocols.push_back(PDecl);
00824   }
00825 }
00826 
00827 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
00828 /// a class method in its extension.
00829 ///
00830 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
00831                                             ObjCInterfaceDecl *ID) {
00832   if (!ID)
00833     return;  // Possibly due to previous error
00834 
00835   llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
00836   for (auto *MD : ID->methods())
00837     MethodMap[MD->getSelector()] = MD;
00838 
00839   if (MethodMap.empty())
00840     return;
00841   for (const auto *Method : CAT->methods()) {
00842     const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
00843     if (PrevMethod &&
00844         (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
00845         !MatchTwoMethodDeclarations(Method, PrevMethod)) {
00846       Diag(Method->getLocation(), diag::err_duplicate_method_decl)
00847             << Method->getDeclName();
00848       Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
00849     }
00850   }
00851 }
00852 
00853 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
00854 Sema::DeclGroupPtrTy
00855 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
00856                                       const IdentifierLocPair *IdentList,
00857                                       unsigned NumElts,
00858                                       AttributeList *attrList) {
00859   SmallVector<Decl *, 8> DeclsInGroup;
00860   for (unsigned i = 0; i != NumElts; ++i) {
00861     IdentifierInfo *Ident = IdentList[i].first;
00862     ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
00863                                                 ForRedeclaration);
00864     ObjCProtocolDecl *PDecl
00865       = ObjCProtocolDecl::Create(Context, CurContext, Ident, 
00866                                  IdentList[i].second, AtProtocolLoc,
00867                                  PrevDecl);
00868         
00869     PushOnScopeChains(PDecl, TUScope);
00870     CheckObjCDeclScope(PDecl);
00871     
00872     if (attrList)
00873       ProcessDeclAttributeList(TUScope, PDecl, attrList);
00874     
00875     if (PrevDecl)
00876       mergeDeclAttributes(PDecl, PrevDecl);
00877 
00878     DeclsInGroup.push_back(PDecl);
00879   }
00880 
00881   return BuildDeclaratorGroup(DeclsInGroup, false);
00882 }
00883 
00884 Decl *Sema::
00885 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
00886                             IdentifierInfo *ClassName, SourceLocation ClassLoc,
00887                             IdentifierInfo *CategoryName,
00888                             SourceLocation CategoryLoc,
00889                             Decl * const *ProtoRefs,
00890                             unsigned NumProtoRefs,
00891                             const SourceLocation *ProtoLocs,
00892                             SourceLocation EndProtoLoc) {
00893   ObjCCategoryDecl *CDecl;
00894   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
00895 
00896   /// Check that class of this category is already completely declared.
00897 
00898   if (!IDecl 
00899       || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
00900                              diag::err_category_forward_interface,
00901                              CategoryName == nullptr)) {
00902     // Create an invalid ObjCCategoryDecl to serve as context for
00903     // the enclosing method declarations.  We mark the decl invalid
00904     // to make it clear that this isn't a valid AST.
00905     CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
00906                                      ClassLoc, CategoryLoc, CategoryName,IDecl);
00907     CDecl->setInvalidDecl();
00908     CurContext->addDecl(CDecl);
00909         
00910     if (!IDecl)
00911       Diag(ClassLoc, diag::err_undef_interface) << ClassName;
00912     return ActOnObjCContainerStartDefinition(CDecl);
00913   }
00914 
00915   if (!CategoryName && IDecl->getImplementation()) {
00916     Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
00917     Diag(IDecl->getImplementation()->getLocation(), 
00918           diag::note_implementation_declared);
00919   }
00920 
00921   if (CategoryName) {
00922     /// Check for duplicate interface declaration for this category
00923     if (ObjCCategoryDecl *Previous
00924           = IDecl->FindCategoryDeclaration(CategoryName)) {
00925       // Class extensions can be declared multiple times, categories cannot.
00926       Diag(CategoryLoc, diag::warn_dup_category_def)
00927         << ClassName << CategoryName;
00928       Diag(Previous->getLocation(), diag::note_previous_definition);
00929     }
00930   }
00931 
00932   CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
00933                                    ClassLoc, CategoryLoc, CategoryName, IDecl);
00934   // FIXME: PushOnScopeChains?
00935   CurContext->addDecl(CDecl);
00936 
00937   if (NumProtoRefs) {
00938     CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs, 
00939                            ProtoLocs, Context);
00940     // Protocols in the class extension belong to the class.
00941     if (CDecl->IsClassExtension())
00942      IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs, 
00943                                             NumProtoRefs, Context); 
00944   }
00945 
00946   CheckObjCDeclScope(CDecl);
00947   return ActOnObjCContainerStartDefinition(CDecl);
00948 }
00949 
00950 /// ActOnStartCategoryImplementation - Perform semantic checks on the
00951 /// category implementation declaration and build an ObjCCategoryImplDecl
00952 /// object.
00953 Decl *Sema::ActOnStartCategoryImplementation(
00954                       SourceLocation AtCatImplLoc,
00955                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
00956                       IdentifierInfo *CatName, SourceLocation CatLoc) {
00957   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
00958   ObjCCategoryDecl *CatIDecl = nullptr;
00959   if (IDecl && IDecl->hasDefinition()) {
00960     CatIDecl = IDecl->FindCategoryDeclaration(CatName);
00961     if (!CatIDecl) {
00962       // Category @implementation with no corresponding @interface.
00963       // Create and install one.
00964       CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
00965                                           ClassLoc, CatLoc,
00966                                           CatName, IDecl);
00967       CatIDecl->setImplicit();
00968     }
00969   }
00970 
00971   ObjCCategoryImplDecl *CDecl =
00972     ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
00973                                  ClassLoc, AtCatImplLoc, CatLoc);
00974   /// Check that class of this category is already completely declared.
00975   if (!IDecl) {
00976     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
00977     CDecl->setInvalidDecl();
00978   } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
00979                                  diag::err_undef_interface)) {
00980     CDecl->setInvalidDecl();
00981   }
00982 
00983   // FIXME: PushOnScopeChains?
00984   CurContext->addDecl(CDecl);
00985 
00986   // If the interface is deprecated/unavailable, warn/error about it.
00987   if (IDecl)
00988     DiagnoseUseOfDecl(IDecl, ClassLoc);
00989 
00990   /// Check that CatName, category name, is not used in another implementation.
00991   if (CatIDecl) {
00992     if (CatIDecl->getImplementation()) {
00993       Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
00994         << CatName;
00995       Diag(CatIDecl->getImplementation()->getLocation(),
00996            diag::note_previous_definition);
00997       CDecl->setInvalidDecl();
00998     } else {
00999       CatIDecl->setImplementation(CDecl);
01000       // Warn on implementating category of deprecated class under 
01001       // -Wdeprecated-implementations flag.
01002       DiagnoseObjCImplementedDeprecations(*this, 
01003                                           dyn_cast<NamedDecl>(IDecl), 
01004                                           CDecl->getLocation(), 2);
01005     }
01006   }
01007 
01008   CheckObjCDeclScope(CDecl);
01009   return ActOnObjCContainerStartDefinition(CDecl);
01010 }
01011 
01012 Decl *Sema::ActOnStartClassImplementation(
01013                       SourceLocation AtClassImplLoc,
01014                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
01015                       IdentifierInfo *SuperClassname,
01016                       SourceLocation SuperClassLoc) {
01017   ObjCInterfaceDecl *IDecl = nullptr;
01018   // Check for another declaration kind with the same name.
01019   NamedDecl *PrevDecl
01020     = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
01021                        ForRedeclaration);
01022   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
01023     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
01024     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
01025   } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
01026     RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
01027                         diag::warn_undef_interface);
01028   } else {
01029     // We did not find anything with the name ClassName; try to correct for
01030     // typos in the class name.
01031     TypoCorrection Corrected = CorrectTypo(
01032         DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
01033         nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
01034     if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
01035       // Suggest the (potentially) correct interface name. Don't provide a
01036       // code-modification hint or use the typo name for recovery, because
01037       // this is just a warning. The program may actually be correct.
01038       diagnoseTypo(Corrected,
01039                    PDiag(diag::warn_undef_interface_suggest) << ClassName,
01040                    /*ErrorRecovery*/false);
01041     } else {
01042       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
01043     }
01044   }
01045 
01046   // Check that super class name is valid class name
01047   ObjCInterfaceDecl *SDecl = nullptr;
01048   if (SuperClassname) {
01049     // Check if a different kind of symbol declared in this scope.
01050     PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
01051                                 LookupOrdinaryName);
01052     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
01053       Diag(SuperClassLoc, diag::err_redefinition_different_kind)
01054         << SuperClassname;
01055       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
01056     } else {
01057       SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
01058       if (SDecl && !SDecl->hasDefinition())
01059         SDecl = nullptr;
01060       if (!SDecl)
01061         Diag(SuperClassLoc, diag::err_undef_superclass)
01062           << SuperClassname << ClassName;
01063       else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
01064         // This implementation and its interface do not have the same
01065         // super class.
01066         Diag(SuperClassLoc, diag::err_conflicting_super_class)
01067           << SDecl->getDeclName();
01068         Diag(SDecl->getLocation(), diag::note_previous_definition);
01069       }
01070     }
01071   }
01072 
01073   if (!IDecl) {
01074     // Legacy case of @implementation with no corresponding @interface.
01075     // Build, chain & install the interface decl into the identifier.
01076 
01077     // FIXME: Do we support attributes on the @implementation? If so we should
01078     // copy them over.
01079     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
01080                                       ClassName, /*PrevDecl=*/nullptr, ClassLoc,
01081                                       true);
01082     IDecl->startDefinition();
01083     if (SDecl) {
01084       IDecl->setSuperClass(SDecl);
01085       IDecl->setSuperClassLoc(SuperClassLoc);
01086       IDecl->setEndOfDefinitionLoc(SuperClassLoc);
01087     } else {
01088       IDecl->setEndOfDefinitionLoc(ClassLoc);
01089     }
01090     
01091     PushOnScopeChains(IDecl, TUScope);
01092   } else {
01093     // Mark the interface as being completed, even if it was just as
01094     //   @class ....;
01095     // declaration; the user cannot reopen it.
01096     if (!IDecl->hasDefinition())
01097       IDecl->startDefinition();
01098   }
01099 
01100   ObjCImplementationDecl* IMPDecl =
01101     ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
01102                                    ClassLoc, AtClassImplLoc, SuperClassLoc);
01103 
01104   if (CheckObjCDeclScope(IMPDecl))
01105     return ActOnObjCContainerStartDefinition(IMPDecl);
01106 
01107   // Check that there is no duplicate implementation of this class.
01108   if (IDecl->getImplementation()) {
01109     // FIXME: Don't leak everything!
01110     Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
01111     Diag(IDecl->getImplementation()->getLocation(),
01112          diag::note_previous_definition);
01113     IMPDecl->setInvalidDecl();
01114   } else { // add it to the list.
01115     IDecl->setImplementation(IMPDecl);
01116     PushOnScopeChains(IMPDecl, TUScope);
01117     // Warn on implementating deprecated class under 
01118     // -Wdeprecated-implementations flag.
01119     DiagnoseObjCImplementedDeprecations(*this, 
01120                                         dyn_cast<NamedDecl>(IDecl), 
01121                                         IMPDecl->getLocation(), 1);
01122   }
01123   return ActOnObjCContainerStartDefinition(IMPDecl);
01124 }
01125 
01126 Sema::DeclGroupPtrTy
01127 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
01128   SmallVector<Decl *, 64> DeclsInGroup;
01129   DeclsInGroup.reserve(Decls.size() + 1);
01130 
01131   for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
01132     Decl *Dcl = Decls[i];
01133     if (!Dcl)
01134       continue;
01135     if (Dcl->getDeclContext()->isFileContext())
01136       Dcl->setTopLevelDeclInObjCContainer();
01137     DeclsInGroup.push_back(Dcl);
01138   }
01139 
01140   DeclsInGroup.push_back(ObjCImpDecl);
01141 
01142   return BuildDeclaratorGroup(DeclsInGroup, false);
01143 }
01144 
01145 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
01146                                     ObjCIvarDecl **ivars, unsigned numIvars,
01147                                     SourceLocation RBrace) {
01148   assert(ImpDecl && "missing implementation decl");
01149   ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
01150   if (!IDecl)
01151     return;
01152   /// Check case of non-existing \@interface decl.
01153   /// (legacy objective-c \@implementation decl without an \@interface decl).
01154   /// Add implementations's ivar to the synthesize class's ivar list.
01155   if (IDecl->isImplicitInterfaceDecl()) {
01156     IDecl->setEndOfDefinitionLoc(RBrace);
01157     // Add ivar's to class's DeclContext.
01158     for (unsigned i = 0, e = numIvars; i != e; ++i) {
01159       ivars[i]->setLexicalDeclContext(ImpDecl);
01160       IDecl->makeDeclVisibleInContext(ivars[i]);
01161       ImpDecl->addDecl(ivars[i]);
01162     }
01163     
01164     return;
01165   }
01166   // If implementation has empty ivar list, just return.
01167   if (numIvars == 0)
01168     return;
01169 
01170   assert(ivars && "missing @implementation ivars");
01171   if (LangOpts.ObjCRuntime.isNonFragile()) {
01172     if (ImpDecl->getSuperClass())
01173       Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
01174     for (unsigned i = 0; i < numIvars; i++) {
01175       ObjCIvarDecl* ImplIvar = ivars[i];
01176       if (const ObjCIvarDecl *ClsIvar = 
01177             IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
01178         Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 
01179         Diag(ClsIvar->getLocation(), diag::note_previous_definition);
01180         continue;
01181       }
01182       // Check class extensions (unnamed categories) for duplicate ivars.
01183       for (const auto *CDecl : IDecl->visible_extensions()) {
01184         if (const ObjCIvarDecl *ClsExtIvar = 
01185             CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
01186           Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration); 
01187           Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
01188           continue;
01189         }
01190       }
01191       // Instance ivar to Implementation's DeclContext.
01192       ImplIvar->setLexicalDeclContext(ImpDecl);
01193       IDecl->makeDeclVisibleInContext(ImplIvar);
01194       ImpDecl->addDecl(ImplIvar);
01195     }
01196     return;
01197   }
01198   // Check interface's Ivar list against those in the implementation.
01199   // names and types must match.
01200   //
01201   unsigned j = 0;
01202   ObjCInterfaceDecl::ivar_iterator
01203     IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
01204   for (; numIvars > 0 && IVI != IVE; ++IVI) {
01205     ObjCIvarDecl* ImplIvar = ivars[j++];
01206     ObjCIvarDecl* ClsIvar = *IVI;
01207     assert (ImplIvar && "missing implementation ivar");
01208     assert (ClsIvar && "missing class ivar");
01209 
01210     // First, make sure the types match.
01211     if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
01212       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
01213         << ImplIvar->getIdentifier()
01214         << ImplIvar->getType() << ClsIvar->getType();
01215       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
01216     } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
01217                ImplIvar->getBitWidthValue(Context) !=
01218                ClsIvar->getBitWidthValue(Context)) {
01219       Diag(ImplIvar->getBitWidth()->getLocStart(),
01220            diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
01221       Diag(ClsIvar->getBitWidth()->getLocStart(),
01222            diag::note_previous_definition);
01223     }
01224     // Make sure the names are identical.
01225     if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
01226       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
01227         << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
01228       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
01229     }
01230     --numIvars;
01231   }
01232 
01233   if (numIvars > 0)
01234     Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
01235   else if (IVI != IVE)
01236     Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
01237 }
01238 
01239 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
01240                                 ObjCMethodDecl *method,
01241                                 bool &IncompleteImpl,
01242                                 unsigned DiagID,
01243                                 NamedDecl *NeededFor = nullptr) {
01244   // No point warning no definition of method which is 'unavailable'.
01245   switch (method->getAvailability()) {
01246   case AR_Available:
01247   case AR_Deprecated:
01248     break;
01249 
01250       // Don't warn about unavailable or not-yet-introduced methods.
01251   case AR_NotYetIntroduced:
01252   case AR_Unavailable:
01253     return;
01254   }
01255   
01256   // FIXME: For now ignore 'IncompleteImpl'.
01257   // Previously we grouped all unimplemented methods under a single
01258   // warning, but some users strongly voiced that they would prefer
01259   // separate warnings.  We will give that approach a try, as that
01260   // matches what we do with protocols.
01261   {
01262     const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
01263     B << method;
01264     if (NeededFor)
01265       B << NeededFor;
01266   }
01267 
01268   // Issue a note to the original declaration.
01269   SourceLocation MethodLoc = method->getLocStart();
01270   if (MethodLoc.isValid())
01271     S.Diag(MethodLoc, diag::note_method_declared_at) << method;
01272 }
01273 
01274 /// Determines if type B can be substituted for type A.  Returns true if we can
01275 /// guarantee that anything that the user will do to an object of type A can 
01276 /// also be done to an object of type B.  This is trivially true if the two 
01277 /// types are the same, or if B is a subclass of A.  It becomes more complex
01278 /// in cases where protocols are involved.
01279 ///
01280 /// Object types in Objective-C describe the minimum requirements for an
01281 /// object, rather than providing a complete description of a type.  For
01282 /// example, if A is a subclass of B, then B* may refer to an instance of A.
01283 /// The principle of substitutability means that we may use an instance of A
01284 /// anywhere that we may use an instance of B - it will implement all of the
01285 /// ivars of B and all of the methods of B.  
01286 ///
01287 /// This substitutability is important when type checking methods, because 
01288 /// the implementation may have stricter type definitions than the interface.
01289 /// The interface specifies minimum requirements, but the implementation may
01290 /// have more accurate ones.  For example, a method may privately accept 
01291 /// instances of B, but only publish that it accepts instances of A.  Any
01292 /// object passed to it will be type checked against B, and so will implicitly
01293 /// by a valid A*.  Similarly, a method may return a subclass of the class that
01294 /// it is declared as returning.
01295 ///
01296 /// This is most important when considering subclassing.  A method in a
01297 /// subclass must accept any object as an argument that its superclass's
01298 /// implementation accepts.  It may, however, accept a more general type
01299 /// without breaking substitutability (i.e. you can still use the subclass
01300 /// anywhere that you can use the superclass, but not vice versa).  The
01301 /// converse requirement applies to return types: the return type for a
01302 /// subclass method must be a valid object of the kind that the superclass
01303 /// advertises, but it may be specified more accurately.  This avoids the need
01304 /// for explicit down-casting by callers.
01305 ///
01306 /// Note: This is a stricter requirement than for assignment.  
01307 static bool isObjCTypeSubstitutable(ASTContext &Context,
01308                                     const ObjCObjectPointerType *A,
01309                                     const ObjCObjectPointerType *B,
01310                                     bool rejectId) {
01311   // Reject a protocol-unqualified id.
01312   if (rejectId && B->isObjCIdType()) return false;
01313 
01314   // If B is a qualified id, then A must also be a qualified id and it must
01315   // implement all of the protocols in B.  It may not be a qualified class.
01316   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
01317   // stricter definition so it is not substitutable for id<A>.
01318   if (B->isObjCQualifiedIdType()) {
01319     return A->isObjCQualifiedIdType() &&
01320            Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
01321                                                      QualType(B,0),
01322                                                      false);
01323   }
01324 
01325   /*
01326   // id is a special type that bypasses type checking completely.  We want a
01327   // warning when it is used in one place but not another.
01328   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
01329 
01330 
01331   // If B is a qualified id, then A must also be a qualified id (which it isn't
01332   // if we've got this far)
01333   if (B->isObjCQualifiedIdType()) return false;
01334   */
01335 
01336   // Now we know that A and B are (potentially-qualified) class types.  The
01337   // normal rules for assignment apply.
01338   return Context.canAssignObjCInterfaces(A, B);
01339 }
01340 
01341 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
01342   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
01343 }
01344 
01345 static bool CheckMethodOverrideReturn(Sema &S,
01346                                       ObjCMethodDecl *MethodImpl,
01347                                       ObjCMethodDecl *MethodDecl,
01348                                       bool IsProtocolMethodDecl,
01349                                       bool IsOverridingMode,
01350                                       bool Warn) {
01351   if (IsProtocolMethodDecl &&
01352       (MethodDecl->getObjCDeclQualifier() !=
01353        MethodImpl->getObjCDeclQualifier())) {
01354     if (Warn) {
01355       S.Diag(MethodImpl->getLocation(),
01356              (IsOverridingMode
01357                   ? diag::warn_conflicting_overriding_ret_type_modifiers
01358                   : diag::warn_conflicting_ret_type_modifiers))
01359           << MethodImpl->getDeclName()
01360           << MethodImpl->getReturnTypeSourceRange();
01361       S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
01362           << MethodDecl->getReturnTypeSourceRange();
01363     }
01364     else
01365       return false;
01366   }
01367 
01368   if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
01369                                        MethodDecl->getReturnType()))
01370     return true;
01371   if (!Warn)
01372     return false;
01373 
01374   unsigned DiagID = 
01375     IsOverridingMode ? diag::warn_conflicting_overriding_ret_types 
01376                      : diag::warn_conflicting_ret_types;
01377 
01378   // Mismatches between ObjC pointers go into a different warning
01379   // category, and sometimes they're even completely whitelisted.
01380   if (const ObjCObjectPointerType *ImplPtrTy =
01381           MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
01382     if (const ObjCObjectPointerType *IfacePtrTy =
01383             MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
01384       // Allow non-matching return types as long as they don't violate
01385       // the principle of substitutability.  Specifically, we permit
01386       // return types that are subclasses of the declared return type,
01387       // or that are more-qualified versions of the declared type.
01388       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
01389         return false;
01390 
01391       DiagID = 
01392         IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types 
01393                           : diag::warn_non_covariant_ret_types;
01394     }
01395   }
01396 
01397   S.Diag(MethodImpl->getLocation(), DiagID)
01398       << MethodImpl->getDeclName() << MethodDecl->getReturnType()
01399       << MethodImpl->getReturnType()
01400       << MethodImpl->getReturnTypeSourceRange();
01401   S.Diag(MethodDecl->getLocation(), IsOverridingMode
01402                                         ? diag::note_previous_declaration
01403                                         : diag::note_previous_definition)
01404       << MethodDecl->getReturnTypeSourceRange();
01405   return false;
01406 }
01407 
01408 static bool CheckMethodOverrideParam(Sema &S,
01409                                      ObjCMethodDecl *MethodImpl,
01410                                      ObjCMethodDecl *MethodDecl,
01411                                      ParmVarDecl *ImplVar,
01412                                      ParmVarDecl *IfaceVar,
01413                                      bool IsProtocolMethodDecl,
01414                                      bool IsOverridingMode,
01415                                      bool Warn) {
01416   if (IsProtocolMethodDecl &&
01417       (ImplVar->getObjCDeclQualifier() !=
01418        IfaceVar->getObjCDeclQualifier())) {
01419     if (Warn) {
01420       if (IsOverridingMode)
01421         S.Diag(ImplVar->getLocation(), 
01422                diag::warn_conflicting_overriding_param_modifiers)
01423             << getTypeRange(ImplVar->getTypeSourceInfo())
01424             << MethodImpl->getDeclName();
01425       else S.Diag(ImplVar->getLocation(), 
01426              diag::warn_conflicting_param_modifiers)
01427           << getTypeRange(ImplVar->getTypeSourceInfo())
01428           << MethodImpl->getDeclName();
01429       S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
01430           << getTypeRange(IfaceVar->getTypeSourceInfo());   
01431     }
01432     else
01433       return false;
01434   }
01435       
01436   QualType ImplTy = ImplVar->getType();
01437   QualType IfaceTy = IfaceVar->getType();
01438   
01439   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
01440     return true;
01441   
01442   if (!Warn)
01443     return false;
01444   unsigned DiagID = 
01445     IsOverridingMode ? diag::warn_conflicting_overriding_param_types 
01446                      : diag::warn_conflicting_param_types;
01447 
01448   // Mismatches between ObjC pointers go into a different warning
01449   // category, and sometimes they're even completely whitelisted.
01450   if (const ObjCObjectPointerType *ImplPtrTy =
01451         ImplTy->getAs<ObjCObjectPointerType>()) {
01452     if (const ObjCObjectPointerType *IfacePtrTy =
01453           IfaceTy->getAs<ObjCObjectPointerType>()) {
01454       // Allow non-matching argument types as long as they don't
01455       // violate the principle of substitutability.  Specifically, the
01456       // implementation must accept any objects that the superclass
01457       // accepts, however it may also accept others.
01458       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
01459         return false;
01460 
01461       DiagID = 
01462       IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types 
01463                        :  diag::warn_non_contravariant_param_types;
01464     }
01465   }
01466 
01467   S.Diag(ImplVar->getLocation(), DiagID)
01468     << getTypeRange(ImplVar->getTypeSourceInfo())
01469     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
01470   S.Diag(IfaceVar->getLocation(), 
01471          (IsOverridingMode ? diag::note_previous_declaration 
01472                         : diag::note_previous_definition))
01473     << getTypeRange(IfaceVar->getTypeSourceInfo());
01474   return false;
01475 }
01476 
01477 /// In ARC, check whether the conventional meanings of the two methods
01478 /// match.  If they don't, it's a hard error.
01479 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
01480                                       ObjCMethodDecl *decl) {
01481   ObjCMethodFamily implFamily = impl->getMethodFamily();
01482   ObjCMethodFamily declFamily = decl->getMethodFamily();
01483   if (implFamily == declFamily) return false;
01484 
01485   // Since conventions are sorted by selector, the only possibility is
01486   // that the types differ enough to cause one selector or the other
01487   // to fall out of the family.
01488   assert(implFamily == OMF_None || declFamily == OMF_None);
01489 
01490   // No further diagnostics required on invalid declarations.
01491   if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
01492 
01493   const ObjCMethodDecl *unmatched = impl;
01494   ObjCMethodFamily family = declFamily;
01495   unsigned errorID = diag::err_arc_lost_method_convention;
01496   unsigned noteID = diag::note_arc_lost_method_convention;
01497   if (declFamily == OMF_None) {
01498     unmatched = decl;
01499     family = implFamily;
01500     errorID = diag::err_arc_gained_method_convention;
01501     noteID = diag::note_arc_gained_method_convention;
01502   }
01503 
01504   // Indexes into a %select clause in the diagnostic.
01505   enum FamilySelector {
01506     F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
01507   };
01508   FamilySelector familySelector = FamilySelector();
01509 
01510   switch (family) {
01511   case OMF_None: llvm_unreachable("logic error, no method convention");
01512   case OMF_retain:
01513   case OMF_release:
01514   case OMF_autorelease:
01515   case OMF_dealloc:
01516   case OMF_finalize:
01517   case OMF_retainCount:
01518   case OMF_self:
01519   case OMF_initialize:
01520   case OMF_performSelector:
01521     // Mismatches for these methods don't change ownership
01522     // conventions, so we don't care.
01523     return false;
01524 
01525   case OMF_init: familySelector = F_init; break;
01526   case OMF_alloc: familySelector = F_alloc; break;
01527   case OMF_copy: familySelector = F_copy; break;
01528   case OMF_mutableCopy: familySelector = F_mutableCopy; break;
01529   case OMF_new: familySelector = F_new; break;
01530   }
01531 
01532   enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
01533   ReasonSelector reasonSelector;
01534 
01535   // The only reason these methods don't fall within their families is
01536   // due to unusual result types.
01537   if (unmatched->getReturnType()->isObjCObjectPointerType()) {
01538     reasonSelector = R_UnrelatedReturn;
01539   } else {
01540     reasonSelector = R_NonObjectReturn;
01541   }
01542 
01543   S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
01544   S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
01545 
01546   return true;
01547 }
01548 
01549 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
01550                                        ObjCMethodDecl *MethodDecl,
01551                                        bool IsProtocolMethodDecl) {
01552   if (getLangOpts().ObjCAutoRefCount &&
01553       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
01554     return;
01555 
01556   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 
01557                             IsProtocolMethodDecl, false, 
01558                             true);
01559 
01560   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
01561        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
01562        EF = MethodDecl->param_end();
01563        IM != EM && IF != EF; ++IM, ++IF) {
01564     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
01565                              IsProtocolMethodDecl, false, true);
01566   }
01567 
01568   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
01569     Diag(ImpMethodDecl->getLocation(), 
01570          diag::warn_conflicting_variadic);
01571     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
01572   }
01573 }
01574 
01575 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
01576                                        ObjCMethodDecl *Overridden,
01577                                        bool IsProtocolMethodDecl) {
01578   
01579   CheckMethodOverrideReturn(*this, Method, Overridden, 
01580                             IsProtocolMethodDecl, true, 
01581                             true);
01582   
01583   for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
01584        IF = Overridden->param_begin(), EM = Method->param_end(),
01585        EF = Overridden->param_end();
01586        IM != EM && IF != EF; ++IM, ++IF) {
01587     CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
01588                              IsProtocolMethodDecl, true, true);
01589   }
01590   
01591   if (Method->isVariadic() != Overridden->isVariadic()) {
01592     Diag(Method->getLocation(), 
01593          diag::warn_conflicting_overriding_variadic);
01594     Diag(Overridden->getLocation(), diag::note_previous_declaration);
01595   }
01596 }
01597 
01598 /// WarnExactTypedMethods - This routine issues a warning if method
01599 /// implementation declaration matches exactly that of its declaration.
01600 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
01601                                  ObjCMethodDecl *MethodDecl,
01602                                  bool IsProtocolMethodDecl) {
01603   // don't issue warning when protocol method is optional because primary
01604   // class is not required to implement it and it is safe for protocol
01605   // to implement it.
01606   if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
01607     return;
01608   // don't issue warning when primary class's method is 
01609   // depecated/unavailable.
01610   if (MethodDecl->hasAttr<UnavailableAttr>() ||
01611       MethodDecl->hasAttr<DeprecatedAttr>())
01612     return;
01613   
01614   bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl, 
01615                                       IsProtocolMethodDecl, false, false);
01616   if (match)
01617     for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
01618          IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
01619          EF = MethodDecl->param_end();
01620          IM != EM && IF != EF; ++IM, ++IF) {
01621       match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, 
01622                                        *IM, *IF,
01623                                        IsProtocolMethodDecl, false, false);
01624       if (!match)
01625         break;
01626     }
01627   if (match)
01628     match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
01629   if (match)
01630     match = !(MethodDecl->isClassMethod() &&
01631               MethodDecl->getSelector() == GetNullarySelector("load", Context));
01632   
01633   if (match) {
01634     Diag(ImpMethodDecl->getLocation(), 
01635          diag::warn_category_method_impl_match);
01636     Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
01637       << MethodDecl->getDeclName();
01638   }
01639 }
01640 
01641 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
01642 /// improve the efficiency of selector lookups and type checking by associating
01643 /// with each protocol / interface / category the flattened instance tables. If
01644 /// we used an immutable set to keep the table then it wouldn't add significant
01645 /// memory cost and it would be handy for lookups.
01646 
01647 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
01648 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
01649 
01650 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
01651                                            ProtocolNameSet &PNS) {
01652   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
01653     PNS.insert(PDecl->getIdentifier());
01654   for (const auto *PI : PDecl->protocols())
01655     findProtocolsWithExplicitImpls(PI, PNS);
01656 }
01657 
01658 /// Recursively populates a set with all conformed protocols in a class
01659 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
01660 /// attribute.
01661 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
01662                                            ProtocolNameSet &PNS) {
01663   if (!Super)
01664     return;
01665 
01666   for (const auto *I : Super->all_referenced_protocols())
01667     findProtocolsWithExplicitImpls(I, PNS);
01668 
01669   findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
01670 }
01671 
01672 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
01673 /// Declared in protocol, and those referenced by it.
01674 static void CheckProtocolMethodDefs(Sema &S,
01675                                     SourceLocation ImpLoc,
01676                                     ObjCProtocolDecl *PDecl,
01677                                     bool& IncompleteImpl,
01678                                     const Sema::SelectorSet &InsMap,
01679                                     const Sema::SelectorSet &ClsMap,
01680                                     ObjCContainerDecl *CDecl,
01681                                     LazyProtocolNameSet &ProtocolsExplictImpl) {
01682   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
01683   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface() 
01684                                : dyn_cast<ObjCInterfaceDecl>(CDecl);
01685   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
01686   
01687   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
01688   ObjCInterfaceDecl *NSIDecl = nullptr;
01689 
01690   // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
01691   // then we should check if any class in the super class hierarchy also
01692   // conforms to this protocol, either directly or via protocol inheritance.
01693   // If so, we can skip checking this protocol completely because we
01694   // know that a parent class already satisfies this protocol.
01695   //
01696   // Note: we could generalize this logic for all protocols, and merely
01697   // add the limit on looking at the super class chain for just
01698   // specially marked protocols.  This may be a good optimization.  This
01699   // change is restricted to 'objc_protocol_requires_explicit_implementation'
01700   // protocols for now for controlled evaluation.
01701   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
01702     if (!ProtocolsExplictImpl) {
01703       ProtocolsExplictImpl.reset(new ProtocolNameSet);
01704       findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
01705     }
01706     if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
01707         ProtocolsExplictImpl->end())
01708       return;
01709 
01710     // If no super class conforms to the protocol, we should not search
01711     // for methods in the super class to implicitly satisfy the protocol.
01712     Super = nullptr;
01713   }
01714 
01715   if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
01716     // check to see if class implements forwardInvocation method and objects
01717     // of this class are derived from 'NSProxy' so that to forward requests
01718     // from one object to another.
01719     // Under such conditions, which means that every method possible is
01720     // implemented in the class, we should not issue "Method definition not
01721     // found" warnings.
01722     // FIXME: Use a general GetUnarySelector method for this.
01723     IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
01724     Selector fISelector = S.Context.Selectors.getSelector(1, &II);
01725     if (InsMap.count(fISelector))
01726       // Is IDecl derived from 'NSProxy'? If so, no instance methods
01727       // need be implemented in the implementation.
01728       NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
01729   }
01730 
01731   // If this is a forward protocol declaration, get its definition.
01732   if (!PDecl->isThisDeclarationADefinition() &&
01733       PDecl->getDefinition())
01734     PDecl = PDecl->getDefinition();
01735   
01736   // If a method lookup fails locally we still need to look and see if
01737   // the method was implemented by a base class or an inherited
01738   // protocol. This lookup is slow, but occurs rarely in correct code
01739   // and otherwise would terminate in a warning.
01740 
01741   // check unimplemented instance methods.
01742   if (!NSIDecl)
01743     for (auto *method : PDecl->instance_methods()) {
01744       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
01745           !method->isPropertyAccessor() &&
01746           !InsMap.count(method->getSelector()) &&
01747           (!Super || !Super->lookupMethod(method->getSelector(),
01748                                           true /* instance */,
01749                                           false /* shallowCategory */,
01750                                           true /* followsSuper */,
01751                                           nullptr /* category */))) {
01752             // If a method is not implemented in the category implementation but
01753             // has been declared in its primary class, superclass,
01754             // or in one of their protocols, no need to issue the warning. 
01755             // This is because method will be implemented in the primary class 
01756             // or one of its super class implementation.
01757             
01758             // Ugly, but necessary. Method declared in protcol might have
01759             // have been synthesized due to a property declared in the class which
01760             // uses the protocol.
01761             if (ObjCMethodDecl *MethodInClass =
01762                   IDecl->lookupMethod(method->getSelector(),
01763                                       true /* instance */,
01764                                       true /* shallowCategoryLookup */,
01765                                       false /* followSuper */))
01766               if (C || MethodInClass->isPropertyAccessor())
01767                 continue;
01768             unsigned DIAG = diag::warn_unimplemented_protocol_method;
01769             if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
01770               WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
01771                                   PDecl);
01772             }
01773           }
01774     }
01775   // check unimplemented class methods
01776   for (auto *method : PDecl->class_methods()) {
01777     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
01778         !ClsMap.count(method->getSelector()) &&
01779         (!Super || !Super->lookupMethod(method->getSelector(),
01780                                         false /* class method */,
01781                                         false /* shallowCategoryLookup */,
01782                                         true  /* followSuper */,
01783                                         nullptr /* category */))) {
01784       // See above comment for instance method lookups.
01785       if (C && IDecl->lookupMethod(method->getSelector(),
01786                                    false /* class */,
01787                                    true /* shallowCategoryLookup */,
01788                                    false /* followSuper */))
01789         continue;
01790 
01791       unsigned DIAG = diag::warn_unimplemented_protocol_method;
01792       if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
01793         WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
01794       }
01795     }
01796   }
01797   // Check on this protocols's referenced protocols, recursively.
01798   for (auto *PI : PDecl->protocols())
01799     CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
01800                             CDecl, ProtocolsExplictImpl);
01801 }
01802 
01803 /// MatchAllMethodDeclarations - Check methods declared in interface
01804 /// or protocol against those declared in their implementations.
01805 ///
01806 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
01807                                       const SelectorSet &ClsMap,
01808                                       SelectorSet &InsMapSeen,
01809                                       SelectorSet &ClsMapSeen,
01810                                       ObjCImplDecl* IMPDecl,
01811                                       ObjCContainerDecl* CDecl,
01812                                       bool &IncompleteImpl,
01813                                       bool ImmediateClass,
01814                                       bool WarnCategoryMethodImpl) {
01815   // Check and see if instance methods in class interface have been
01816   // implemented in the implementation class. If so, their types match.
01817   for (auto *I : CDecl->instance_methods()) {
01818     if (!InsMapSeen.insert(I->getSelector()))
01819       continue;
01820     if (!I->isPropertyAccessor() &&
01821         !InsMap.count(I->getSelector())) {
01822       if (ImmediateClass)
01823         WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
01824                             diag::warn_undef_method_impl);
01825       continue;
01826     } else {
01827       ObjCMethodDecl *ImpMethodDecl =
01828         IMPDecl->getInstanceMethod(I->getSelector());
01829       assert(CDecl->getInstanceMethod(I->getSelector()) &&
01830              "Expected to find the method through lookup as well");
01831       // ImpMethodDecl may be null as in a @dynamic property.
01832       if (ImpMethodDecl) {
01833         if (!WarnCategoryMethodImpl)
01834           WarnConflictingTypedMethods(ImpMethodDecl, I,
01835                                       isa<ObjCProtocolDecl>(CDecl));
01836         else if (!I->isPropertyAccessor())
01837           WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
01838       }
01839     }
01840   }
01841 
01842   // Check and see if class methods in class interface have been
01843   // implemented in the implementation class. If so, their types match.
01844   for (auto *I : CDecl->class_methods()) {
01845     if (!ClsMapSeen.insert(I->getSelector()))
01846       continue;
01847     if (!ClsMap.count(I->getSelector())) {
01848       if (ImmediateClass)
01849         WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
01850                             diag::warn_undef_method_impl);
01851     } else {
01852       ObjCMethodDecl *ImpMethodDecl =
01853         IMPDecl->getClassMethod(I->getSelector());
01854       assert(CDecl->getClassMethod(I->getSelector()) &&
01855              "Expected to find the method through lookup as well");
01856       if (!WarnCategoryMethodImpl)
01857         WarnConflictingTypedMethods(ImpMethodDecl, I, 
01858                                     isa<ObjCProtocolDecl>(CDecl));
01859       else
01860         WarnExactTypedMethods(ImpMethodDecl, I,
01861                               isa<ObjCProtocolDecl>(CDecl));
01862     }
01863   }
01864   
01865   if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
01866     // Also, check for methods declared in protocols inherited by
01867     // this protocol.
01868     for (auto *PI : PD->protocols())
01869       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01870                                  IMPDecl, PI, IncompleteImpl, false,
01871                                  WarnCategoryMethodImpl);
01872   }
01873   
01874   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
01875     // when checking that methods in implementation match their declaration,
01876     // i.e. when WarnCategoryMethodImpl is false, check declarations in class
01877     // extension; as well as those in categories.
01878     if (!WarnCategoryMethodImpl) {
01879       for (auto *Cat : I->visible_categories())
01880         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01881                                    IMPDecl, Cat, IncompleteImpl, false,
01882                                    WarnCategoryMethodImpl);
01883     } else {
01884       // Also methods in class extensions need be looked at next.
01885       for (auto *Ext : I->visible_extensions())
01886         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01887                                    IMPDecl, Ext, IncompleteImpl, false,
01888                                    WarnCategoryMethodImpl);
01889     }
01890 
01891     // Check for any implementation of a methods declared in protocol.
01892     for (auto *PI : I->all_referenced_protocols())
01893       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01894                                  IMPDecl, PI, IncompleteImpl, false,
01895                                  WarnCategoryMethodImpl);
01896 
01897     // FIXME. For now, we are not checking for extact match of methods 
01898     // in category implementation and its primary class's super class. 
01899     if (!WarnCategoryMethodImpl && I->getSuperClass())
01900       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01901                                  IMPDecl,
01902                                  I->getSuperClass(), IncompleteImpl, false);
01903   }
01904 }
01905 
01906 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
01907 /// category matches with those implemented in its primary class and
01908 /// warns each time an exact match is found. 
01909 void Sema::CheckCategoryVsClassMethodMatches(
01910                                   ObjCCategoryImplDecl *CatIMPDecl) {
01911   // Get category's primary class.
01912   ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
01913   if (!CatDecl)
01914     return;
01915   ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
01916   if (!IDecl)
01917     return;
01918   ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
01919   SelectorSet InsMap, ClsMap;
01920   
01921   for (const auto *I : CatIMPDecl->instance_methods()) {
01922     Selector Sel = I->getSelector();
01923     // When checking for methods implemented in the category, skip over
01924     // those declared in category class's super class. This is because
01925     // the super class must implement the method.
01926     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
01927       continue;
01928     InsMap.insert(Sel);
01929   }
01930   
01931   for (const auto *I : CatIMPDecl->class_methods()) {
01932     Selector Sel = I->getSelector();
01933     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
01934       continue;
01935     ClsMap.insert(Sel);
01936   }
01937   if (InsMap.empty() && ClsMap.empty())
01938     return;
01939   
01940   SelectorSet InsMapSeen, ClsMapSeen;
01941   bool IncompleteImpl = false;
01942   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01943                              CatIMPDecl, IDecl,
01944                              IncompleteImpl, false, 
01945                              true /*WarnCategoryMethodImpl*/);
01946 }
01947 
01948 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
01949                                      ObjCContainerDecl* CDecl,
01950                                      bool IncompleteImpl) {
01951   SelectorSet InsMap;
01952   // Check and see if instance methods in class interface have been
01953   // implemented in the implementation class.
01954   for (const auto *I : IMPDecl->instance_methods())
01955     InsMap.insert(I->getSelector());
01956 
01957   // Check and see if properties declared in the interface have either 1)
01958   // an implementation or 2) there is a @synthesize/@dynamic implementation
01959   // of the property in the @implementation.
01960   if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
01961     bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
01962                                 LangOpts.ObjCRuntime.isNonFragile() &&
01963                                 !IDecl->isObjCRequiresPropertyDefs();
01964     DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
01965   }
01966 
01967   SelectorSet ClsMap;
01968   for (const auto *I : IMPDecl->class_methods())
01969     ClsMap.insert(I->getSelector());
01970 
01971   // Check for type conflict of methods declared in a class/protocol and
01972   // its implementation; if any.
01973   SelectorSet InsMapSeen, ClsMapSeen;
01974   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
01975                              IMPDecl, CDecl,
01976                              IncompleteImpl, true);
01977   
01978   // check all methods implemented in category against those declared
01979   // in its primary class.
01980   if (ObjCCategoryImplDecl *CatDecl = 
01981         dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
01982     CheckCategoryVsClassMethodMatches(CatDecl);
01983 
01984   // Check the protocol list for unimplemented methods in the @implementation
01985   // class.
01986   // Check and see if class methods in class interface have been
01987   // implemented in the implementation class.
01988 
01989   LazyProtocolNameSet ExplicitImplProtocols;
01990 
01991   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
01992     for (auto *PI : I->all_referenced_protocols())
01993       CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
01994                               InsMap, ClsMap, I, ExplicitImplProtocols);
01995     // Check class extensions (unnamed categories)
01996     for (auto *Ext : I->visible_extensions())
01997       ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
01998   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
01999     // For extended class, unimplemented methods in its protocols will
02000     // be reported in the primary class.
02001     if (!C->IsClassExtension()) {
02002       for (auto *P : C->protocols())
02003         CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
02004                                 IncompleteImpl, InsMap, ClsMap, CDecl,
02005                                 ExplicitImplProtocols);
02006       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
02007                                       /* SynthesizeProperties */ false);
02008     } 
02009   } else
02010     llvm_unreachable("invalid ObjCContainerDecl type.");
02011 }
02012 
02013 /// ActOnForwardClassDeclaration -
02014 Sema::DeclGroupPtrTy
02015 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
02016                                    IdentifierInfo **IdentList,
02017                                    SourceLocation *IdentLocs,
02018                                    unsigned NumElts) {
02019   SmallVector<Decl *, 8> DeclsInGroup;
02020   for (unsigned i = 0; i != NumElts; ++i) {
02021     // Check for another declaration kind with the same name.
02022     NamedDecl *PrevDecl
02023       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i], 
02024                          LookupOrdinaryName, ForRedeclaration);
02025     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
02026       // GCC apparently allows the following idiom:
02027       //
02028       // typedef NSObject < XCElementTogglerP > XCElementToggler;
02029       // @class XCElementToggler;
02030       //
02031       // Here we have chosen to ignore the forward class declaration
02032       // with a warning. Since this is the implied behavior.
02033       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
02034       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
02035         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
02036         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
02037       } else {
02038         // a forward class declaration matching a typedef name of a class refers
02039         // to the underlying class. Just ignore the forward class with a warning
02040         // as this will force the intended behavior which is to lookup the typedef
02041         // name.
02042         if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
02043           Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
02044           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
02045           continue;
02046         }
02047       }
02048     }
02049     
02050     // Create a declaration to describe this forward declaration.
02051     ObjCInterfaceDecl *PrevIDecl
02052       = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
02053 
02054     IdentifierInfo *ClassName = IdentList[i];
02055     if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
02056       // A previous decl with a different name is because of
02057       // @compatibility_alias, for example:
02058       // \code
02059       //   @class NewImage;
02060       //   @compatibility_alias OldImage NewImage;
02061       // \endcode
02062       // A lookup for 'OldImage' will return the 'NewImage' decl.
02063       //
02064       // In such a case use the real declaration name, instead of the alias one,
02065       // otherwise we will break IdentifierResolver and redecls-chain invariants.
02066       // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
02067       // has been aliased.
02068       ClassName = PrevIDecl->getIdentifier();
02069     }
02070 
02071     ObjCInterfaceDecl *IDecl
02072       = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
02073                                   ClassName, PrevIDecl, IdentLocs[i]);
02074     IDecl->setAtEndRange(IdentLocs[i]);
02075     
02076     PushOnScopeChains(IDecl, TUScope);
02077     CheckObjCDeclScope(IDecl);
02078     DeclsInGroup.push_back(IDecl);
02079   }
02080 
02081   return BuildDeclaratorGroup(DeclsInGroup, false);
02082 }
02083 
02084 static bool tryMatchRecordTypes(ASTContext &Context,
02085                                 Sema::MethodMatchStrategy strategy,
02086                                 const Type *left, const Type *right);
02087 
02088 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
02089                        QualType leftQT, QualType rightQT) {
02090   const Type *left =
02091     Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
02092   const Type *right =
02093     Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
02094 
02095   if (left == right) return true;
02096 
02097   // If we're doing a strict match, the types have to match exactly.
02098   if (strategy == Sema::MMS_strict) return false;
02099 
02100   if (left->isIncompleteType() || right->isIncompleteType()) return false;
02101 
02102   // Otherwise, use this absurdly complicated algorithm to try to
02103   // validate the basic, low-level compatibility of the two types.
02104 
02105   // As a minimum, require the sizes and alignments to match.
02106   TypeInfo LeftTI = Context.getTypeInfo(left);
02107   TypeInfo RightTI = Context.getTypeInfo(right);
02108   if (LeftTI.Width != RightTI.Width)
02109     return false;
02110 
02111   if (LeftTI.Align != RightTI.Align)
02112     return false;
02113 
02114   // Consider all the kinds of non-dependent canonical types:
02115   // - functions and arrays aren't possible as return and parameter types
02116   
02117   // - vector types of equal size can be arbitrarily mixed
02118   if (isa<VectorType>(left)) return isa<VectorType>(right);
02119   if (isa<VectorType>(right)) return false;
02120 
02121   // - references should only match references of identical type
02122   // - structs, unions, and Objective-C objects must match more-or-less
02123   //   exactly
02124   // - everything else should be a scalar
02125   if (!left->isScalarType() || !right->isScalarType())
02126     return tryMatchRecordTypes(Context, strategy, left, right);
02127 
02128   // Make scalars agree in kind, except count bools as chars, and group
02129   // all non-member pointers together.
02130   Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
02131   Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
02132   if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
02133   if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
02134   if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
02135     leftSK = Type::STK_ObjCObjectPointer;
02136   if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
02137     rightSK = Type::STK_ObjCObjectPointer;
02138 
02139   // Note that data member pointers and function member pointers don't
02140   // intermix because of the size differences.
02141 
02142   return (leftSK == rightSK);
02143 }
02144 
02145 static bool tryMatchRecordTypes(ASTContext &Context,
02146                                 Sema::MethodMatchStrategy strategy,
02147                                 const Type *lt, const Type *rt) {
02148   assert(lt && rt && lt != rt);
02149 
02150   if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
02151   RecordDecl *left = cast<RecordType>(lt)->getDecl();
02152   RecordDecl *right = cast<RecordType>(rt)->getDecl();
02153 
02154   // Require union-hood to match.
02155   if (left->isUnion() != right->isUnion()) return false;
02156 
02157   // Require an exact match if either is non-POD.
02158   if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
02159       (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
02160     return false;
02161 
02162   // Require size and alignment to match.
02163   TypeInfo LeftTI = Context.getTypeInfo(lt);
02164   TypeInfo RightTI = Context.getTypeInfo(rt);
02165   if (LeftTI.Width != RightTI.Width)
02166     return false;
02167 
02168   if (LeftTI.Align != RightTI.Align)
02169     return false;
02170 
02171   // Require fields to match.
02172   RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
02173   RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
02174   for (; li != le && ri != re; ++li, ++ri) {
02175     if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
02176       return false;
02177   }
02178   return (li == le && ri == re);
02179 }
02180 
02181 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
02182 /// returns true, or false, accordingly.
02183 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
02184 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
02185                                       const ObjCMethodDecl *right,
02186                                       MethodMatchStrategy strategy) {
02187   if (!matchTypes(Context, strategy, left->getReturnType(),
02188                   right->getReturnType()))
02189     return false;
02190 
02191   // If either is hidden, it is not considered to match.
02192   if (left->isHidden() || right->isHidden())
02193     return false;
02194 
02195   if (getLangOpts().ObjCAutoRefCount &&
02196       (left->hasAttr<NSReturnsRetainedAttr>()
02197          != right->hasAttr<NSReturnsRetainedAttr>() ||
02198        left->hasAttr<NSConsumesSelfAttr>()
02199          != right->hasAttr<NSConsumesSelfAttr>()))
02200     return false;
02201 
02202   ObjCMethodDecl::param_const_iterator
02203     li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
02204     re = right->param_end();
02205 
02206   for (; li != le && ri != re; ++li, ++ri) {
02207     assert(ri != right->param_end() && "Param mismatch");
02208     const ParmVarDecl *lparm = *li, *rparm = *ri;
02209 
02210     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
02211       return false;
02212 
02213     if (getLangOpts().ObjCAutoRefCount &&
02214         lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
02215       return false;
02216   }
02217   return true;
02218 }
02219 
02220 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
02221   // Record at the head of the list whether there were 0, 1, or >= 2 methods
02222   // inside categories.
02223   if (ObjCCategoryDecl *
02224         CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
02225     if (!CD->IsClassExtension() && List->getBits() < 2)
02226         List->setBits(List->getBits()+1);
02227 
02228   // If the list is empty, make it a singleton list.
02229   if (List->Method == nullptr) {
02230     List->Method = Method;
02231     List->setNext(nullptr);
02232       List->Count = Method->isDefined() ? 0 : 1;
02233     return;
02234   }
02235   
02236   // We've seen a method with this name, see if we have already seen this type
02237   // signature.
02238   ObjCMethodList *Previous = List;
02239   for (; List; Previous = List, List = List->getNext()) {
02240     // If we are building a module, keep all of the methods.
02241     if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
02242       continue;
02243 
02244     if (!MatchTwoMethodDeclarations(Method, List->Method))
02245       continue;
02246       
02247     ObjCMethodDecl *PrevObjCMethod = List->Method;
02248 
02249     // Propagate the 'defined' bit.
02250     if (Method->isDefined())
02251       PrevObjCMethod->setDefined(true);
02252     else
02253       ++List->Count;
02254     
02255     // If a method is deprecated, push it in the global pool.
02256     // This is used for better diagnostics.
02257     if (Method->isDeprecated()) {
02258       if (!PrevObjCMethod->isDeprecated())
02259         List->Method = Method;
02260     }
02261     // If new method is unavailable, push it into global pool
02262     // unless previous one is deprecated.
02263     if (Method->isUnavailable()) {
02264       if (PrevObjCMethod->getAvailability() < AR_Deprecated)
02265         List->Method = Method;
02266     }
02267     
02268     return;
02269   }
02270   
02271   // We have a new signature for an existing method - add it.
02272   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
02273   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
02274   Previous->setNext(new (Mem) ObjCMethodList(Method, 0, nullptr));
02275 }
02276 
02277 /// \brief Read the contents of the method pool for a given selector from
02278 /// external storage.
02279 void Sema::ReadMethodPool(Selector Sel) {
02280   assert(ExternalSource && "We need an external AST source");
02281   ExternalSource->ReadMethodPool(Sel);
02282 }
02283 
02284 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
02285                                  bool instance) {
02286   // Ignore methods of invalid containers.
02287   if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
02288     return;
02289 
02290   if (ExternalSource)
02291     ReadMethodPool(Method->getSelector());
02292   
02293   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
02294   if (Pos == MethodPool.end())
02295     Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
02296                                            GlobalMethods())).first;
02297   
02298   Method->setDefined(impl);
02299   
02300   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
02301   addMethodToGlobalList(&Entry, Method);
02302 }
02303 
02304 /// Determines if this is an "acceptable" loose mismatch in the global
02305 /// method pool.  This exists mostly as a hack to get around certain
02306 /// global mismatches which we can't afford to make warnings / errors.
02307 /// Really, what we want is a way to take a method out of the global
02308 /// method pool.
02309 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
02310                                        ObjCMethodDecl *other) {
02311   if (!chosen->isInstanceMethod())
02312     return false;
02313 
02314   Selector sel = chosen->getSelector();
02315   if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
02316     return false;
02317 
02318   // Don't complain about mismatches for -length if the method we
02319   // chose has an integral result type.
02320   return (chosen->getReturnType()->isIntegerType());
02321 }
02322 
02323 bool Sema::CollectMultipleMethodsInGlobalPool(Selector Sel,
02324                                               SmallVectorImpl<ObjCMethodDecl*>& Methods,
02325                                               bool instance) {
02326   if (ExternalSource)
02327     ReadMethodPool(Sel);
02328 
02329   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
02330   if (Pos == MethodPool.end())
02331     return false;
02332   // Gather the non-hidden methods.
02333   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
02334   for (ObjCMethodList *M = &MethList; M; M = M->getNext())
02335     if (M->Method && !M->Method->isHidden())
02336       Methods.push_back(M->Method);
02337   return (Methods.size() > 1);
02338 }
02339 
02340 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel,
02341                                           bool instance) {
02342   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
02343   // Test for no method in the pool which should not trigger any warning by caller.
02344   if (Pos == MethodPool.end())
02345     return true;
02346   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
02347   return MethList.Count > 1;
02348 }
02349 
02350 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
02351                                                bool receiverIdOrClass,
02352                                                bool warn, bool instance) {
02353   if (ExternalSource)
02354     ReadMethodPool(Sel);
02355     
02356   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
02357   if (Pos == MethodPool.end())
02358     return nullptr;
02359 
02360   // Gather the non-hidden methods.
02361   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
02362   SmallVector<ObjCMethodDecl *, 4> Methods;
02363   for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
02364     if (M->Method && !M->Method->isHidden()) {
02365       // If we're not supposed to warn about mismatches, we're done.
02366       if (!warn)
02367         return M->Method;
02368 
02369       Methods.push_back(M->Method);
02370     }
02371   }
02372 
02373   // If there aren't any visible methods, we're done.
02374   // FIXME: Recover if there are any known-but-hidden methods?
02375   if (Methods.empty())
02376     return nullptr;
02377 
02378   if (Methods.size() == 1)
02379     return Methods[0];
02380 
02381   // We found multiple methods, so we may have to complain.
02382   bool issueDiagnostic = false, issueError = false;
02383 
02384   // We support a warning which complains about *any* difference in
02385   // method signature.
02386   bool strictSelectorMatch =
02387       receiverIdOrClass && warn &&
02388       !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
02389   if (strictSelectorMatch) {
02390     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
02391       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
02392         issueDiagnostic = true;
02393         break;
02394       }
02395     }
02396   }
02397 
02398   // If we didn't see any strict differences, we won't see any loose
02399   // differences.  In ARC, however, we also need to check for loose
02400   // mismatches, because most of them are errors.
02401   if (!strictSelectorMatch ||
02402       (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
02403     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
02404       // This checks if the methods differ in type mismatch.
02405       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
02406           !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
02407         issueDiagnostic = true;
02408         if (getLangOpts().ObjCAutoRefCount)
02409           issueError = true;
02410         break;
02411       }
02412     }
02413 
02414   if (issueDiagnostic) {
02415     if (issueError)
02416       Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
02417     else if (strictSelectorMatch)
02418       Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
02419     else
02420       Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
02421 
02422     Diag(Methods[0]->getLocStart(),
02423          issueError ? diag::note_possibility : diag::note_using)
02424       << Methods[0]->getSourceRange();
02425     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
02426       Diag(Methods[I]->getLocStart(), diag::note_also_found)
02427         << Methods[I]->getSourceRange();
02428   }
02429   }
02430   return Methods[0];
02431 }
02432 
02433 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
02434   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
02435   if (Pos == MethodPool.end())
02436     return nullptr;
02437 
02438   GlobalMethods &Methods = Pos->second;
02439   for (const ObjCMethodList *Method = &Methods.first; Method;
02440        Method = Method->getNext())
02441     if (Method->Method && Method->Method->isDefined())
02442       return Method->Method;
02443   
02444   for (const ObjCMethodList *Method = &Methods.second; Method;
02445        Method = Method->getNext())
02446     if (Method->Method && Method->Method->isDefined())
02447       return Method->Method;
02448   return nullptr;
02449 }
02450 
02451 static void
02452 HelperSelectorsForTypoCorrection(
02453                       SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
02454                       StringRef Typo, const ObjCMethodDecl * Method) {
02455   const unsigned MaxEditDistance = 1;
02456   unsigned BestEditDistance = MaxEditDistance + 1;
02457   std::string MethodName = Method->getSelector().getAsString();
02458   
02459   unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
02460   if (MinPossibleEditDistance > 0 &&
02461       Typo.size() / MinPossibleEditDistance < 1)
02462     return;
02463   unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
02464   if (EditDistance > MaxEditDistance)
02465     return;
02466   if (EditDistance == BestEditDistance)
02467     BestMethod.push_back(Method);
02468   else if (EditDistance < BestEditDistance) {
02469     BestMethod.clear();
02470     BestMethod.push_back(Method);
02471   }
02472 }
02473 
02474 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
02475                                      QualType ObjectType) {
02476   if (ObjectType.isNull())
02477     return true;
02478   if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
02479     return true;
02480   return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
02481          nullptr;
02482 }
02483 
02484 const ObjCMethodDecl *
02485 Sema::SelectorsForTypoCorrection(Selector Sel,
02486                                  QualType ObjectType) {
02487   unsigned NumArgs = Sel.getNumArgs();
02488   SmallVector<const ObjCMethodDecl *, 8> Methods;
02489   bool ObjectIsId = true, ObjectIsClass = true;
02490   if (ObjectType.isNull())
02491     ObjectIsId = ObjectIsClass = false;
02492   else if (!ObjectType->isObjCObjectPointerType())
02493     return nullptr;
02494   else if (const ObjCObjectPointerType *ObjCPtr =
02495            ObjectType->getAsObjCInterfacePointerType()) {
02496     ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
02497     ObjectIsId = ObjectIsClass = false;
02498   }
02499   else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
02500     ObjectIsClass = false;
02501   else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
02502     ObjectIsId = false;
02503   else
02504     return nullptr;
02505 
02506   for (GlobalMethodPool::iterator b = MethodPool.begin(),
02507        e = MethodPool.end(); b != e; b++) {
02508     // instance methods
02509     for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
02510       if (M->Method &&
02511           (M->Method->getSelector().getNumArgs() == NumArgs) &&
02512           (M->Method->getSelector() != Sel)) {
02513         if (ObjectIsId)
02514           Methods.push_back(M->Method);
02515         else if (!ObjectIsClass &&
02516                  HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
02517           Methods.push_back(M->Method);
02518       }
02519     // class methods
02520     for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
02521       if (M->Method &&
02522           (M->Method->getSelector().getNumArgs() == NumArgs) &&
02523           (M->Method->getSelector() != Sel)) {
02524         if (ObjectIsClass)
02525           Methods.push_back(M->Method);
02526         else if (!ObjectIsId &&
02527                  HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
02528           Methods.push_back(M->Method);
02529       }
02530   }
02531   
02532   SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
02533   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
02534     HelperSelectorsForTypoCorrection(SelectedMethods,
02535                                      Sel.getAsString(), Methods[i]);
02536   }
02537   return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
02538 }
02539 
02540 /// DiagnoseDuplicateIvars -
02541 /// Check for duplicate ivars in the entire class at the start of 
02542 /// \@implementation. This becomes necesssary because class extension can
02543 /// add ivars to a class in random order which will not be known until
02544 /// class's \@implementation is seen.
02545 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID, 
02546                                   ObjCInterfaceDecl *SID) {
02547   for (auto *Ivar : ID->ivars()) {
02548     if (Ivar->isInvalidDecl())
02549       continue;
02550     if (IdentifierInfo *II = Ivar->getIdentifier()) {
02551       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
02552       if (prevIvar) {
02553         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
02554         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
02555         Ivar->setInvalidDecl();
02556       }
02557     }
02558   }
02559 }
02560 
02561 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
02562   switch (CurContext->getDeclKind()) {
02563     case Decl::ObjCInterface:
02564       return Sema::OCK_Interface;
02565     case Decl::ObjCProtocol:
02566       return Sema::OCK_Protocol;
02567     case Decl::ObjCCategory:
02568       if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
02569         return Sema::OCK_ClassExtension;
02570       else
02571         return Sema::OCK_Category;
02572     case Decl::ObjCImplementation:
02573       return Sema::OCK_Implementation;
02574     case Decl::ObjCCategoryImpl:
02575       return Sema::OCK_CategoryImplementation;
02576 
02577     default:
02578       return Sema::OCK_None;
02579   }
02580 }
02581 
02582 // Note: For class/category implementations, allMethods is always null.
02583 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
02584                        ArrayRef<DeclGroupPtrTy> allTUVars) {
02585   if (getObjCContainerKind() == Sema::OCK_None)
02586     return nullptr;
02587 
02588   assert(AtEnd.isValid() && "Invalid location for '@end'");
02589 
02590   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
02591   Decl *ClassDecl = cast<Decl>(OCD);
02592   
02593   bool isInterfaceDeclKind =
02594         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
02595          || isa<ObjCProtocolDecl>(ClassDecl);
02596   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
02597 
02598   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
02599   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
02600   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
02601 
02602   for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
02603     ObjCMethodDecl *Method =
02604       cast_or_null<ObjCMethodDecl>(allMethods[i]);
02605 
02606     if (!Method) continue;  // Already issued a diagnostic.
02607     if (Method->isInstanceMethod()) {
02608       /// Check for instance method of the same name with incompatible types
02609       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
02610       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
02611                               : false;
02612       if ((isInterfaceDeclKind && PrevMethod && !match)
02613           || (checkIdenticalMethods && match)) {
02614           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
02615             << Method->getDeclName();
02616           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02617         Method->setInvalidDecl();
02618       } else {
02619         if (PrevMethod) {
02620           Method->setAsRedeclaration(PrevMethod);
02621           if (!Context.getSourceManager().isInSystemHeader(
02622                  Method->getLocation()))
02623             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
02624               << Method->getDeclName();
02625           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02626         }
02627         InsMap[Method->getSelector()] = Method;
02628         /// The following allows us to typecheck messages to "id".
02629         AddInstanceMethodToGlobalPool(Method);
02630       }
02631     } else {
02632       /// Check for class method of the same name with incompatible types
02633       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
02634       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
02635                               : false;
02636       if ((isInterfaceDeclKind && PrevMethod && !match)
02637           || (checkIdenticalMethods && match)) {
02638         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
02639           << Method->getDeclName();
02640         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02641         Method->setInvalidDecl();
02642       } else {
02643         if (PrevMethod) {
02644           Method->setAsRedeclaration(PrevMethod);
02645           if (!Context.getSourceManager().isInSystemHeader(
02646                  Method->getLocation()))
02647             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
02648               << Method->getDeclName();
02649           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
02650         }
02651         ClsMap[Method->getSelector()] = Method;
02652         AddFactoryMethodToGlobalPool(Method);
02653       }
02654     }
02655   }
02656   if (isa<ObjCInterfaceDecl>(ClassDecl)) {
02657     // Nothing to do here.
02658   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
02659     // Categories are used to extend the class by declaring new methods.
02660     // By the same token, they are also used to add new properties. No
02661     // need to compare the added property to those in the class.
02662 
02663     if (C->IsClassExtension()) {
02664       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
02665       DiagnoseClassExtensionDupMethods(C, CCPrimary);
02666     }
02667   }
02668   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
02669     if (CDecl->getIdentifier())
02670       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
02671       // user-defined setter/getter. It also synthesizes setter/getter methods
02672       // and adds them to the DeclContext and global method pools.
02673       for (auto *I : CDecl->properties())
02674         ProcessPropertyDecl(I, CDecl);
02675     CDecl->setAtEndRange(AtEnd);
02676   }
02677   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
02678     IC->setAtEndRange(AtEnd);
02679     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
02680       // Any property declared in a class extension might have user
02681       // declared setter or getter in current class extension or one
02682       // of the other class extensions. Mark them as synthesized as
02683       // property will be synthesized when property with same name is
02684       // seen in the @implementation.
02685       for (const auto *Ext : IDecl->visible_extensions()) {
02686         for (const auto *Property : Ext->properties()) {
02687           // Skip over properties declared @dynamic
02688           if (const ObjCPropertyImplDecl *PIDecl
02689               = IC->FindPropertyImplDecl(Property->getIdentifier()))
02690             if (PIDecl->getPropertyImplementation() 
02691                   == ObjCPropertyImplDecl::Dynamic)
02692               continue;
02693 
02694           for (const auto *Ext : IDecl->visible_extensions()) {
02695             if (ObjCMethodDecl *GetterMethod
02696                   = Ext->getInstanceMethod(Property->getGetterName()))
02697               GetterMethod->setPropertyAccessor(true);
02698             if (!Property->isReadOnly())
02699               if (ObjCMethodDecl *SetterMethod
02700                     = Ext->getInstanceMethod(Property->getSetterName()))
02701                 SetterMethod->setPropertyAccessor(true);
02702           }
02703         }
02704       }
02705       ImplMethodsVsClassMethods(S, IC, IDecl);
02706       AtomicPropertySetterGetterRules(IC, IDecl);
02707       DiagnoseOwningPropertyGetterSynthesis(IC);
02708       DiagnoseUnusedBackingIvarInAccessor(S, IC);
02709       if (IDecl->hasDesignatedInitializers())
02710         DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
02711 
02712       bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
02713       if (IDecl->getSuperClass() == nullptr) {
02714         // This class has no superclass, so check that it has been marked with
02715         // __attribute((objc_root_class)).
02716         if (!HasRootClassAttr) {
02717           SourceLocation DeclLoc(IDecl->getLocation());
02718           SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
02719           Diag(DeclLoc, diag::warn_objc_root_class_missing)
02720             << IDecl->getIdentifier();
02721           // See if NSObject is in the current scope, and if it is, suggest
02722           // adding " : NSObject " to the class declaration.
02723           NamedDecl *IF = LookupSingleName(TUScope,
02724                                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
02725                                            DeclLoc, LookupOrdinaryName);
02726           ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
02727           if (NSObjectDecl && NSObjectDecl->getDefinition()) {
02728             Diag(SuperClassLoc, diag::note_objc_needs_superclass)
02729               << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
02730           } else {
02731             Diag(SuperClassLoc, diag::note_objc_needs_superclass);
02732           }
02733         }
02734       } else if (HasRootClassAttr) {
02735         // Complain that only root classes may have this attribute.
02736         Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
02737       }
02738 
02739       if (LangOpts.ObjCRuntime.isNonFragile()) {
02740         while (IDecl->getSuperClass()) {
02741           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
02742           IDecl = IDecl->getSuperClass();
02743         }
02744       }
02745     }
02746     SetIvarInitializers(IC);
02747   } else if (ObjCCategoryImplDecl* CatImplClass =
02748                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
02749     CatImplClass->setAtEndRange(AtEnd);
02750 
02751     // Find category interface decl and then check that all methods declared
02752     // in this interface are implemented in the category @implementation.
02753     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
02754       if (ObjCCategoryDecl *Cat
02755             = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
02756         ImplMethodsVsClassMethods(S, CatImplClass, Cat);
02757       }
02758     }
02759   }
02760   if (isInterfaceDeclKind) {
02761     // Reject invalid vardecls.
02762     for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
02763       DeclGroupRef DG = allTUVars[i].get();
02764       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
02765         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
02766           if (!VDecl->hasExternalStorage())
02767             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
02768         }
02769     }
02770   }
02771   ActOnObjCContainerFinishDefinition();
02772 
02773   for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
02774     DeclGroupRef DG = allTUVars[i].get();
02775     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
02776       (*I)->setTopLevelDeclInObjCContainer();
02777     Consumer.HandleTopLevelDeclInObjCContainer(DG);
02778   }
02779 
02780   ActOnDocumentableDecl(ClassDecl);
02781   return ClassDecl;
02782 }
02783 
02784 
02785 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
02786 /// objective-c's type qualifier from the parser version of the same info.
02787 static Decl::ObjCDeclQualifier
02788 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
02789   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
02790 }
02791 
02792 /// \brief Check whether the declared result type of the given Objective-C
02793 /// method declaration is compatible with the method's class.
02794 ///
02795 static Sema::ResultTypeCompatibilityKind 
02796 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
02797                                     ObjCInterfaceDecl *CurrentClass) {
02798   QualType ResultType = Method->getReturnType();
02799 
02800   // If an Objective-C method inherits its related result type, then its 
02801   // declared result type must be compatible with its own class type. The
02802   // declared result type is compatible if:
02803   if (const ObjCObjectPointerType *ResultObjectType
02804                                 = ResultType->getAs<ObjCObjectPointerType>()) {
02805     //   - it is id or qualified id, or
02806     if (ResultObjectType->isObjCIdType() ||
02807         ResultObjectType->isObjCQualifiedIdType())
02808       return Sema::RTC_Compatible;
02809   
02810     if (CurrentClass) {
02811       if (ObjCInterfaceDecl *ResultClass 
02812                                       = ResultObjectType->getInterfaceDecl()) {
02813         //   - it is the same as the method's class type, or
02814         if (declaresSameEntity(CurrentClass, ResultClass))
02815           return Sema::RTC_Compatible;
02816         
02817         //   - it is a superclass of the method's class type
02818         if (ResultClass->isSuperClassOf(CurrentClass))
02819           return Sema::RTC_Compatible;
02820       }      
02821     } else {
02822       // Any Objective-C pointer type might be acceptable for a protocol
02823       // method; we just don't know.
02824       return Sema::RTC_Unknown;
02825     }
02826   }
02827   
02828   return Sema::RTC_Incompatible;
02829 }
02830 
02831 namespace {
02832 /// A helper class for searching for methods which a particular method
02833 /// overrides.
02834 class OverrideSearch {
02835 public:
02836   Sema &S;
02837   ObjCMethodDecl *Method;
02838   llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
02839   bool Recursive;
02840 
02841 public:
02842   OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
02843     Selector selector = method->getSelector();
02844 
02845     // Bypass this search if we've never seen an instance/class method
02846     // with this selector before.
02847     Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
02848     if (it == S.MethodPool.end()) {
02849       if (!S.getExternalSource()) return;
02850       S.ReadMethodPool(selector);
02851       
02852       it = S.MethodPool.find(selector);
02853       if (it == S.MethodPool.end())
02854         return;
02855     }
02856     ObjCMethodList &list =
02857       method->isInstanceMethod() ? it->second.first : it->second.second;
02858     if (!list.Method) return;
02859 
02860     ObjCContainerDecl *container
02861       = cast<ObjCContainerDecl>(method->getDeclContext());
02862 
02863     // Prevent the search from reaching this container again.  This is
02864     // important with categories, which override methods from the
02865     // interface and each other.
02866     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
02867       searchFromContainer(container);
02868       if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
02869         searchFromContainer(Interface);
02870     } else {
02871       searchFromContainer(container);
02872     }
02873   }
02874 
02875   typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
02876   iterator begin() const { return Overridden.begin(); }
02877   iterator end() const { return Overridden.end(); }
02878 
02879 private:
02880   void searchFromContainer(ObjCContainerDecl *container) {
02881     if (container->isInvalidDecl()) return;
02882 
02883     switch (container->getDeclKind()) {
02884 #define OBJCCONTAINER(type, base) \
02885     case Decl::type: \
02886       searchFrom(cast<type##Decl>(container)); \
02887       break;
02888 #define ABSTRACT_DECL(expansion)
02889 #define DECL(type, base) \
02890     case Decl::type:
02891 #include "clang/AST/DeclNodes.inc"
02892       llvm_unreachable("not an ObjC container!");
02893     }
02894   }
02895 
02896   void searchFrom(ObjCProtocolDecl *protocol) {
02897     if (!protocol->hasDefinition())
02898       return;
02899     
02900     // A method in a protocol declaration overrides declarations from
02901     // referenced ("parent") protocols.
02902     search(protocol->getReferencedProtocols());
02903   }
02904 
02905   void searchFrom(ObjCCategoryDecl *category) {
02906     // A method in a category declaration overrides declarations from
02907     // the main class and from protocols the category references.
02908     // The main class is handled in the constructor.
02909     search(category->getReferencedProtocols());
02910   }
02911 
02912   void searchFrom(ObjCCategoryImplDecl *impl) {
02913     // A method in a category definition that has a category
02914     // declaration overrides declarations from the category
02915     // declaration.
02916     if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
02917       search(category);
02918       if (ObjCInterfaceDecl *Interface = category->getClassInterface())
02919         search(Interface);
02920 
02921     // Otherwise it overrides declarations from the class.
02922     } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
02923       search(Interface);
02924     }
02925   }
02926 
02927   void searchFrom(ObjCInterfaceDecl *iface) {
02928     // A method in a class declaration overrides declarations from
02929     if (!iface->hasDefinition())
02930       return;
02931     
02932     //   - categories,
02933     for (auto *Cat : iface->known_categories())
02934       search(Cat);
02935 
02936     //   - the super class, and
02937     if (ObjCInterfaceDecl *super = iface->getSuperClass())
02938       search(super);
02939 
02940     //   - any referenced protocols.
02941     search(iface->getReferencedProtocols());
02942   }
02943 
02944   void searchFrom(ObjCImplementationDecl *impl) {
02945     // A method in a class implementation overrides declarations from
02946     // the class interface.
02947     if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
02948       search(Interface);
02949   }
02950 
02951 
02952   void search(const ObjCProtocolList &protocols) {
02953     for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
02954          i != e; ++i)
02955       search(*i);
02956   }
02957 
02958   void search(ObjCContainerDecl *container) {
02959     // Check for a method in this container which matches this selector.
02960     ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
02961                                                 Method->isInstanceMethod(),
02962                                                 /*AllowHidden=*/true);
02963 
02964     // If we find one, record it and bail out.
02965     if (meth) {
02966       Overridden.insert(meth);
02967       return;
02968     }
02969 
02970     // Otherwise, search for methods that a hypothetical method here
02971     // would have overridden.
02972 
02973     // Note that we're now in a recursive case.
02974     Recursive = true;
02975 
02976     searchFromContainer(container);
02977   }
02978 };
02979 }
02980 
02981 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
02982                                     ObjCInterfaceDecl *CurrentClass,
02983                                     ResultTypeCompatibilityKind RTC) {
02984   // Search for overridden methods and merge information down from them.
02985   OverrideSearch overrides(*this, ObjCMethod);
02986   // Keep track if the method overrides any method in the class's base classes,
02987   // its protocols, or its categories' protocols; we will keep that info
02988   // in the ObjCMethodDecl.
02989   // For this info, a method in an implementation is not considered as
02990   // overriding the same method in the interface or its categories.
02991   bool hasOverriddenMethodsInBaseOrProtocol = false;
02992   for (OverrideSearch::iterator
02993          i = overrides.begin(), e = overrides.end(); i != e; ++i) {
02994     ObjCMethodDecl *overridden = *i;
02995 
02996     if (!hasOverriddenMethodsInBaseOrProtocol) {
02997       if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
02998           CurrentClass != overridden->getClassInterface() ||
02999           overridden->isOverriding()) {
03000         hasOverriddenMethodsInBaseOrProtocol = true;
03001 
03002       } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
03003         // OverrideSearch will return as "overridden" the same method in the
03004         // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
03005         // check whether a category of a base class introduced a method with the
03006         // same selector, after the interface method declaration.
03007         // To avoid unnecessary lookups in the majority of cases, we use the
03008         // extra info bits in GlobalMethodPool to check whether there were any
03009         // category methods with this selector.
03010         GlobalMethodPool::iterator It =
03011             MethodPool.find(ObjCMethod->getSelector());
03012         if (It != MethodPool.end()) {
03013           ObjCMethodList &List =
03014             ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
03015           unsigned CategCount = List.getBits();
03016           if (CategCount > 0) {
03017             // If the method is in a category we'll do lookup if there were at
03018             // least 2 category methods recorded, otherwise only one will do.
03019             if (CategCount > 1 ||
03020                 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
03021               OverrideSearch overrides(*this, overridden);
03022               for (OverrideSearch::iterator
03023                      OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
03024                 ObjCMethodDecl *SuperOverridden = *OI;
03025                 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
03026                     CurrentClass != SuperOverridden->getClassInterface()) {
03027                   hasOverriddenMethodsInBaseOrProtocol = true;
03028                   overridden->setOverriding(true);
03029                   break;
03030                 }
03031               }
03032             }
03033           }
03034         }
03035       }
03036     }
03037 
03038     // Propagate down the 'related result type' bit from overridden methods.
03039     if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
03040       ObjCMethod->SetRelatedResultType();
03041 
03042     // Then merge the declarations.
03043     mergeObjCMethodDecls(ObjCMethod, overridden);
03044 
03045     if (ObjCMethod->isImplicit() && overridden->isImplicit())
03046       continue; // Conflicting properties are detected elsewhere.
03047 
03048     // Check for overriding methods
03049     if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) || 
03050         isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
03051       CheckConflictingOverridingMethod(ObjCMethod, overridden,
03052               isa<ObjCProtocolDecl>(overridden->getDeclContext()));
03053     
03054     if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
03055         isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
03056         !overridden->isImplicit() /* not meant for properties */) {
03057       ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
03058                                           E = ObjCMethod->param_end();
03059       ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
03060                                      PrevE = overridden->param_end();
03061       for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
03062         assert(PrevI != overridden->param_end() && "Param mismatch");
03063         QualType T1 = Context.getCanonicalType((*ParamI)->getType());
03064         QualType T2 = Context.getCanonicalType((*PrevI)->getType());
03065         // If type of argument of method in this class does not match its
03066         // respective argument type in the super class method, issue warning;
03067         if (!Context.typesAreCompatible(T1, T2)) {
03068           Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
03069             << T1 << T2;
03070           Diag(overridden->getLocation(), diag::note_previous_declaration);
03071           break;
03072         }
03073       }
03074     }
03075   }
03076 
03077   ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
03078 }
03079 
03080 Decl *Sema::ActOnMethodDeclaration(
03081     Scope *S,
03082     SourceLocation MethodLoc, SourceLocation EndLoc,
03083     tok::TokenKind MethodType, 
03084     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
03085     ArrayRef<SourceLocation> SelectorLocs,
03086     Selector Sel,
03087     // optional arguments. The number of types/arguments is obtained
03088     // from the Sel.getNumArgs().
03089     ObjCArgInfo *ArgInfo,
03090     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
03091     AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
03092     bool isVariadic, bool MethodDefinition) {
03093   // Make sure we can establish a context for the method.
03094   if (!CurContext->isObjCContainer()) {
03095     Diag(MethodLoc, diag::error_missing_method_context);
03096     return nullptr;
03097   }
03098   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
03099   Decl *ClassDecl = cast<Decl>(OCD); 
03100   QualType resultDeclType;
03101 
03102   bool HasRelatedResultType = false;
03103   TypeSourceInfo *ReturnTInfo = nullptr;
03104   if (ReturnType) {
03105     resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
03106 
03107     if (CheckFunctionReturnType(resultDeclType, MethodLoc))
03108       return nullptr;
03109 
03110     HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
03111   } else { // get the type for "id".
03112     resultDeclType = Context.getObjCIdType();
03113     Diag(MethodLoc, diag::warn_missing_method_return_type)
03114       << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
03115   }
03116 
03117   ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
03118       Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
03119       MethodType == tok::minus, isVariadic,
03120       /*isPropertyAccessor=*/false,
03121       /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
03122       MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
03123                                            : ObjCMethodDecl::Required,
03124       HasRelatedResultType);
03125 
03126   SmallVector<ParmVarDecl*, 16> Params;
03127 
03128   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
03129     QualType ArgType;
03130     TypeSourceInfo *DI;
03131 
03132     if (!ArgInfo[i].Type) {
03133       ArgType = Context.getObjCIdType();
03134       DI = nullptr;
03135     } else {
03136       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
03137     }
03138 
03139     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc, 
03140                    LookupOrdinaryName, ForRedeclaration);
03141     LookupName(R, S);
03142     if (R.isSingleResult()) {
03143       NamedDecl *PrevDecl = R.getFoundDecl();
03144       if (S->isDeclScope(PrevDecl)) {
03145         Diag(ArgInfo[i].NameLoc, 
03146              (MethodDefinition ? diag::warn_method_param_redefinition 
03147                                : diag::warn_method_param_declaration)) 
03148           << ArgInfo[i].Name;
03149         Diag(PrevDecl->getLocation(), 
03150              diag::note_previous_declaration);
03151       }
03152     }
03153 
03154     SourceLocation StartLoc = DI
03155       ? DI->getTypeLoc().getBeginLoc()
03156       : ArgInfo[i].NameLoc;
03157 
03158     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
03159                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
03160                                         ArgType, DI, SC_None);
03161 
03162     Param->setObjCMethodScopeInfo(i);
03163 
03164     Param->setObjCDeclQualifier(
03165       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
03166 
03167     // Apply the attributes to the parameter.
03168     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
03169 
03170     if (Param->hasAttr<BlocksAttr>()) {
03171       Diag(Param->getLocation(), diag::err_block_on_nonlocal);
03172       Param->setInvalidDecl();
03173     }
03174     S->AddDecl(Param);
03175     IdResolver.AddDecl(Param);
03176 
03177     Params.push_back(Param);
03178   }
03179   
03180   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
03181     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
03182     QualType ArgType = Param->getType();
03183     if (ArgType.isNull())
03184       ArgType = Context.getObjCIdType();
03185     else
03186       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
03187       ArgType = Context.getAdjustedParameterType(ArgType);
03188 
03189     Param->setDeclContext(ObjCMethod);
03190     Params.push_back(Param);
03191   }
03192   
03193   ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
03194   ObjCMethod->setObjCDeclQualifier(
03195     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
03196 
03197   if (AttrList)
03198     ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
03199 
03200   // Add the method now.
03201   const ObjCMethodDecl *PrevMethod = nullptr;
03202   if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
03203     if (MethodType == tok::minus) {
03204       PrevMethod = ImpDecl->getInstanceMethod(Sel);
03205       ImpDecl->addInstanceMethod(ObjCMethod);
03206     } else {
03207       PrevMethod = ImpDecl->getClassMethod(Sel);
03208       ImpDecl->addClassMethod(ObjCMethod);
03209     }
03210 
03211     ObjCMethodDecl *IMD = nullptr;
03212     if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
03213       IMD = IDecl->lookupMethod(ObjCMethod->getSelector(), 
03214                                 ObjCMethod->isInstanceMethod());
03215     if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
03216         !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
03217       // merge the attribute into implementation.
03218       ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
03219                                                    ObjCMethod->getLocation()));
03220     }
03221     if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
03222       ObjCMethodFamily family = 
03223         ObjCMethod->getSelector().getMethodFamily();
03224       if (family == OMF_dealloc && IMD && IMD->isOverriding()) 
03225         Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
03226           << ObjCMethod->getDeclName();
03227     }
03228   } else {
03229     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
03230   }
03231 
03232   if (PrevMethod) {
03233     // You can never have two method definitions with the same name.
03234     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
03235       << ObjCMethod->getDeclName();
03236     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
03237     ObjCMethod->setInvalidDecl();
03238     return ObjCMethod;
03239   }
03240 
03241   // If this Objective-C method does not have a related result type, but we
03242   // are allowed to infer related result types, try to do so based on the
03243   // method family.
03244   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
03245   if (!CurrentClass) {
03246     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
03247       CurrentClass = Cat->getClassInterface();
03248     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
03249       CurrentClass = Impl->getClassInterface();
03250     else if (ObjCCategoryImplDecl *CatImpl
03251                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
03252       CurrentClass = CatImpl->getClassInterface();
03253   }
03254 
03255   ResultTypeCompatibilityKind RTC
03256     = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
03257 
03258   CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
03259 
03260   bool ARCError = false;
03261   if (getLangOpts().ObjCAutoRefCount)
03262     ARCError = CheckARCMethodDecl(ObjCMethod);
03263 
03264   // Infer the related result type when possible.
03265   if (!ARCError && RTC == Sema::RTC_Compatible &&
03266       !ObjCMethod->hasRelatedResultType() &&
03267       LangOpts.ObjCInferRelatedResultType) {
03268     bool InferRelatedResultType = false;
03269     switch (ObjCMethod->getMethodFamily()) {
03270     case OMF_None:
03271     case OMF_copy:
03272     case OMF_dealloc:
03273     case OMF_finalize:
03274     case OMF_mutableCopy:
03275     case OMF_release:
03276     case OMF_retainCount:
03277     case OMF_initialize:
03278     case OMF_performSelector:
03279       break;
03280       
03281     case OMF_alloc:
03282     case OMF_new:
03283       InferRelatedResultType = ObjCMethod->isClassMethod();
03284       break;
03285         
03286     case OMF_init:
03287     case OMF_autorelease:
03288     case OMF_retain:
03289     case OMF_self:
03290       InferRelatedResultType = ObjCMethod->isInstanceMethod();
03291       break;
03292     }
03293     
03294     if (InferRelatedResultType)
03295       ObjCMethod->SetRelatedResultType();
03296   }
03297 
03298   ActOnDocumentableDecl(ObjCMethod);
03299 
03300   return ObjCMethod;
03301 }
03302 
03303 bool Sema::CheckObjCDeclScope(Decl *D) {
03304   // Following is also an error. But it is caused by a missing @end
03305   // and diagnostic is issued elsewhere.
03306   if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
03307     return false;
03308 
03309   // If we switched context to translation unit while we are still lexically in
03310   // an objc container, it means the parser missed emitting an error.
03311   if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
03312     return false;
03313   
03314   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
03315   D->setInvalidDecl();
03316 
03317   return true;
03318 }
03319 
03320 /// Called whenever \@defs(ClassName) is encountered in the source.  Inserts the
03321 /// instance variables of ClassName into Decls.
03322 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
03323                      IdentifierInfo *ClassName,
03324                      SmallVectorImpl<Decl*> &Decls) {
03325   // Check that ClassName is a valid class
03326   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
03327   if (!Class) {
03328     Diag(DeclStart, diag::err_undef_interface) << ClassName;
03329     return;
03330   }
03331   if (LangOpts.ObjCRuntime.isNonFragile()) {
03332     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
03333     return;
03334   }
03335 
03336   // Collect the instance variables
03337   SmallVector<const ObjCIvarDecl*, 32> Ivars;
03338   Context.DeepCollectObjCIvars(Class, true, Ivars);
03339   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
03340   for (unsigned i = 0; i < Ivars.size(); i++) {
03341     const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
03342     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
03343     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
03344                                            /*FIXME: StartL=*/ID->getLocation(),
03345                                            ID->getLocation(),
03346                                            ID->getIdentifier(), ID->getType(),
03347                                            ID->getBitWidth());
03348     Decls.push_back(FD);
03349   }
03350 
03351   // Introduce all of these fields into the appropriate scope.
03352   for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
03353        D != Decls.end(); ++D) {
03354     FieldDecl *FD = cast<FieldDecl>(*D);
03355     if (getLangOpts().CPlusPlus)
03356       PushOnScopeChains(cast<FieldDecl>(FD), S);
03357     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
03358       Record->addDecl(FD);
03359   }
03360 }
03361 
03362 /// \brief Build a type-check a new Objective-C exception variable declaration.
03363 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
03364                                       SourceLocation StartLoc,
03365                                       SourceLocation IdLoc,
03366                                       IdentifierInfo *Id,
03367                                       bool Invalid) {
03368   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage 
03369   // duration shall not be qualified by an address-space qualifier."
03370   // Since all parameters have automatic store duration, they can not have
03371   // an address space.
03372   if (T.getAddressSpace() != 0) {
03373     Diag(IdLoc, diag::err_arg_with_address_space);
03374     Invalid = true;
03375   }
03376   
03377   // An @catch parameter must be an unqualified object pointer type;
03378   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
03379   if (Invalid) {
03380     // Don't do any further checking.
03381   } else if (T->isDependentType()) {
03382     // Okay: we don't know what this type will instantiate to.
03383   } else if (!T->isObjCObjectPointerType()) {
03384     Invalid = true;
03385     Diag(IdLoc ,diag::err_catch_param_not_objc_type);
03386   } else if (T->isObjCQualifiedIdType()) {
03387     Invalid = true;
03388     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
03389   }
03390   
03391   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
03392                                  T, TInfo, SC_None);
03393   New->setExceptionVariable(true);
03394   
03395   // In ARC, infer 'retaining' for variables of retainable type.
03396   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
03397     Invalid = true;
03398 
03399   if (Invalid)
03400     New->setInvalidDecl();
03401   return New;
03402 }
03403 
03404 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
03405   const DeclSpec &DS = D.getDeclSpec();
03406   
03407   // We allow the "register" storage class on exception variables because
03408   // GCC did, but we drop it completely. Any other storage class is an error.
03409   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
03410     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
03411       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
03412   } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
03413     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
03414       << DeclSpec::getSpecifierName(SCS);
03415   }
03416   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
03417     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
03418          diag::err_invalid_thread)
03419      << DeclSpec::getSpecifierName(TSCS);
03420   D.getMutableDeclSpec().ClearStorageClassSpecs();
03421 
03422   DiagnoseFunctionSpecifiers(D.getDeclSpec());
03423   
03424   // Check that there are no default arguments inside the type of this
03425   // exception object (C++ only).
03426   if (getLangOpts().CPlusPlus)
03427     CheckExtraCXXDefaultArguments(D);
03428   
03429   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
03430   QualType ExceptionType = TInfo->getType();
03431 
03432   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
03433                                         D.getSourceRange().getBegin(),
03434                                         D.getIdentifierLoc(),
03435                                         D.getIdentifier(),
03436                                         D.isInvalidType());
03437   
03438   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
03439   if (D.getCXXScopeSpec().isSet()) {
03440     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
03441       << D.getCXXScopeSpec().getRange();
03442     New->setInvalidDecl();
03443   }
03444   
03445   // Add the parameter declaration into this scope.
03446   S->AddDecl(New);
03447   if (D.getIdentifier())
03448     IdResolver.AddDecl(New);
03449   
03450   ProcessDeclAttributes(S, New, D);
03451   
03452   if (New->hasAttr<BlocksAttr>())
03453     Diag(New->getLocation(), diag::err_block_on_nonlocal);
03454   return New;
03455 }
03456 
03457 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
03458 /// initialization.
03459 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
03460                                 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
03461   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv; 
03462        Iv= Iv->getNextIvar()) {
03463     QualType QT = Context.getBaseElementType(Iv->getType());
03464     if (QT->isRecordType())
03465       Ivars.push_back(Iv);
03466   }
03467 }
03468 
03469 void Sema::DiagnoseUseOfUnimplementedSelectors() {
03470   // Load referenced selectors from the external source.
03471   if (ExternalSource) {
03472     SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
03473     ExternalSource->ReadReferencedSelectors(Sels);
03474     for (unsigned I = 0, N = Sels.size(); I != N; ++I)
03475       ReferencedSelectors[Sels[I].first] = Sels[I].second;
03476   }
03477   
03478   // Warning will be issued only when selector table is
03479   // generated (which means there is at lease one implementation
03480   // in the TU). This is to match gcc's behavior.
03481   if (ReferencedSelectors.empty() || 
03482       !Context.AnyObjCImplementation())
03483     return;
03484   for (llvm::DenseMap<Selector, SourceLocation>::iterator S = 
03485         ReferencedSelectors.begin(),
03486        E = ReferencedSelectors.end(); S != E; ++S) {
03487     Selector Sel = (*S).first;
03488     if (!LookupImplementedMethodInGlobalPool(Sel))
03489       Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
03490   }
03491   return;
03492 }
03493 
03494 ObjCIvarDecl *
03495 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
03496                                      const ObjCPropertyDecl *&PDecl) const {
03497   if (Method->isClassMethod())
03498     return nullptr;
03499   const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
03500   if (!IDecl)
03501     return nullptr;
03502   Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
03503                                /*shallowCategoryLookup=*/false,
03504                                /*followSuper=*/false);
03505   if (!Method || !Method->isPropertyAccessor())
03506     return nullptr;
03507   if ((PDecl = Method->findPropertyDecl()))
03508     if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
03509       // property backing ivar must belong to property's class
03510       // or be a private ivar in class's implementation.
03511       // FIXME. fix the const-ness issue.
03512       IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
03513                                                         IV->getIdentifier());
03514       return IV;
03515     }
03516   return nullptr;
03517 }
03518 
03519 namespace {
03520   /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
03521   /// accessor references the backing ivar.
03522   class UnusedBackingIvarChecker :
03523       public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
03524   public:
03525     Sema &S;
03526     const ObjCMethodDecl *Method;
03527     const ObjCIvarDecl *IvarD;
03528     bool AccessedIvar;
03529     bool InvokedSelfMethod;
03530 
03531     UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
03532                              const ObjCIvarDecl *IvarD)
03533       : S(S), Method(Method), IvarD(IvarD),
03534         AccessedIvar(false), InvokedSelfMethod(false) {
03535       assert(IvarD);
03536     }
03537 
03538     bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
03539       if (E->getDecl() == IvarD) {
03540         AccessedIvar = true;
03541         return false;
03542       }
03543       return true;
03544     }
03545 
03546     bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
03547       if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
03548           S.isSelfExpr(E->getInstanceReceiver(), Method)) {
03549         InvokedSelfMethod = true;
03550       }
03551       return true;
03552     }
03553   };
03554 }
03555 
03556 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
03557                                           const ObjCImplementationDecl *ImplD) {
03558   if (S->hasUnrecoverableErrorOccurred())
03559     return;
03560 
03561   for (const auto *CurMethod : ImplD->instance_methods()) {
03562     unsigned DIAG = diag::warn_unused_property_backing_ivar;
03563     SourceLocation Loc = CurMethod->getLocation();
03564     if (Diags.isIgnored(DIAG, Loc))
03565       continue;
03566 
03567     const ObjCPropertyDecl *PDecl;
03568     const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
03569     if (!IV)
03570       continue;
03571 
03572     UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
03573     Checker.TraverseStmt(CurMethod->getBody());
03574     if (Checker.AccessedIvar)
03575       continue;
03576 
03577     // Do not issue this warning if backing ivar is used somewhere and accessor
03578     // implementation makes a self call. This is to prevent false positive in
03579     // cases where the ivar is accessed by another method that the accessor
03580     // delegates to.
03581     if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
03582       Diag(Loc, DIAG) << IV;
03583       Diag(PDecl->getLocation(), diag::note_property_declare);
03584     }
03585   }
03586 }