1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for Objective C declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DataRecursiveASTVisitor.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Sema/DeclSpec.h"
24 #include "clang/Sema/ExternalSemaSource.h"
25 #include "clang/Sema/Lookup.h"
26 #include "clang/Sema/Scope.h"
27 #include "clang/Sema/ScopeInfo.h"
28 #include "llvm/ADT/DenseSet.h"
29 
30 using namespace clang;
31 
32 /// Check whether the given method, which must be in the 'init'
33 /// family, is a valid member of that family.
34 ///
35 /// \param receiverTypeIfCall - if null, check this as if declaring it;
36 ///   if non-null, check this as if making a call to it with the given
37 ///   receiver type
38 ///
39 /// \return true to indicate that there was an error and appropriate
40 ///   actions were taken
41 bool Sema::checkInitMethod(ObjCMethodDecl *method,
42                            QualType receiverTypeIfCall) {
43   if (method->isInvalidDecl()) return true;
44 
45   // This castAs is safe: methods that don't return an object
46   // pointer won't be inferred as inits and will reject an explicit
47   // objc_method_family(init).
48 
49   // We ignore protocols here.  Should we?  What about Class?
50 
51   const ObjCObjectType *result =
52       method->getReturnType()->castAs<ObjCObjectPointerType>()->getObjectType();
53 
54   if (result->isObjCId()) {
55     return false;
56   } else if (result->isObjCClass()) {
57     // fall through: always an error
58   } else {
59     ObjCInterfaceDecl *resultClass = result->getInterface();
60     assert(resultClass && "unexpected object type!");
61 
62     // It's okay for the result type to still be a forward declaration
63     // if we're checking an interface declaration.
64     if (!resultClass->hasDefinition()) {
65       if (receiverTypeIfCall.isNull() &&
66           !isa<ObjCImplementationDecl>(method->getDeclContext()))
67         return false;
68 
69     // Otherwise, we try to compare class types.
70     } else {
71       // If this method was declared in a protocol, we can't check
72       // anything unless we have a receiver type that's an interface.
73       const ObjCInterfaceDecl *receiverClass = nullptr;
74       if (isa<ObjCProtocolDecl>(method->getDeclContext())) {
75         if (receiverTypeIfCall.isNull())
76           return false;
77 
78         receiverClass = receiverTypeIfCall->castAs<ObjCObjectPointerType>()
79           ->getInterfaceDecl();
80 
81         // This can be null for calls to e.g. id<Foo>.
82         if (!receiverClass) return false;
83       } else {
84         receiverClass = method->getClassInterface();
85         assert(receiverClass && "method not associated with a class!");
86       }
87 
88       // If either class is a subclass of the other, it's fine.
89       if (receiverClass->isSuperClassOf(resultClass) ||
90           resultClass->isSuperClassOf(receiverClass))
91         return false;
92     }
93   }
94 
95   SourceLocation loc = method->getLocation();
96 
97   // If we're in a system header, and this is not a call, just make
98   // the method unusable.
99   if (receiverTypeIfCall.isNull() && getSourceManager().isInSystemHeader(loc)) {
100     method->addAttr(UnavailableAttr::CreateImplicit(Context,
101                 "init method returns a type unrelated to its receiver type",
102                 loc));
103     return true;
104   }
105 
106   // Otherwise, it's an error.
107   Diag(loc, diag::err_arc_init_method_unrelated_result_type);
108   method->setInvalidDecl();
109   return true;
110 }
111 
112 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
113                                    const ObjCMethodDecl *Overridden) {
114   if (Overridden->hasRelatedResultType() &&
115       !NewMethod->hasRelatedResultType()) {
116     // This can only happen when the method follows a naming convention that
117     // implies a related result type, and the original (overridden) method has
118     // a suitable return type, but the new (overriding) method does not have
119     // a suitable return type.
120     QualType ResultType = NewMethod->getReturnType();
121     SourceRange ResultTypeRange = NewMethod->getReturnTypeSourceRange();
122 
123     // Figure out which class this method is part of, if any.
124     ObjCInterfaceDecl *CurrentClass
125       = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
126     if (!CurrentClass) {
127       DeclContext *DC = NewMethod->getDeclContext();
128       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
129         CurrentClass = Cat->getClassInterface();
130       else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
131         CurrentClass = Impl->getClassInterface();
132       else if (ObjCCategoryImplDecl *CatImpl
133                = dyn_cast<ObjCCategoryImplDecl>(DC))
134         CurrentClass = CatImpl->getClassInterface();
135     }
136 
137     if (CurrentClass) {
138       Diag(NewMethod->getLocation(),
139            diag::warn_related_result_type_compatibility_class)
140         << Context.getObjCInterfaceType(CurrentClass)
141         << ResultType
142         << ResultTypeRange;
143     } else {
144       Diag(NewMethod->getLocation(),
145            diag::warn_related_result_type_compatibility_protocol)
146         << ResultType
147         << ResultTypeRange;
148     }
149 
150     if (ObjCMethodFamily Family = Overridden->getMethodFamily())
151       Diag(Overridden->getLocation(),
152            diag::note_related_result_type_family)
153         << /*overridden method*/ 0
154         << Family;
155     else
156       Diag(Overridden->getLocation(),
157            diag::note_related_result_type_overridden);
158   }
159   if (getLangOpts().ObjCAutoRefCount) {
160     if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
161          Overridden->hasAttr<NSReturnsRetainedAttr>())) {
162         Diag(NewMethod->getLocation(),
163              diag::err_nsreturns_retained_attribute_mismatch) << 1;
164         Diag(Overridden->getLocation(), diag::note_previous_decl)
165         << "method";
166     }
167     if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
168               Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
169         Diag(NewMethod->getLocation(),
170              diag::err_nsreturns_retained_attribute_mismatch) << 0;
171         Diag(Overridden->getLocation(), diag::note_previous_decl)
172         << "method";
173     }
174     ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
175                                          oe = Overridden->param_end();
176     for (ObjCMethodDecl::param_iterator
177            ni = NewMethod->param_begin(), ne = NewMethod->param_end();
178          ni != ne && oi != oe; ++ni, ++oi) {
179       const ParmVarDecl *oldDecl = (*oi);
180       ParmVarDecl *newDecl = (*ni);
181       if (newDecl->hasAttr<NSConsumedAttr>() !=
182           oldDecl->hasAttr<NSConsumedAttr>()) {
183         Diag(newDecl->getLocation(),
184              diag::err_nsconsumed_attribute_mismatch);
185         Diag(oldDecl->getLocation(), diag::note_previous_decl)
186           << "parameter";
187       }
188     }
189   }
190 }
191 
192 /// \brief Check a method declaration for compatibility with the Objective-C
193 /// ARC conventions.
194 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
195   ObjCMethodFamily family = method->getMethodFamily();
196   switch (family) {
197   case OMF_None:
198   case OMF_finalize:
199   case OMF_retain:
200   case OMF_release:
201   case OMF_autorelease:
202   case OMF_retainCount:
203   case OMF_self:
204   case OMF_initialize:
205   case OMF_performSelector:
206     return false;
207 
208   case OMF_dealloc:
209     if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
210       SourceRange ResultTypeRange = method->getReturnTypeSourceRange();
211       if (ResultTypeRange.isInvalid())
212         Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
213             << method->getReturnType()
214             << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
215       else
216         Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
217             << method->getReturnType()
218             << FixItHint::CreateReplacement(ResultTypeRange, "void");
219       return true;
220     }
221     return false;
222 
223   case OMF_init:
224     // If the method doesn't obey the init rules, don't bother annotating it.
225     if (checkInitMethod(method, QualType()))
226       return true;
227 
228     method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
229 
230     // Don't add a second copy of this attribute, but otherwise don't
231     // let it be suppressed.
232     if (method->hasAttr<NSReturnsRetainedAttr>())
233       return false;
234     break;
235 
236   case OMF_alloc:
237   case OMF_copy:
238   case OMF_mutableCopy:
239   case OMF_new:
240     if (method->hasAttr<NSReturnsRetainedAttr>() ||
241         method->hasAttr<NSReturnsNotRetainedAttr>() ||
242         method->hasAttr<NSReturnsAutoreleasedAttr>())
243       return false;
244     break;
245   }
246 
247   method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
248   return false;
249 }
250 
251 static void DiagnoseObjCImplementedDeprecations(Sema &S,
252                                                 NamedDecl *ND,
253                                                 SourceLocation ImplLoc,
254                                                 int select) {
255   if (ND && ND->isDeprecated()) {
256     S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
257     if (select == 0)
258       S.Diag(ND->getLocation(), diag::note_method_declared_at)
259         << ND->getDeclName();
260     else
261       S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
262   }
263 }
264 
265 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
266 /// pool.
267 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
268   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
269 
270   // If we don't have a valid method decl, simply return.
271   if (!MDecl)
272     return;
273   if (MDecl->isInstanceMethod())
274     AddInstanceMethodToGlobalPool(MDecl, true);
275   else
276     AddFactoryMethodToGlobalPool(MDecl, true);
277 }
278 
279 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
280 /// has explicit ownership attribute; false otherwise.
281 static bool
282 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
283   QualType T = Param->getType();
284 
285   if (const PointerType *PT = T->getAs<PointerType>()) {
286     T = PT->getPointeeType();
287   } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
288     T = RT->getPointeeType();
289   } else {
290     return true;
291   }
292 
293   // If we have a lifetime qualifier, but it's local, we must have
294   // inferred it. So, it is implicit.
295   return !T.getLocalQualifiers().hasObjCLifetime();
296 }
297 
298 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
299 /// and user declared, in the method definition's AST.
300 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
301   assert((getCurMethodDecl() == nullptr) && "Methodparsing confused");
302   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
303 
304   // If we don't have a valid method decl, simply return.
305   if (!MDecl)
306     return;
307 
308   // Allow all of Sema to see that we are entering a method definition.
309   PushDeclContext(FnBodyScope, MDecl);
310   PushFunctionScope();
311 
312   // Create Decl objects for each parameter, entrring them in the scope for
313   // binding to their use.
314 
315   // Insert the invisible arguments, self and _cmd!
316   MDecl->createImplicitParams(Context, MDecl->getClassInterface());
317 
318   PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
319   PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
320 
321   // The ObjC parser requires parameter names so there's no need to check.
322   CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
323                            /*CheckParameterNames=*/false);
324 
325   // Introduce all of the other parameters into this scope.
326   for (auto *Param : MDecl->params()) {
327     if (!Param->isInvalidDecl() &&
328         getLangOpts().ObjCAutoRefCount &&
329         !HasExplicitOwnershipAttr(*this, Param))
330       Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
331             Param->getType();
332 
333     if (Param->getIdentifier())
334       PushOnScopeChains(Param, FnBodyScope);
335   }
336 
337   // In ARC, disallow definition of retain/release/autorelease/retainCount
338   if (getLangOpts().ObjCAutoRefCount) {
339     switch (MDecl->getMethodFamily()) {
340     case OMF_retain:
341     case OMF_retainCount:
342     case OMF_release:
343     case OMF_autorelease:
344       Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
345         << 0 << MDecl->getSelector();
346       break;
347 
348     case OMF_None:
349     case OMF_dealloc:
350     case OMF_finalize:
351     case OMF_alloc:
352     case OMF_init:
353     case OMF_mutableCopy:
354     case OMF_copy:
355     case OMF_new:
356     case OMF_self:
357     case OMF_initialize:
358     case OMF_performSelector:
359       break;
360     }
361   }
362 
363   // Warn on deprecated methods under -Wdeprecated-implementations,
364   // and prepare for warning on missing super calls.
365   if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
366     ObjCMethodDecl *IMD =
367       IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
368 
369     if (IMD) {
370       ObjCImplDecl *ImplDeclOfMethodDef =
371         dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
372       ObjCContainerDecl *ContDeclOfMethodDecl =
373         dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
374       ObjCImplDecl *ImplDeclOfMethodDecl = nullptr;
375       if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
376         ImplDeclOfMethodDecl = OID->getImplementation();
377       else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl)) {
378         if (CD->IsClassExtension()) {
379           if (ObjCInterfaceDecl *OID = CD->getClassInterface())
380             ImplDeclOfMethodDecl = OID->getImplementation();
381         } else
382             ImplDeclOfMethodDecl = CD->getImplementation();
383       }
384       // No need to issue deprecated warning if deprecated mehod in class/category
385       // is being implemented in its own implementation (no overriding is involved).
386       if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
387         DiagnoseObjCImplementedDeprecations(*this,
388                                           dyn_cast<NamedDecl>(IMD),
389                                           MDecl->getLocation(), 0);
390     }
391 
392     if (MDecl->getMethodFamily() == OMF_init) {
393       if (MDecl->isDesignatedInitializerForTheInterface()) {
394         getCurFunction()->ObjCIsDesignatedInit = true;
395         getCurFunction()->ObjCWarnForNoDesignatedInitChain =
396             IC->getSuperClass() != nullptr;
397       } else if (IC->hasDesignatedInitializers()) {
398         getCurFunction()->ObjCIsSecondaryInit = true;
399         getCurFunction()->ObjCWarnForNoInitDelegation = true;
400       }
401     }
402 
403     // If this is "dealloc" or "finalize", set some bit here.
404     // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
405     // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
406     // Only do this if the current class actually has a superclass.
407     if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
408       ObjCMethodFamily Family = MDecl->getMethodFamily();
409       if (Family == OMF_dealloc) {
410         if (!(getLangOpts().ObjCAutoRefCount ||
411               getLangOpts().getGC() == LangOptions::GCOnly))
412           getCurFunction()->ObjCShouldCallSuper = true;
413 
414       } else if (Family == OMF_finalize) {
415         if (Context.getLangOpts().getGC() != LangOptions::NonGC)
416           getCurFunction()->ObjCShouldCallSuper = true;
417 
418       } else {
419         const ObjCMethodDecl *SuperMethod =
420           SuperClass->lookupMethod(MDecl->getSelector(),
421                                    MDecl->isInstanceMethod());
422         getCurFunction()->ObjCShouldCallSuper =
423           (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
424       }
425     }
426   }
427 }
428 
429 namespace {
430 
431 // Callback to only accept typo corrections that are Objective-C classes.
432 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
433 // function will reject corrections to that class.
434 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
435  public:
436   ObjCInterfaceValidatorCCC() : CurrentIDecl(nullptr) {}
437   explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
438       : CurrentIDecl(IDecl) {}
439 
440   bool ValidateCandidate(const TypoCorrection &candidate) override {
441     ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
442     return ID && !declaresSameEntity(ID, CurrentIDecl);
443   }
444 
445  private:
446   ObjCInterfaceDecl *CurrentIDecl;
447 };
448 
449 }
450 
451 Decl *Sema::
452 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
453                          IdentifierInfo *ClassName, SourceLocation ClassLoc,
454                          IdentifierInfo *SuperName, SourceLocation SuperLoc,
455                          Decl * const *ProtoRefs, unsigned NumProtoRefs,
456                          const SourceLocation *ProtoLocs,
457                          SourceLocation EndProtoLoc, AttributeList *AttrList) {
458   assert(ClassName && "Missing class identifier");
459 
460   // Check for another declaration kind with the same name.
461   NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
462                                          LookupOrdinaryName, ForRedeclaration);
463 
464   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
465     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
466     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
467   }
468 
469   // Create a declaration to describe this @interface.
470   ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
471 
472   if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
473     // A previous decl with a different name is because of
474     // @compatibility_alias, for example:
475     // \code
476     //   @class NewImage;
477     //   @compatibility_alias OldImage NewImage;
478     // \endcode
479     // A lookup for 'OldImage' will return the 'NewImage' decl.
480     //
481     // In such a case use the real declaration name, instead of the alias one,
482     // otherwise we will break IdentifierResolver and redecls-chain invariants.
483     // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
484     // has been aliased.
485     ClassName = PrevIDecl->getIdentifier();
486   }
487 
488   ObjCInterfaceDecl *IDecl
489     = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
490                                 PrevIDecl, ClassLoc);
491 
492   if (PrevIDecl) {
493     // Class already seen. Was it a definition?
494     if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
495       Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
496         << PrevIDecl->getDeclName();
497       Diag(Def->getLocation(), diag::note_previous_definition);
498       IDecl->setInvalidDecl();
499     }
500   }
501 
502   if (AttrList)
503     ProcessDeclAttributeList(TUScope, IDecl, AttrList);
504   PushOnScopeChains(IDecl, TUScope);
505 
506   // Start the definition of this class. If we're in a redefinition case, there
507   // may already be a definition, so we'll end up adding to it.
508   if (!IDecl->hasDefinition())
509     IDecl->startDefinition();
510 
511   if (SuperName) {
512     // Check if a different kind of symbol declared in this scope.
513     PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
514                                 LookupOrdinaryName);
515 
516     if (!PrevDecl) {
517       // Try to correct for a typo in the superclass name without correcting
518       // to the class we're defining.
519       ObjCInterfaceValidatorCCC Validator(IDecl);
520       if (TypoCorrection Corrected = CorrectTypo(
521           DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
522           nullptr, Validator, CTK_ErrorRecovery)) {
523         diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
524                                     << SuperName << ClassName);
525         PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
526       }
527     }
528 
529     if (declaresSameEntity(PrevDecl, IDecl)) {
530       Diag(SuperLoc, diag::err_recursive_superclass)
531         << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
532       IDecl->setEndOfDefinitionLoc(ClassLoc);
533     } else {
534       ObjCInterfaceDecl *SuperClassDecl =
535                                 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
536 
537       // Diagnose classes that inherit from deprecated classes.
538       if (SuperClassDecl)
539         (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
540 
541       if (PrevDecl && !SuperClassDecl) {
542         // The previous declaration was not a class decl. Check if we have a
543         // typedef. If we do, get the underlying class type.
544         if (const TypedefNameDecl *TDecl =
545               dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
546           QualType T = TDecl->getUnderlyingType();
547           if (T->isObjCObjectType()) {
548             if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
549               SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
550               // This handles the following case:
551               // @interface NewI @end
552               // typedef NewI DeprI __attribute__((deprecated("blah")))
553               // @interface SI : DeprI /* warn here */ @end
554               (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
555             }
556           }
557         }
558 
559         // This handles the following case:
560         //
561         // typedef int SuperClass;
562         // @interface MyClass : SuperClass {} @end
563         //
564         if (!SuperClassDecl) {
565           Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
566           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
567         }
568       }
569 
570       if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
571         if (!SuperClassDecl)
572           Diag(SuperLoc, diag::err_undef_superclass)
573             << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
574         else if (RequireCompleteType(SuperLoc,
575                                   Context.getObjCInterfaceType(SuperClassDecl),
576                                      diag::err_forward_superclass,
577                                      SuperClassDecl->getDeclName(),
578                                      ClassName,
579                                      SourceRange(AtInterfaceLoc, ClassLoc))) {
580           SuperClassDecl = nullptr;
581         }
582       }
583       IDecl->setSuperClass(SuperClassDecl);
584       IDecl->setSuperClassLoc(SuperLoc);
585       IDecl->setEndOfDefinitionLoc(SuperLoc);
586     }
587   } else { // we have a root class.
588     IDecl->setEndOfDefinitionLoc(ClassLoc);
589   }
590 
591   // Check then save referenced protocols.
592   if (NumProtoRefs) {
593     IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
594                            ProtoLocs, Context);
595     IDecl->setEndOfDefinitionLoc(EndProtoLoc);
596   }
597 
598   CheckObjCDeclScope(IDecl);
599   return ActOnObjCContainerStartDefinition(IDecl);
600 }
601 
602 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
603 /// typedef'ed use for a qualified super class and adds them to the list
604 /// of the protocols.
605 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
606                                    IdentifierInfo *SuperName,
607                                    SourceLocation SuperLoc) {
608   if (!SuperName)
609     return;
610   NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
611                                       LookupOrdinaryName);
612   if (!IDecl)
613     return;
614 
615   if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
616     QualType T = TDecl->getUnderlyingType();
617     if (T->isObjCObjectType())
618       if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
619         for (auto *I : OPT->quals())
620           ProtocolRefs.push_back(I);
621   }
622 }
623 
624 /// ActOnCompatibilityAlias - this action is called after complete parsing of
625 /// a \@compatibility_alias declaration. It sets up the alias relationships.
626 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
627                                     IdentifierInfo *AliasName,
628                                     SourceLocation AliasLocation,
629                                     IdentifierInfo *ClassName,
630                                     SourceLocation ClassLocation) {
631   // Look for previous declaration of alias name
632   NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
633                                       LookupOrdinaryName, ForRedeclaration);
634   if (ADecl) {
635     Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
636     Diag(ADecl->getLocation(), diag::note_previous_declaration);
637     return nullptr;
638   }
639   // Check for class declaration
640   NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
641                                        LookupOrdinaryName, ForRedeclaration);
642   if (const TypedefNameDecl *TDecl =
643         dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
644     QualType T = TDecl->getUnderlyingType();
645     if (T->isObjCObjectType()) {
646       if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
647         ClassName = IDecl->getIdentifier();
648         CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
649                                   LookupOrdinaryName, ForRedeclaration);
650       }
651     }
652   }
653   ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
654   if (!CDecl) {
655     Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
656     if (CDeclU)
657       Diag(CDeclU->getLocation(), diag::note_previous_declaration);
658     return nullptr;
659   }
660 
661   // Everything checked out, instantiate a new alias declaration AST.
662   ObjCCompatibleAliasDecl *AliasDecl =
663     ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
664 
665   if (!CheckObjCDeclScope(AliasDecl))
666     PushOnScopeChains(AliasDecl, TUScope);
667 
668   return AliasDecl;
669 }
670 
671 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
672   IdentifierInfo *PName,
673   SourceLocation &Ploc, SourceLocation PrevLoc,
674   const ObjCList<ObjCProtocolDecl> &PList) {
675 
676   bool res = false;
677   for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
678        E = PList.end(); I != E; ++I) {
679     if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
680                                                  Ploc)) {
681       if (PDecl->getIdentifier() == PName) {
682         Diag(Ploc, diag::err_protocol_has_circular_dependency);
683         Diag(PrevLoc, diag::note_previous_definition);
684         res = true;
685       }
686 
687       if (!PDecl->hasDefinition())
688         continue;
689 
690       if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
691             PDecl->getLocation(), PDecl->getReferencedProtocols()))
692         res = true;
693     }
694   }
695   return res;
696 }
697 
698 Decl *
699 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
700                                   IdentifierInfo *ProtocolName,
701                                   SourceLocation ProtocolLoc,
702                                   Decl * const *ProtoRefs,
703                                   unsigned NumProtoRefs,
704                                   const SourceLocation *ProtoLocs,
705                                   SourceLocation EndProtoLoc,
706                                   AttributeList *AttrList) {
707   bool err = false;
708   // FIXME: Deal with AttrList.
709   assert(ProtocolName && "Missing protocol identifier");
710   ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
711                                               ForRedeclaration);
712   ObjCProtocolDecl *PDecl = nullptr;
713   if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : nullptr) {
714     // If we already have a definition, complain.
715     Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
716     Diag(Def->getLocation(), diag::note_previous_definition);
717 
718     // Create a new protocol that is completely distinct from previous
719     // declarations, and do not make this protocol available for name lookup.
720     // That way, we'll end up completely ignoring the duplicate.
721     // FIXME: Can we turn this into an error?
722     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
723                                      ProtocolLoc, AtProtoInterfaceLoc,
724                                      /*PrevDecl=*/nullptr);
725     PDecl->startDefinition();
726   } else {
727     if (PrevDecl) {
728       // Check for circular dependencies among protocol declarations. This can
729       // only happen if this protocol was forward-declared.
730       ObjCList<ObjCProtocolDecl> PList;
731       PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
732       err = CheckForwardProtocolDeclarationForCircularDependency(
733               ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
734     }
735 
736     // Create the new declaration.
737     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
738                                      ProtocolLoc, AtProtoInterfaceLoc,
739                                      /*PrevDecl=*/PrevDecl);
740 
741     PushOnScopeChains(PDecl, TUScope);
742     PDecl->startDefinition();
743   }
744 
745   if (AttrList)
746     ProcessDeclAttributeList(TUScope, PDecl, AttrList);
747 
748   // Merge attributes from previous declarations.
749   if (PrevDecl)
750     mergeDeclAttributes(PDecl, PrevDecl);
751 
752   if (!err && NumProtoRefs ) {
753     /// Check then save referenced protocols.
754     PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
755                            ProtoLocs, Context);
756   }
757 
758   CheckObjCDeclScope(PDecl);
759   return ActOnObjCContainerStartDefinition(PDecl);
760 }
761 
762 static bool NestedProtocolHasNoDefinition(ObjCProtocolDecl *PDecl,
763                                           ObjCProtocolDecl *&UndefinedProtocol) {
764   if (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()) {
765     UndefinedProtocol = PDecl;
766     return true;
767   }
768 
769   for (auto *PI : PDecl->protocols())
770     if (NestedProtocolHasNoDefinition(PI, UndefinedProtocol)) {
771       UndefinedProtocol = PI;
772       return true;
773     }
774   return false;
775 }
776 
777 /// FindProtocolDeclaration - This routine looks up protocols and
778 /// issues an error if they are not declared. It returns list of
779 /// protocol declarations in its 'Protocols' argument.
780 void
781 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
782                               const IdentifierLocPair *ProtocolId,
783                               unsigned NumProtocols,
784                               SmallVectorImpl<Decl *> &Protocols) {
785   for (unsigned i = 0; i != NumProtocols; ++i) {
786     ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
787                                              ProtocolId[i].second);
788     if (!PDecl) {
789       DeclFilterCCC<ObjCProtocolDecl> Validator;
790       TypoCorrection Corrected = CorrectTypo(
791           DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
792           LookupObjCProtocolName, TUScope, nullptr, Validator,
793           CTK_ErrorRecovery);
794       if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
795         diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
796                                     << ProtocolId[i].first);
797     }
798 
799     if (!PDecl) {
800       Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
801         << ProtocolId[i].first;
802       continue;
803     }
804     // If this is a forward protocol declaration, get its definition.
805     if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
806       PDecl = PDecl->getDefinition();
807 
808     (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
809 
810     // If this is a forward declaration and we are supposed to warn in this
811     // case, do it.
812     // FIXME: Recover nicely in the hidden case.
813     ObjCProtocolDecl *UndefinedProtocol;
814 
815     if (WarnOnDeclarations &&
816         NestedProtocolHasNoDefinition(PDecl, UndefinedProtocol)) {
817       Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
818         << ProtocolId[i].first;
819       Diag(UndefinedProtocol->getLocation(), diag::note_protocol_decl_undefined)
820         << UndefinedProtocol;
821     }
822     Protocols.push_back(PDecl);
823   }
824 }
825 
826 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
827 /// a class method in its extension.
828 ///
829 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
830                                             ObjCInterfaceDecl *ID) {
831   if (!ID)
832     return;  // Possibly due to previous error
833 
834   llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
835   for (auto *MD : ID->methods())
836     MethodMap[MD->getSelector()] = MD;
837 
838   if (MethodMap.empty())
839     return;
840   for (const auto *Method : CAT->methods()) {
841     const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
842     if (PrevMethod &&
843         (PrevMethod->isInstanceMethod() == Method->isInstanceMethod()) &&
844         !MatchTwoMethodDeclarations(Method, PrevMethod)) {
845       Diag(Method->getLocation(), diag::err_duplicate_method_decl)
846             << Method->getDeclName();
847       Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
848     }
849   }
850 }
851 
852 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
853 Sema::DeclGroupPtrTy
854 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
855                                       const IdentifierLocPair *IdentList,
856                                       unsigned NumElts,
857                                       AttributeList *attrList) {
858   SmallVector<Decl *, 8> DeclsInGroup;
859   for (unsigned i = 0; i != NumElts; ++i) {
860     IdentifierInfo *Ident = IdentList[i].first;
861     ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
862                                                 ForRedeclaration);
863     ObjCProtocolDecl *PDecl
864       = ObjCProtocolDecl::Create(Context, CurContext, Ident,
865                                  IdentList[i].second, AtProtocolLoc,
866                                  PrevDecl);
867 
868     PushOnScopeChains(PDecl, TUScope);
869     CheckObjCDeclScope(PDecl);
870 
871     if (attrList)
872       ProcessDeclAttributeList(TUScope, PDecl, attrList);
873 
874     if (PrevDecl)
875       mergeDeclAttributes(PDecl, PrevDecl);
876 
877     DeclsInGroup.push_back(PDecl);
878   }
879 
880   return BuildDeclaratorGroup(DeclsInGroup, false);
881 }
882 
883 Decl *Sema::
884 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
885                             IdentifierInfo *ClassName, SourceLocation ClassLoc,
886                             IdentifierInfo *CategoryName,
887                             SourceLocation CategoryLoc,
888                             Decl * const *ProtoRefs,
889                             unsigned NumProtoRefs,
890                             const SourceLocation *ProtoLocs,
891                             SourceLocation EndProtoLoc) {
892   ObjCCategoryDecl *CDecl;
893   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
894 
895   /// Check that class of this category is already completely declared.
896 
897   if (!IDecl
898       || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
899                              diag::err_category_forward_interface,
900                              CategoryName == nullptr)) {
901     // Create an invalid ObjCCategoryDecl to serve as context for
902     // the enclosing method declarations.  We mark the decl invalid
903     // to make it clear that this isn't a valid AST.
904     CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
905                                      ClassLoc, CategoryLoc, CategoryName,IDecl);
906     CDecl->setInvalidDecl();
907     CurContext->addDecl(CDecl);
908 
909     if (!IDecl)
910       Diag(ClassLoc, diag::err_undef_interface) << ClassName;
911     return ActOnObjCContainerStartDefinition(CDecl);
912   }
913 
914   if (!CategoryName && IDecl->getImplementation()) {
915     Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
916     Diag(IDecl->getImplementation()->getLocation(),
917           diag::note_implementation_declared);
918   }
919 
920   if (CategoryName) {
921     /// Check for duplicate interface declaration for this category
922     if (ObjCCategoryDecl *Previous
923           = IDecl->FindCategoryDeclaration(CategoryName)) {
924       // Class extensions can be declared multiple times, categories cannot.
925       Diag(CategoryLoc, diag::warn_dup_category_def)
926         << ClassName << CategoryName;
927       Diag(Previous->getLocation(), diag::note_previous_definition);
928     }
929   }
930 
931   CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
932                                    ClassLoc, CategoryLoc, CategoryName, IDecl);
933   // FIXME: PushOnScopeChains?
934   CurContext->addDecl(CDecl);
935 
936   if (NumProtoRefs) {
937     CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
938                            ProtoLocs, Context);
939     // Protocols in the class extension belong to the class.
940     if (CDecl->IsClassExtension())
941      IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
942                                             NumProtoRefs, Context);
943   }
944 
945   CheckObjCDeclScope(CDecl);
946   return ActOnObjCContainerStartDefinition(CDecl);
947 }
948 
949 /// ActOnStartCategoryImplementation - Perform semantic checks on the
950 /// category implementation declaration and build an ObjCCategoryImplDecl
951 /// object.
952 Decl *Sema::ActOnStartCategoryImplementation(
953                       SourceLocation AtCatImplLoc,
954                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
955                       IdentifierInfo *CatName, SourceLocation CatLoc) {
956   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
957   ObjCCategoryDecl *CatIDecl = nullptr;
958   if (IDecl && IDecl->hasDefinition()) {
959     CatIDecl = IDecl->FindCategoryDeclaration(CatName);
960     if (!CatIDecl) {
961       // Category @implementation with no corresponding @interface.
962       // Create and install one.
963       CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
964                                           ClassLoc, CatLoc,
965                                           CatName, IDecl);
966       CatIDecl->setImplicit();
967     }
968   }
969 
970   ObjCCategoryImplDecl *CDecl =
971     ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
972                                  ClassLoc, AtCatImplLoc, CatLoc);
973   /// Check that class of this category is already completely declared.
974   if (!IDecl) {
975     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
976     CDecl->setInvalidDecl();
977   } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
978                                  diag::err_undef_interface)) {
979     CDecl->setInvalidDecl();
980   }
981 
982   // FIXME: PushOnScopeChains?
983   CurContext->addDecl(CDecl);
984 
985   // If the interface is deprecated/unavailable, warn/error about it.
986   if (IDecl)
987     DiagnoseUseOfDecl(IDecl, ClassLoc);
988 
989   /// Check that CatName, category name, is not used in another implementation.
990   if (CatIDecl) {
991     if (CatIDecl->getImplementation()) {
992       Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
993         << CatName;
994       Diag(CatIDecl->getImplementation()->getLocation(),
995            diag::note_previous_definition);
996       CDecl->setInvalidDecl();
997     } else {
998       CatIDecl->setImplementation(CDecl);
999       // Warn on implementating category of deprecated class under
1000       // -Wdeprecated-implementations flag.
1001       DiagnoseObjCImplementedDeprecations(*this,
1002                                           dyn_cast<NamedDecl>(IDecl),
1003                                           CDecl->getLocation(), 2);
1004     }
1005   }
1006 
1007   CheckObjCDeclScope(CDecl);
1008   return ActOnObjCContainerStartDefinition(CDecl);
1009 }
1010 
1011 Decl *Sema::ActOnStartClassImplementation(
1012                       SourceLocation AtClassImplLoc,
1013                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
1014                       IdentifierInfo *SuperClassname,
1015                       SourceLocation SuperClassLoc) {
1016   ObjCInterfaceDecl *IDecl = nullptr;
1017   // Check for another declaration kind with the same name.
1018   NamedDecl *PrevDecl
1019     = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1020                        ForRedeclaration);
1021   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1022     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1023     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1024   } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1025     RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1026                         diag::warn_undef_interface);
1027   } else {
1028     // We did not find anything with the name ClassName; try to correct for
1029     // typos in the class name.
1030     ObjCInterfaceValidatorCCC Validator;
1031     TypoCorrection Corrected =
1032             CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
1033                         LookupOrdinaryName, TUScope, nullptr, Validator,
1034                         CTK_NonError);
1035     if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1036       // Suggest the (potentially) correct interface name. Don't provide a
1037       // code-modification hint or use the typo name for recovery, because
1038       // this is just a warning. The program may actually be correct.
1039       diagnoseTypo(Corrected,
1040                    PDiag(diag::warn_undef_interface_suggest) << ClassName,
1041                    /*ErrorRecovery*/false);
1042     } else {
1043       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1044     }
1045   }
1046 
1047   // Check that super class name is valid class name
1048   ObjCInterfaceDecl *SDecl = nullptr;
1049   if (SuperClassname) {
1050     // Check if a different kind of symbol declared in this scope.
1051     PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1052                                 LookupOrdinaryName);
1053     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1054       Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1055         << SuperClassname;
1056       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1057     } else {
1058       SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1059       if (SDecl && !SDecl->hasDefinition())
1060         SDecl = nullptr;
1061       if (!SDecl)
1062         Diag(SuperClassLoc, diag::err_undef_superclass)
1063           << SuperClassname << ClassName;
1064       else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1065         // This implementation and its interface do not have the same
1066         // super class.
1067         Diag(SuperClassLoc, diag::err_conflicting_super_class)
1068           << SDecl->getDeclName();
1069         Diag(SDecl->getLocation(), diag::note_previous_definition);
1070       }
1071     }
1072   }
1073 
1074   if (!IDecl) {
1075     // Legacy case of @implementation with no corresponding @interface.
1076     // Build, chain & install the interface decl into the identifier.
1077 
1078     // FIXME: Do we support attributes on the @implementation? If so we should
1079     // copy them over.
1080     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1081                                       ClassName, /*PrevDecl=*/nullptr, ClassLoc,
1082                                       true);
1083     IDecl->startDefinition();
1084     if (SDecl) {
1085       IDecl->setSuperClass(SDecl);
1086       IDecl->setSuperClassLoc(SuperClassLoc);
1087       IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1088     } else {
1089       IDecl->setEndOfDefinitionLoc(ClassLoc);
1090     }
1091 
1092     PushOnScopeChains(IDecl, TUScope);
1093   } else {
1094     // Mark the interface as being completed, even if it was just as
1095     //   @class ....;
1096     // declaration; the user cannot reopen it.
1097     if (!IDecl->hasDefinition())
1098       IDecl->startDefinition();
1099   }
1100 
1101   ObjCImplementationDecl* IMPDecl =
1102     ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1103                                    ClassLoc, AtClassImplLoc, SuperClassLoc);
1104 
1105   if (CheckObjCDeclScope(IMPDecl))
1106     return ActOnObjCContainerStartDefinition(IMPDecl);
1107 
1108   // Check that there is no duplicate implementation of this class.
1109   if (IDecl->getImplementation()) {
1110     // FIXME: Don't leak everything!
1111     Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1112     Diag(IDecl->getImplementation()->getLocation(),
1113          diag::note_previous_definition);
1114     IMPDecl->setInvalidDecl();
1115   } else { // add it to the list.
1116     IDecl->setImplementation(IMPDecl);
1117     PushOnScopeChains(IMPDecl, TUScope);
1118     // Warn on implementating deprecated class under
1119     // -Wdeprecated-implementations flag.
1120     DiagnoseObjCImplementedDeprecations(*this,
1121                                         dyn_cast<NamedDecl>(IDecl),
1122                                         IMPDecl->getLocation(), 1);
1123   }
1124   return ActOnObjCContainerStartDefinition(IMPDecl);
1125 }
1126 
1127 Sema::DeclGroupPtrTy
1128 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1129   SmallVector<Decl *, 64> DeclsInGroup;
1130   DeclsInGroup.reserve(Decls.size() + 1);
1131 
1132   for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1133     Decl *Dcl = Decls[i];
1134     if (!Dcl)
1135       continue;
1136     if (Dcl->getDeclContext()->isFileContext())
1137       Dcl->setTopLevelDeclInObjCContainer();
1138     DeclsInGroup.push_back(Dcl);
1139   }
1140 
1141   DeclsInGroup.push_back(ObjCImpDecl);
1142 
1143   return BuildDeclaratorGroup(DeclsInGroup, false);
1144 }
1145 
1146 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1147                                     ObjCIvarDecl **ivars, unsigned numIvars,
1148                                     SourceLocation RBrace) {
1149   assert(ImpDecl && "missing implementation decl");
1150   ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
1151   if (!IDecl)
1152     return;
1153   /// Check case of non-existing \@interface decl.
1154   /// (legacy objective-c \@implementation decl without an \@interface decl).
1155   /// Add implementations's ivar to the synthesize class's ivar list.
1156   if (IDecl->isImplicitInterfaceDecl()) {
1157     IDecl->setEndOfDefinitionLoc(RBrace);
1158     // Add ivar's to class's DeclContext.
1159     for (unsigned i = 0, e = numIvars; i != e; ++i) {
1160       ivars[i]->setLexicalDeclContext(ImpDecl);
1161       IDecl->makeDeclVisibleInContext(ivars[i]);
1162       ImpDecl->addDecl(ivars[i]);
1163     }
1164 
1165     return;
1166   }
1167   // If implementation has empty ivar list, just return.
1168   if (numIvars == 0)
1169     return;
1170 
1171   assert(ivars && "missing @implementation ivars");
1172   if (LangOpts.ObjCRuntime.isNonFragile()) {
1173     if (ImpDecl->getSuperClass())
1174       Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1175     for (unsigned i = 0; i < numIvars; i++) {
1176       ObjCIvarDecl* ImplIvar = ivars[i];
1177       if (const ObjCIvarDecl *ClsIvar =
1178             IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1179         Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1180         Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1181         continue;
1182       }
1183       // Check class extensions (unnamed categories) for duplicate ivars.
1184       for (const auto *CDecl : IDecl->visible_extensions()) {
1185         if (const ObjCIvarDecl *ClsExtIvar =
1186             CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1187           Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1188           Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
1189           continue;
1190         }
1191       }
1192       // Instance ivar to Implementation's DeclContext.
1193       ImplIvar->setLexicalDeclContext(ImpDecl);
1194       IDecl->makeDeclVisibleInContext(ImplIvar);
1195       ImpDecl->addDecl(ImplIvar);
1196     }
1197     return;
1198   }
1199   // Check interface's Ivar list against those in the implementation.
1200   // names and types must match.
1201   //
1202   unsigned j = 0;
1203   ObjCInterfaceDecl::ivar_iterator
1204     IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1205   for (; numIvars > 0 && IVI != IVE; ++IVI) {
1206     ObjCIvarDecl* ImplIvar = ivars[j++];
1207     ObjCIvarDecl* ClsIvar = *IVI;
1208     assert (ImplIvar && "missing implementation ivar");
1209     assert (ClsIvar && "missing class ivar");
1210 
1211     // First, make sure the types match.
1212     if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1213       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1214         << ImplIvar->getIdentifier()
1215         << ImplIvar->getType() << ClsIvar->getType();
1216       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1217     } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1218                ImplIvar->getBitWidthValue(Context) !=
1219                ClsIvar->getBitWidthValue(Context)) {
1220       Diag(ImplIvar->getBitWidth()->getLocStart(),
1221            diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1222       Diag(ClsIvar->getBitWidth()->getLocStart(),
1223            diag::note_previous_definition);
1224     }
1225     // Make sure the names are identical.
1226     if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1227       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1228         << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1229       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1230     }
1231     --numIvars;
1232   }
1233 
1234   if (numIvars > 0)
1235     Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
1236   else if (IVI != IVE)
1237     Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
1238 }
1239 
1240 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
1241                                 ObjCMethodDecl *method,
1242                                 bool &IncompleteImpl,
1243                                 unsigned DiagID,
1244                                 NamedDecl *NeededFor = nullptr) {
1245   // No point warning no definition of method which is 'unavailable'.
1246   switch (method->getAvailability()) {
1247   case AR_Available:
1248   case AR_Deprecated:
1249     break;
1250 
1251       // Don't warn about unavailable or not-yet-introduced methods.
1252   case AR_NotYetIntroduced:
1253   case AR_Unavailable:
1254     return;
1255   }
1256 
1257   // FIXME: For now ignore 'IncompleteImpl'.
1258   // Previously we grouped all unimplemented methods under a single
1259   // warning, but some users strongly voiced that they would prefer
1260   // separate warnings.  We will give that approach a try, as that
1261   // matches what we do with protocols.
1262   {
1263     const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
1264     B << method;
1265     if (NeededFor)
1266       B << NeededFor;
1267   }
1268 
1269   // Issue a note to the original declaration.
1270   SourceLocation MethodLoc = method->getLocStart();
1271   if (MethodLoc.isValid())
1272     S.Diag(MethodLoc, diag::note_method_declared_at) << method;
1273 }
1274 
1275 /// Determines if type B can be substituted for type A.  Returns true if we can
1276 /// guarantee that anything that the user will do to an object of type A can
1277 /// also be done to an object of type B.  This is trivially true if the two
1278 /// types are the same, or if B is a subclass of A.  It becomes more complex
1279 /// in cases where protocols are involved.
1280 ///
1281 /// Object types in Objective-C describe the minimum requirements for an
1282 /// object, rather than providing a complete description of a type.  For
1283 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1284 /// The principle of substitutability means that we may use an instance of A
1285 /// anywhere that we may use an instance of B - it will implement all of the
1286 /// ivars of B and all of the methods of B.
1287 ///
1288 /// This substitutability is important when type checking methods, because
1289 /// the implementation may have stricter type definitions than the interface.
1290 /// The interface specifies minimum requirements, but the implementation may
1291 /// have more accurate ones.  For example, a method may privately accept
1292 /// instances of B, but only publish that it accepts instances of A.  Any
1293 /// object passed to it will be type checked against B, and so will implicitly
1294 /// by a valid A*.  Similarly, a method may return a subclass of the class that
1295 /// it is declared as returning.
1296 ///
1297 /// This is most important when considering subclassing.  A method in a
1298 /// subclass must accept any object as an argument that its superclass's
1299 /// implementation accepts.  It may, however, accept a more general type
1300 /// without breaking substitutability (i.e. you can still use the subclass
1301 /// anywhere that you can use the superclass, but not vice versa).  The
1302 /// converse requirement applies to return types: the return type for a
1303 /// subclass method must be a valid object of the kind that the superclass
1304 /// advertises, but it may be specified more accurately.  This avoids the need
1305 /// for explicit down-casting by callers.
1306 ///
1307 /// Note: This is a stricter requirement than for assignment.
1308 static bool isObjCTypeSubstitutable(ASTContext &Context,
1309                                     const ObjCObjectPointerType *A,
1310                                     const ObjCObjectPointerType *B,
1311                                     bool rejectId) {
1312   // Reject a protocol-unqualified id.
1313   if (rejectId && B->isObjCIdType()) return false;
1314 
1315   // If B is a qualified id, then A must also be a qualified id and it must
1316   // implement all of the protocols in B.  It may not be a qualified class.
1317   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1318   // stricter definition so it is not substitutable for id<A>.
1319   if (B->isObjCQualifiedIdType()) {
1320     return A->isObjCQualifiedIdType() &&
1321            Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1322                                                      QualType(B,0),
1323                                                      false);
1324   }
1325 
1326   /*
1327   // id is a special type that bypasses type checking completely.  We want a
1328   // warning when it is used in one place but not another.
1329   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1330 
1331 
1332   // If B is a qualified id, then A must also be a qualified id (which it isn't
1333   // if we've got this far)
1334   if (B->isObjCQualifiedIdType()) return false;
1335   */
1336 
1337   // Now we know that A and B are (potentially-qualified) class types.  The
1338   // normal rules for assignment apply.
1339   return Context.canAssignObjCInterfaces(A, B);
1340 }
1341 
1342 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1343   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1344 }
1345 
1346 static bool CheckMethodOverrideReturn(Sema &S,
1347                                       ObjCMethodDecl *MethodImpl,
1348                                       ObjCMethodDecl *MethodDecl,
1349                                       bool IsProtocolMethodDecl,
1350                                       bool IsOverridingMode,
1351                                       bool Warn) {
1352   if (IsProtocolMethodDecl &&
1353       (MethodDecl->getObjCDeclQualifier() !=
1354        MethodImpl->getObjCDeclQualifier())) {
1355     if (Warn) {
1356       S.Diag(MethodImpl->getLocation(),
1357              (IsOverridingMode
1358                   ? diag::warn_conflicting_overriding_ret_type_modifiers
1359                   : diag::warn_conflicting_ret_type_modifiers))
1360           << MethodImpl->getDeclName()
1361           << MethodImpl->getReturnTypeSourceRange();
1362       S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1363           << MethodDecl->getReturnTypeSourceRange();
1364     }
1365     else
1366       return false;
1367   }
1368 
1369   if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
1370                                        MethodDecl->getReturnType()))
1371     return true;
1372   if (!Warn)
1373     return false;
1374 
1375   unsigned DiagID =
1376     IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1377                      : diag::warn_conflicting_ret_types;
1378 
1379   // Mismatches between ObjC pointers go into a different warning
1380   // category, and sometimes they're even completely whitelisted.
1381   if (const ObjCObjectPointerType *ImplPtrTy =
1382           MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1383     if (const ObjCObjectPointerType *IfacePtrTy =
1384             MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1385       // Allow non-matching return types as long as they don't violate
1386       // the principle of substitutability.  Specifically, we permit
1387       // return types that are subclasses of the declared return type,
1388       // or that are more-qualified versions of the declared type.
1389       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1390         return false;
1391 
1392       DiagID =
1393         IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1394                           : diag::warn_non_covariant_ret_types;
1395     }
1396   }
1397 
1398   S.Diag(MethodImpl->getLocation(), DiagID)
1399       << MethodImpl->getDeclName() << MethodDecl->getReturnType()
1400       << MethodImpl->getReturnType()
1401       << MethodImpl->getReturnTypeSourceRange();
1402   S.Diag(MethodDecl->getLocation(), IsOverridingMode
1403                                         ? diag::note_previous_declaration
1404                                         : diag::note_previous_definition)
1405       << MethodDecl->getReturnTypeSourceRange();
1406   return false;
1407 }
1408 
1409 static bool CheckMethodOverrideParam(Sema &S,
1410                                      ObjCMethodDecl *MethodImpl,
1411                                      ObjCMethodDecl *MethodDecl,
1412                                      ParmVarDecl *ImplVar,
1413                                      ParmVarDecl *IfaceVar,
1414                                      bool IsProtocolMethodDecl,
1415                                      bool IsOverridingMode,
1416                                      bool Warn) {
1417   if (IsProtocolMethodDecl &&
1418       (ImplVar->getObjCDeclQualifier() !=
1419        IfaceVar->getObjCDeclQualifier())) {
1420     if (Warn) {
1421       if (IsOverridingMode)
1422         S.Diag(ImplVar->getLocation(),
1423                diag::warn_conflicting_overriding_param_modifiers)
1424             << getTypeRange(ImplVar->getTypeSourceInfo())
1425             << MethodImpl->getDeclName();
1426       else S.Diag(ImplVar->getLocation(),
1427              diag::warn_conflicting_param_modifiers)
1428           << getTypeRange(ImplVar->getTypeSourceInfo())
1429           << MethodImpl->getDeclName();
1430       S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1431           << getTypeRange(IfaceVar->getTypeSourceInfo());
1432     }
1433     else
1434       return false;
1435   }
1436 
1437   QualType ImplTy = ImplVar->getType();
1438   QualType IfaceTy = IfaceVar->getType();
1439 
1440   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1441     return true;
1442 
1443   if (!Warn)
1444     return false;
1445   unsigned DiagID =
1446     IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1447                      : diag::warn_conflicting_param_types;
1448 
1449   // Mismatches between ObjC pointers go into a different warning
1450   // category, and sometimes they're even completely whitelisted.
1451   if (const ObjCObjectPointerType *ImplPtrTy =
1452         ImplTy->getAs<ObjCObjectPointerType>()) {
1453     if (const ObjCObjectPointerType *IfacePtrTy =
1454           IfaceTy->getAs<ObjCObjectPointerType>()) {
1455       // Allow non-matching argument types as long as they don't
1456       // violate the principle of substitutability.  Specifically, the
1457       // implementation must accept any objects that the superclass
1458       // accepts, however it may also accept others.
1459       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1460         return false;
1461 
1462       DiagID =
1463       IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1464                        :  diag::warn_non_contravariant_param_types;
1465     }
1466   }
1467 
1468   S.Diag(ImplVar->getLocation(), DiagID)
1469     << getTypeRange(ImplVar->getTypeSourceInfo())
1470     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1471   S.Diag(IfaceVar->getLocation(),
1472          (IsOverridingMode ? diag::note_previous_declaration
1473                         : diag::note_previous_definition))
1474     << getTypeRange(IfaceVar->getTypeSourceInfo());
1475   return false;
1476 }
1477 
1478 /// In ARC, check whether the conventional meanings of the two methods
1479 /// match.  If they don't, it's a hard error.
1480 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1481                                       ObjCMethodDecl *decl) {
1482   ObjCMethodFamily implFamily = impl->getMethodFamily();
1483   ObjCMethodFamily declFamily = decl->getMethodFamily();
1484   if (implFamily == declFamily) return false;
1485 
1486   // Since conventions are sorted by selector, the only possibility is
1487   // that the types differ enough to cause one selector or the other
1488   // to fall out of the family.
1489   assert(implFamily == OMF_None || declFamily == OMF_None);
1490 
1491   // No further diagnostics required on invalid declarations.
1492   if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1493 
1494   const ObjCMethodDecl *unmatched = impl;
1495   ObjCMethodFamily family = declFamily;
1496   unsigned errorID = diag::err_arc_lost_method_convention;
1497   unsigned noteID = diag::note_arc_lost_method_convention;
1498   if (declFamily == OMF_None) {
1499     unmatched = decl;
1500     family = implFamily;
1501     errorID = diag::err_arc_gained_method_convention;
1502     noteID = diag::note_arc_gained_method_convention;
1503   }
1504 
1505   // Indexes into a %select clause in the diagnostic.
1506   enum FamilySelector {
1507     F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1508   };
1509   FamilySelector familySelector = FamilySelector();
1510 
1511   switch (family) {
1512   case OMF_None: llvm_unreachable("logic error, no method convention");
1513   case OMF_retain:
1514   case OMF_release:
1515   case OMF_autorelease:
1516   case OMF_dealloc:
1517   case OMF_finalize:
1518   case OMF_retainCount:
1519   case OMF_self:
1520   case OMF_initialize:
1521   case OMF_performSelector:
1522     // Mismatches for these methods don't change ownership
1523     // conventions, so we don't care.
1524     return false;
1525 
1526   case OMF_init: familySelector = F_init; break;
1527   case OMF_alloc: familySelector = F_alloc; break;
1528   case OMF_copy: familySelector = F_copy; break;
1529   case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1530   case OMF_new: familySelector = F_new; break;
1531   }
1532 
1533   enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1534   ReasonSelector reasonSelector;
1535 
1536   // The only reason these methods don't fall within their families is
1537   // due to unusual result types.
1538   if (unmatched->getReturnType()->isObjCObjectPointerType()) {
1539     reasonSelector = R_UnrelatedReturn;
1540   } else {
1541     reasonSelector = R_NonObjectReturn;
1542   }
1543 
1544   S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
1545   S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
1546 
1547   return true;
1548 }
1549 
1550 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1551                                        ObjCMethodDecl *MethodDecl,
1552                                        bool IsProtocolMethodDecl) {
1553   if (getLangOpts().ObjCAutoRefCount &&
1554       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1555     return;
1556 
1557   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1558                             IsProtocolMethodDecl, false,
1559                             true);
1560 
1561   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1562        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1563        EF = MethodDecl->param_end();
1564        IM != EM && IF != EF; ++IM, ++IF) {
1565     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1566                              IsProtocolMethodDecl, false, true);
1567   }
1568 
1569   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1570     Diag(ImpMethodDecl->getLocation(),
1571          diag::warn_conflicting_variadic);
1572     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1573   }
1574 }
1575 
1576 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1577                                        ObjCMethodDecl *Overridden,
1578                                        bool IsProtocolMethodDecl) {
1579 
1580   CheckMethodOverrideReturn(*this, Method, Overridden,
1581                             IsProtocolMethodDecl, true,
1582                             true);
1583 
1584   for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1585        IF = Overridden->param_begin(), EM = Method->param_end(),
1586        EF = Overridden->param_end();
1587        IM != EM && IF != EF; ++IM, ++IF) {
1588     CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1589                              IsProtocolMethodDecl, true, true);
1590   }
1591 
1592   if (Method->isVariadic() != Overridden->isVariadic()) {
1593     Diag(Method->getLocation(),
1594          diag::warn_conflicting_overriding_variadic);
1595     Diag(Overridden->getLocation(), diag::note_previous_declaration);
1596   }
1597 }
1598 
1599 /// WarnExactTypedMethods - This routine issues a warning if method
1600 /// implementation declaration matches exactly that of its declaration.
1601 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1602                                  ObjCMethodDecl *MethodDecl,
1603                                  bool IsProtocolMethodDecl) {
1604   // don't issue warning when protocol method is optional because primary
1605   // class is not required to implement it and it is safe for protocol
1606   // to implement it.
1607   if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1608     return;
1609   // don't issue warning when primary class's method is
1610   // depecated/unavailable.
1611   if (MethodDecl->hasAttr<UnavailableAttr>() ||
1612       MethodDecl->hasAttr<DeprecatedAttr>())
1613     return;
1614 
1615   bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1616                                       IsProtocolMethodDecl, false, false);
1617   if (match)
1618     for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1619          IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1620          EF = MethodDecl->param_end();
1621          IM != EM && IF != EF; ++IM, ++IF) {
1622       match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1623                                        *IM, *IF,
1624                                        IsProtocolMethodDecl, false, false);
1625       if (!match)
1626         break;
1627     }
1628   if (match)
1629     match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1630   if (match)
1631     match = !(MethodDecl->isClassMethod() &&
1632               MethodDecl->getSelector() == GetNullarySelector("load", Context));
1633 
1634   if (match) {
1635     Diag(ImpMethodDecl->getLocation(),
1636          diag::warn_category_method_impl_match);
1637     Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1638       << MethodDecl->getDeclName();
1639   }
1640 }
1641 
1642 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1643 /// improve the efficiency of selector lookups and type checking by associating
1644 /// with each protocol / interface / category the flattened instance tables. If
1645 /// we used an immutable set to keep the table then it wouldn't add significant
1646 /// memory cost and it would be handy for lookups.
1647 
1648 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
1649 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
1650 
1651 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
1652                                            ProtocolNameSet &PNS) {
1653   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
1654     PNS.insert(PDecl->getIdentifier());
1655   for (const auto *PI : PDecl->protocols())
1656     findProtocolsWithExplicitImpls(PI, PNS);
1657 }
1658 
1659 /// Recursively populates a set with all conformed protocols in a class
1660 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
1661 /// attribute.
1662 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
1663                                            ProtocolNameSet &PNS) {
1664   if (!Super)
1665     return;
1666 
1667   for (const auto *I : Super->all_referenced_protocols())
1668     findProtocolsWithExplicitImpls(I, PNS);
1669 
1670   findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
1671 }
1672 
1673 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1674 /// Declared in protocol, and those referenced by it.
1675 static void CheckProtocolMethodDefs(Sema &S,
1676                                     SourceLocation ImpLoc,
1677                                     ObjCProtocolDecl *PDecl,
1678                                     bool& IncompleteImpl,
1679                                     const Sema::SelectorSet &InsMap,
1680                                     const Sema::SelectorSet &ClsMap,
1681                                     ObjCContainerDecl *CDecl,
1682                                     LazyProtocolNameSet &ProtocolsExplictImpl) {
1683   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1684   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1685                                : dyn_cast<ObjCInterfaceDecl>(CDecl);
1686   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1687 
1688   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1689   ObjCInterfaceDecl *NSIDecl = nullptr;
1690 
1691   // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
1692   // then we should check if any class in the super class hierarchy also
1693   // conforms to this protocol, either directly or via protocol inheritance.
1694   // If so, we can skip checking this protocol completely because we
1695   // know that a parent class already satisfies this protocol.
1696   //
1697   // Note: we could generalize this logic for all protocols, and merely
1698   // add the limit on looking at the super class chain for just
1699   // specially marked protocols.  This may be a good optimization.  This
1700   // change is restricted to 'objc_protocol_requires_explicit_implementation'
1701   // protocols for now for controlled evaluation.
1702   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
1703     if (!ProtocolsExplictImpl) {
1704       ProtocolsExplictImpl.reset(new ProtocolNameSet);
1705       findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
1706     }
1707     if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
1708         ProtocolsExplictImpl->end())
1709       return;
1710 
1711     // If no super class conforms to the protocol, we should not search
1712     // for methods in the super class to implicitly satisfy the protocol.
1713     Super = nullptr;
1714   }
1715 
1716   if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
1717     // check to see if class implements forwardInvocation method and objects
1718     // of this class are derived from 'NSProxy' so that to forward requests
1719     // from one object to another.
1720     // Under such conditions, which means that every method possible is
1721     // implemented in the class, we should not issue "Method definition not
1722     // found" warnings.
1723     // FIXME: Use a general GetUnarySelector method for this.
1724     IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
1725     Selector fISelector = S.Context.Selectors.getSelector(1, &II);
1726     if (InsMap.count(fISelector))
1727       // Is IDecl derived from 'NSProxy'? If so, no instance methods
1728       // need be implemented in the implementation.
1729       NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
1730   }
1731 
1732   // If this is a forward protocol declaration, get its definition.
1733   if (!PDecl->isThisDeclarationADefinition() &&
1734       PDecl->getDefinition())
1735     PDecl = PDecl->getDefinition();
1736 
1737   // If a method lookup fails locally we still need to look and see if
1738   // the method was implemented by a base class or an inherited
1739   // protocol. This lookup is slow, but occurs rarely in correct code
1740   // and otherwise would terminate in a warning.
1741 
1742   // check unimplemented instance methods.
1743   if (!NSIDecl)
1744     for (auto *method : PDecl->instance_methods()) {
1745       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1746           !method->isPropertyAccessor() &&
1747           !InsMap.count(method->getSelector()) &&
1748           (!Super || !Super->lookupMethod(method->getSelector(),
1749                                           true /* instance */,
1750                                           false /* shallowCategory */,
1751                                           true /* followsSuper */,
1752                                           nullptr /* category */))) {
1753             // If a method is not implemented in the category implementation but
1754             // has been declared in its primary class, superclass,
1755             // or in one of their protocols, no need to issue the warning.
1756             // This is because method will be implemented in the primary class
1757             // or one of its super class implementation.
1758 
1759             // Ugly, but necessary. Method declared in protcol might have
1760             // have been synthesized due to a property declared in the class which
1761             // uses the protocol.
1762             if (ObjCMethodDecl *MethodInClass =
1763                   IDecl->lookupMethod(method->getSelector(),
1764                                       true /* instance */,
1765                                       true /* shallowCategoryLookup */,
1766                                       false /* followSuper */))
1767               if (C || MethodInClass->isPropertyAccessor())
1768                 continue;
1769             unsigned DIAG = diag::warn_unimplemented_protocol_method;
1770             if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1771               WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
1772                                   PDecl);
1773             }
1774           }
1775     }
1776   // check unimplemented class methods
1777   for (auto *method : PDecl->class_methods()) {
1778     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1779         !ClsMap.count(method->getSelector()) &&
1780         (!Super || !Super->lookupMethod(method->getSelector(),
1781                                         false /* class method */,
1782                                         false /* shallowCategoryLookup */,
1783                                         true  /* followSuper */,
1784                                         nullptr /* category */))) {
1785       // See above comment for instance method lookups.
1786       if (C && IDecl->lookupMethod(method->getSelector(),
1787                                    false /* class */,
1788                                    true /* shallowCategoryLookup */,
1789                                    false /* followSuper */))
1790         continue;
1791 
1792       unsigned DIAG = diag::warn_unimplemented_protocol_method;
1793       if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1794         WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
1795       }
1796     }
1797   }
1798   // Check on this protocols's referenced protocols, recursively.
1799   for (auto *PI : PDecl->protocols())
1800     CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
1801                             CDecl, ProtocolsExplictImpl);
1802 }
1803 
1804 /// MatchAllMethodDeclarations - Check methods declared in interface
1805 /// or protocol against those declared in their implementations.
1806 ///
1807 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1808                                       const SelectorSet &ClsMap,
1809                                       SelectorSet &InsMapSeen,
1810                                       SelectorSet &ClsMapSeen,
1811                                       ObjCImplDecl* IMPDecl,
1812                                       ObjCContainerDecl* CDecl,
1813                                       bool &IncompleteImpl,
1814                                       bool ImmediateClass,
1815                                       bool WarnCategoryMethodImpl) {
1816   // Check and see if instance methods in class interface have been
1817   // implemented in the implementation class. If so, their types match.
1818   for (auto *I : CDecl->instance_methods()) {
1819     if (!InsMapSeen.insert(I->getSelector()))
1820       continue;
1821     if (!I->isPropertyAccessor() &&
1822         !InsMap.count(I->getSelector())) {
1823       if (ImmediateClass)
1824         WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1825                             diag::warn_undef_method_impl);
1826       continue;
1827     } else {
1828       ObjCMethodDecl *ImpMethodDecl =
1829         IMPDecl->getInstanceMethod(I->getSelector());
1830       assert(CDecl->getInstanceMethod(I->getSelector()) &&
1831              "Expected to find the method through lookup as well");
1832       // ImpMethodDecl may be null as in a @dynamic property.
1833       if (ImpMethodDecl) {
1834         if (!WarnCategoryMethodImpl)
1835           WarnConflictingTypedMethods(ImpMethodDecl, I,
1836                                       isa<ObjCProtocolDecl>(CDecl));
1837         else if (!I->isPropertyAccessor())
1838           WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
1839       }
1840     }
1841   }
1842 
1843   // Check and see if class methods in class interface have been
1844   // implemented in the implementation class. If so, their types match.
1845   for (auto *I : CDecl->class_methods()) {
1846     if (!ClsMapSeen.insert(I->getSelector()))
1847       continue;
1848     if (!ClsMap.count(I->getSelector())) {
1849       if (ImmediateClass)
1850         WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1851                             diag::warn_undef_method_impl);
1852     } else {
1853       ObjCMethodDecl *ImpMethodDecl =
1854         IMPDecl->getClassMethod(I->getSelector());
1855       assert(CDecl->getClassMethod(I->getSelector()) &&
1856              "Expected to find the method through lookup as well");
1857       if (!WarnCategoryMethodImpl)
1858         WarnConflictingTypedMethods(ImpMethodDecl, I,
1859                                     isa<ObjCProtocolDecl>(CDecl));
1860       else
1861         WarnExactTypedMethods(ImpMethodDecl, I,
1862                               isa<ObjCProtocolDecl>(CDecl));
1863     }
1864   }
1865 
1866   if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
1867     // Also, check for methods declared in protocols inherited by
1868     // this protocol.
1869     for (auto *PI : PD->protocols())
1870       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1871                                  IMPDecl, PI, IncompleteImpl, false,
1872                                  WarnCategoryMethodImpl);
1873   }
1874 
1875   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1876     // when checking that methods in implementation match their declaration,
1877     // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1878     // extension; as well as those in categories.
1879     if (!WarnCategoryMethodImpl) {
1880       for (auto *Cat : I->visible_categories())
1881         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1882                                    IMPDecl, Cat, IncompleteImpl, false,
1883                                    WarnCategoryMethodImpl);
1884     } else {
1885       // Also methods in class extensions need be looked at next.
1886       for (auto *Ext : I->visible_extensions())
1887         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1888                                    IMPDecl, Ext, IncompleteImpl, false,
1889                                    WarnCategoryMethodImpl);
1890     }
1891 
1892     // Check for any implementation of a methods declared in protocol.
1893     for (auto *PI : I->all_referenced_protocols())
1894       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1895                                  IMPDecl, PI, IncompleteImpl, false,
1896                                  WarnCategoryMethodImpl);
1897 
1898     // FIXME. For now, we are not checking for extact match of methods
1899     // in category implementation and its primary class's super class.
1900     if (!WarnCategoryMethodImpl && I->getSuperClass())
1901       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1902                                  IMPDecl,
1903                                  I->getSuperClass(), IncompleteImpl, false);
1904   }
1905 }
1906 
1907 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1908 /// category matches with those implemented in its primary class and
1909 /// warns each time an exact match is found.
1910 void Sema::CheckCategoryVsClassMethodMatches(
1911                                   ObjCCategoryImplDecl *CatIMPDecl) {
1912   // Get category's primary class.
1913   ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1914   if (!CatDecl)
1915     return;
1916   ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1917   if (!IDecl)
1918     return;
1919   ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
1920   SelectorSet InsMap, ClsMap;
1921 
1922   for (const auto *I : CatIMPDecl->instance_methods()) {
1923     Selector Sel = I->getSelector();
1924     // When checking for methods implemented in the category, skip over
1925     // those declared in category class's super class. This is because
1926     // the super class must implement the method.
1927     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
1928       continue;
1929     InsMap.insert(Sel);
1930   }
1931 
1932   for (const auto *I : CatIMPDecl->class_methods()) {
1933     Selector Sel = I->getSelector();
1934     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
1935       continue;
1936     ClsMap.insert(Sel);
1937   }
1938   if (InsMap.empty() && ClsMap.empty())
1939     return;
1940 
1941   SelectorSet InsMapSeen, ClsMapSeen;
1942   bool IncompleteImpl = false;
1943   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1944                              CatIMPDecl, IDecl,
1945                              IncompleteImpl, false,
1946                              true /*WarnCategoryMethodImpl*/);
1947 }
1948 
1949 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1950                                      ObjCContainerDecl* CDecl,
1951                                      bool IncompleteImpl) {
1952   SelectorSet InsMap;
1953   // Check and see if instance methods in class interface have been
1954   // implemented in the implementation class.
1955   for (const auto *I : IMPDecl->instance_methods())
1956     InsMap.insert(I->getSelector());
1957 
1958   // Check and see if properties declared in the interface have either 1)
1959   // an implementation or 2) there is a @synthesize/@dynamic implementation
1960   // of the property in the @implementation.
1961   if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1962     bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
1963                                 LangOpts.ObjCRuntime.isNonFragile() &&
1964                                 !IDecl->isObjCRequiresPropertyDefs();
1965     DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
1966   }
1967 
1968   SelectorSet ClsMap;
1969   for (const auto *I : IMPDecl->class_methods())
1970     ClsMap.insert(I->getSelector());
1971 
1972   // Check for type conflict of methods declared in a class/protocol and
1973   // its implementation; if any.
1974   SelectorSet InsMapSeen, ClsMapSeen;
1975   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1976                              IMPDecl, CDecl,
1977                              IncompleteImpl, true);
1978 
1979   // check all methods implemented in category against those declared
1980   // in its primary class.
1981   if (ObjCCategoryImplDecl *CatDecl =
1982         dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1983     CheckCategoryVsClassMethodMatches(CatDecl);
1984 
1985   // Check the protocol list for unimplemented methods in the @implementation
1986   // class.
1987   // Check and see if class methods in class interface have been
1988   // implemented in the implementation class.
1989 
1990   LazyProtocolNameSet ExplicitImplProtocols;
1991 
1992   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1993     for (auto *PI : I->all_referenced_protocols())
1994       CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
1995                               InsMap, ClsMap, I, ExplicitImplProtocols);
1996     // Check class extensions (unnamed categories)
1997     for (auto *Ext : I->visible_extensions())
1998       ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
1999   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2000     // For extended class, unimplemented methods in its protocols will
2001     // be reported in the primary class.
2002     if (!C->IsClassExtension()) {
2003       for (auto *P : C->protocols())
2004         CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
2005                                 IncompleteImpl, InsMap, ClsMap, CDecl,
2006                                 ExplicitImplProtocols);
2007       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2008                                       /* SynthesizeProperties */ false);
2009     }
2010   } else
2011     llvm_unreachable("invalid ObjCContainerDecl type.");
2012 }
2013 
2014 /// ActOnForwardClassDeclaration -
2015 Sema::DeclGroupPtrTy
2016 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
2017                                    IdentifierInfo **IdentList,
2018                                    SourceLocation *IdentLocs,
2019                                    unsigned NumElts) {
2020   SmallVector<Decl *, 8> DeclsInGroup;
2021   for (unsigned i = 0; i != NumElts; ++i) {
2022     // Check for another declaration kind with the same name.
2023     NamedDecl *PrevDecl
2024       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
2025                          LookupOrdinaryName, ForRedeclaration);
2026     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2027       // GCC apparently allows the following idiom:
2028       //
2029       // typedef NSObject < XCElementTogglerP > XCElementToggler;
2030       // @class XCElementToggler;
2031       //
2032       // Here we have chosen to ignore the forward class declaration
2033       // with a warning. Since this is the implied behavior.
2034       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
2035       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
2036         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
2037         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2038       } else {
2039         // a forward class declaration matching a typedef name of a class refers
2040         // to the underlying class. Just ignore the forward class with a warning
2041         // as this will force the intended behavior which is to lookup the typedef
2042         // name.
2043         if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2044           Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
2045           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2046           continue;
2047         }
2048       }
2049     }
2050 
2051     // Create a declaration to describe this forward declaration.
2052     ObjCInterfaceDecl *PrevIDecl
2053       = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2054 
2055     IdentifierInfo *ClassName = IdentList[i];
2056     if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2057       // A previous decl with a different name is because of
2058       // @compatibility_alias, for example:
2059       // \code
2060       //   @class NewImage;
2061       //   @compatibility_alias OldImage NewImage;
2062       // \endcode
2063       // A lookup for 'OldImage' will return the 'NewImage' decl.
2064       //
2065       // In such a case use the real declaration name, instead of the alias one,
2066       // otherwise we will break IdentifierResolver and redecls-chain invariants.
2067       // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2068       // has been aliased.
2069       ClassName = PrevIDecl->getIdentifier();
2070     }
2071 
2072     ObjCInterfaceDecl *IDecl
2073       = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
2074                                   ClassName, PrevIDecl, IdentLocs[i]);
2075     IDecl->setAtEndRange(IdentLocs[i]);
2076 
2077     PushOnScopeChains(IDecl, TUScope);
2078     CheckObjCDeclScope(IDecl);
2079     DeclsInGroup.push_back(IDecl);
2080   }
2081 
2082   return BuildDeclaratorGroup(DeclsInGroup, false);
2083 }
2084 
2085 static bool tryMatchRecordTypes(ASTContext &Context,
2086                                 Sema::MethodMatchStrategy strategy,
2087                                 const Type *left, const Type *right);
2088 
2089 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2090                        QualType leftQT, QualType rightQT) {
2091   const Type *left =
2092     Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2093   const Type *right =
2094     Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2095 
2096   if (left == right) return true;
2097 
2098   // If we're doing a strict match, the types have to match exactly.
2099   if (strategy == Sema::MMS_strict) return false;
2100 
2101   if (left->isIncompleteType() || right->isIncompleteType()) return false;
2102 
2103   // Otherwise, use this absurdly complicated algorithm to try to
2104   // validate the basic, low-level compatibility of the two types.
2105 
2106   // As a minimum, require the sizes and alignments to match.
2107   TypeInfo LeftTI = Context.getTypeInfo(left);
2108   TypeInfo RightTI = Context.getTypeInfo(right);
2109   if (LeftTI.Width != RightTI.Width)
2110     return false;
2111 
2112   if (LeftTI.Align != RightTI.Align)
2113     return false;
2114 
2115   // Consider all the kinds of non-dependent canonical types:
2116   // - functions and arrays aren't possible as return and parameter types
2117 
2118   // - vector types of equal size can be arbitrarily mixed
2119   if (isa<VectorType>(left)) return isa<VectorType>(right);
2120   if (isa<VectorType>(right)) return false;
2121 
2122   // - references should only match references of identical type
2123   // - structs, unions, and Objective-C objects must match more-or-less
2124   //   exactly
2125   // - everything else should be a scalar
2126   if (!left->isScalarType() || !right->isScalarType())
2127     return tryMatchRecordTypes(Context, strategy, left, right);
2128 
2129   // Make scalars agree in kind, except count bools as chars, and group
2130   // all non-member pointers together.
2131   Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2132   Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2133   if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2134   if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
2135   if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2136     leftSK = Type::STK_ObjCObjectPointer;
2137   if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2138     rightSK = Type::STK_ObjCObjectPointer;
2139 
2140   // Note that data member pointers and function member pointers don't
2141   // intermix because of the size differences.
2142 
2143   return (leftSK == rightSK);
2144 }
2145 
2146 static bool tryMatchRecordTypes(ASTContext &Context,
2147                                 Sema::MethodMatchStrategy strategy,
2148                                 const Type *lt, const Type *rt) {
2149   assert(lt && rt && lt != rt);
2150 
2151   if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2152   RecordDecl *left = cast<RecordType>(lt)->getDecl();
2153   RecordDecl *right = cast<RecordType>(rt)->getDecl();
2154 
2155   // Require union-hood to match.
2156   if (left->isUnion() != right->isUnion()) return false;
2157 
2158   // Require an exact match if either is non-POD.
2159   if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2160       (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2161     return false;
2162 
2163   // Require size and alignment to match.
2164   TypeInfo LeftTI = Context.getTypeInfo(lt);
2165   TypeInfo RightTI = Context.getTypeInfo(rt);
2166   if (LeftTI.Width != RightTI.Width)
2167     return false;
2168 
2169   if (LeftTI.Align != RightTI.Align)
2170     return false;
2171 
2172   // Require fields to match.
2173   RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2174   RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2175   for (; li != le && ri != re; ++li, ++ri) {
2176     if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2177       return false;
2178   }
2179   return (li == le && ri == re);
2180 }
2181 
2182 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2183 /// returns true, or false, accordingly.
2184 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
2185 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2186                                       const ObjCMethodDecl *right,
2187                                       MethodMatchStrategy strategy) {
2188   if (!matchTypes(Context, strategy, left->getReturnType(),
2189                   right->getReturnType()))
2190     return false;
2191 
2192   // If either is hidden, it is not considered to match.
2193   if (left->isHidden() || right->isHidden())
2194     return false;
2195 
2196   if (getLangOpts().ObjCAutoRefCount &&
2197       (left->hasAttr<NSReturnsRetainedAttr>()
2198          != right->hasAttr<NSReturnsRetainedAttr>() ||
2199        left->hasAttr<NSConsumesSelfAttr>()
2200          != right->hasAttr<NSConsumesSelfAttr>()))
2201     return false;
2202 
2203   ObjCMethodDecl::param_const_iterator
2204     li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2205     re = right->param_end();
2206 
2207   for (; li != le && ri != re; ++li, ++ri) {
2208     assert(ri != right->param_end() && "Param mismatch");
2209     const ParmVarDecl *lparm = *li, *rparm = *ri;
2210 
2211     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2212       return false;
2213 
2214     if (getLangOpts().ObjCAutoRefCount &&
2215         lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2216       return false;
2217   }
2218   return true;
2219 }
2220 
2221 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
2222   // Record at the head of the list whether there were 0, 1, or >= 2 methods
2223   // inside categories.
2224   if (ObjCCategoryDecl *
2225         CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
2226     if (!CD->IsClassExtension() && List->getBits() < 2)
2227         List->setBits(List->getBits()+1);
2228 
2229   // If the list is empty, make it a singleton list.
2230   if (List->Method == nullptr) {
2231     List->Method = Method;
2232     List->setNext(nullptr);
2233     return;
2234   }
2235 
2236   // We've seen a method with this name, see if we have already seen this type
2237   // signature.
2238   ObjCMethodList *Previous = List;
2239   for (; List; Previous = List, List = List->getNext()) {
2240     // If we are building a module, keep all of the methods.
2241     if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
2242       continue;
2243 
2244     if (!MatchTwoMethodDeclarations(Method, List->Method))
2245       continue;
2246 
2247     ObjCMethodDecl *PrevObjCMethod = List->Method;
2248 
2249     // Propagate the 'defined' bit.
2250     if (Method->isDefined())
2251       PrevObjCMethod->setDefined(true);
2252 
2253     // If a method is deprecated, push it in the global pool.
2254     // This is used for better diagnostics.
2255     if (Method->isDeprecated()) {
2256       if (!PrevObjCMethod->isDeprecated())
2257         List->Method = Method;
2258     }
2259     // If new method is unavailable, push it into global pool
2260     // unless previous one is deprecated.
2261     if (Method->isUnavailable()) {
2262       if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2263         List->Method = Method;
2264     }
2265 
2266     return;
2267   }
2268 
2269   // We have a new signature for an existing method - add it.
2270   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2271   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
2272   Previous->setNext(new (Mem) ObjCMethodList(Method, nullptr));
2273 }
2274 
2275 /// \brief Read the contents of the method pool for a given selector from
2276 /// external storage.
2277 void Sema::ReadMethodPool(Selector Sel) {
2278   assert(ExternalSource && "We need an external AST source");
2279   ExternalSource->ReadMethodPool(Sel);
2280 }
2281 
2282 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
2283                                  bool instance) {
2284   // Ignore methods of invalid containers.
2285   if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
2286     return;
2287 
2288   if (ExternalSource)
2289     ReadMethodPool(Method->getSelector());
2290 
2291   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
2292   if (Pos == MethodPool.end())
2293     Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2294                                            GlobalMethods())).first;
2295 
2296   Method->setDefined(impl);
2297 
2298   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
2299   addMethodToGlobalList(&Entry, Method);
2300 }
2301 
2302 /// Determines if this is an "acceptable" loose mismatch in the global
2303 /// method pool.  This exists mostly as a hack to get around certain
2304 /// global mismatches which we can't afford to make warnings / errors.
2305 /// Really, what we want is a way to take a method out of the global
2306 /// method pool.
2307 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2308                                        ObjCMethodDecl *other) {
2309   if (!chosen->isInstanceMethod())
2310     return false;
2311 
2312   Selector sel = chosen->getSelector();
2313   if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2314     return false;
2315 
2316   // Don't complain about mismatches for -length if the method we
2317   // chose has an integral result type.
2318   return (chosen->getReturnType()->isIntegerType());
2319 }
2320 
2321 bool Sema::CollectMultipleMethodsInGlobalPool(Selector Sel,
2322                                               SmallVectorImpl<ObjCMethodDecl*>& Methods,
2323                                               bool instance) {
2324   if (ExternalSource)
2325     ReadMethodPool(Sel);
2326 
2327   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2328   if (Pos == MethodPool.end())
2329     return false;
2330   // Gather the non-hidden methods.
2331   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2332   for (ObjCMethodList *M = &MethList; M; M = M->getNext())
2333     if (M->Method && !M->Method->isHidden())
2334       Methods.push_back(M->Method);
2335   return (Methods.size() > 1);
2336 }
2337 
2338 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2339                                                bool receiverIdOrClass,
2340                                                bool warn, bool instance) {
2341   if (ExternalSource)
2342     ReadMethodPool(Sel);
2343 
2344   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2345   if (Pos == MethodPool.end())
2346     return nullptr;
2347 
2348   // Gather the non-hidden methods.
2349   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2350   SmallVector<ObjCMethodDecl *, 4> Methods;
2351   for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
2352     if (M->Method && !M->Method->isHidden()) {
2353       // If we're not supposed to warn about mismatches, we're done.
2354       if (!warn)
2355         return M->Method;
2356 
2357       Methods.push_back(M->Method);
2358     }
2359   }
2360 
2361   // If there aren't any visible methods, we're done.
2362   // FIXME: Recover if there are any known-but-hidden methods?
2363   if (Methods.empty())
2364     return nullptr;
2365 
2366   if (Methods.size() == 1)
2367     return Methods[0];
2368 
2369   // We found multiple methods, so we may have to complain.
2370   bool issueDiagnostic = false, issueError = false;
2371 
2372   // We support a warning which complains about *any* difference in
2373   // method signature.
2374   bool strictSelectorMatch =
2375       receiverIdOrClass && warn &&
2376       !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
2377   if (strictSelectorMatch) {
2378     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2379       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2380         issueDiagnostic = true;
2381         break;
2382       }
2383     }
2384   }
2385 
2386   // If we didn't see any strict differences, we won't see any loose
2387   // differences.  In ARC, however, we also need to check for loose
2388   // mismatches, because most of them are errors.
2389   if (!strictSelectorMatch ||
2390       (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2391     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2392       // This checks if the methods differ in type mismatch.
2393       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2394           !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2395         issueDiagnostic = true;
2396         if (getLangOpts().ObjCAutoRefCount)
2397           issueError = true;
2398         break;
2399       }
2400     }
2401 
2402   if (issueDiagnostic) {
2403     if (issueError)
2404       Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2405     else if (strictSelectorMatch)
2406       Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2407     else
2408       Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2409 
2410     Diag(Methods[0]->getLocStart(),
2411          issueError ? diag::note_possibility : diag::note_using)
2412       << Methods[0]->getSourceRange();
2413     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2414       Diag(Methods[I]->getLocStart(), diag::note_also_found)
2415         << Methods[I]->getSourceRange();
2416   }
2417   }
2418   return Methods[0];
2419 }
2420 
2421 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2422   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2423   if (Pos == MethodPool.end())
2424     return nullptr;
2425 
2426   GlobalMethods &Methods = Pos->second;
2427   for (const ObjCMethodList *Method = &Methods.first; Method;
2428        Method = Method->getNext())
2429     if (Method->Method && Method->Method->isDefined())
2430       return Method->Method;
2431 
2432   for (const ObjCMethodList *Method = &Methods.second; Method;
2433        Method = Method->getNext())
2434     if (Method->Method && Method->Method->isDefined())
2435       return Method->Method;
2436   return nullptr;
2437 }
2438 
2439 static void
2440 HelperSelectorsForTypoCorrection(
2441                       SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
2442                       StringRef Typo, const ObjCMethodDecl * Method) {
2443   const unsigned MaxEditDistance = 1;
2444   unsigned BestEditDistance = MaxEditDistance + 1;
2445   std::string MethodName = Method->getSelector().getAsString();
2446 
2447   unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
2448   if (MinPossibleEditDistance > 0 &&
2449       Typo.size() / MinPossibleEditDistance < 1)
2450     return;
2451   unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
2452   if (EditDistance > MaxEditDistance)
2453     return;
2454   if (EditDistance == BestEditDistance)
2455     BestMethod.push_back(Method);
2456   else if (EditDistance < BestEditDistance) {
2457     BestMethod.clear();
2458     BestMethod.push_back(Method);
2459   }
2460 }
2461 
2462 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
2463                                      QualType ObjectType) {
2464   if (ObjectType.isNull())
2465     return true;
2466   if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
2467     return true;
2468   return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
2469          nullptr;
2470 }
2471 
2472 const ObjCMethodDecl *
2473 Sema::SelectorsForTypoCorrection(Selector Sel,
2474                                  QualType ObjectType) {
2475   unsigned NumArgs = Sel.getNumArgs();
2476   SmallVector<const ObjCMethodDecl *, 8> Methods;
2477   bool ObjectIsId = true, ObjectIsClass = true;
2478   if (ObjectType.isNull())
2479     ObjectIsId = ObjectIsClass = false;
2480   else if (!ObjectType->isObjCObjectPointerType())
2481     return nullptr;
2482   else if (const ObjCObjectPointerType *ObjCPtr =
2483            ObjectType->getAsObjCInterfacePointerType()) {
2484     ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
2485     ObjectIsId = ObjectIsClass = false;
2486   }
2487   else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
2488     ObjectIsClass = false;
2489   else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
2490     ObjectIsId = false;
2491   else
2492     return nullptr;
2493 
2494   for (GlobalMethodPool::iterator b = MethodPool.begin(),
2495        e = MethodPool.end(); b != e; b++) {
2496     // instance methods
2497     for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
2498       if (M->Method &&
2499           (M->Method->getSelector().getNumArgs() == NumArgs) &&
2500           (M->Method->getSelector() != Sel)) {
2501         if (ObjectIsId)
2502           Methods.push_back(M->Method);
2503         else if (!ObjectIsClass &&
2504                  HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2505           Methods.push_back(M->Method);
2506       }
2507     // class methods
2508     for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
2509       if (M->Method &&
2510           (M->Method->getSelector().getNumArgs() == NumArgs) &&
2511           (M->Method->getSelector() != Sel)) {
2512         if (ObjectIsClass)
2513           Methods.push_back(M->Method);
2514         else if (!ObjectIsId &&
2515                  HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2516           Methods.push_back(M->Method);
2517       }
2518   }
2519 
2520   SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
2521   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
2522     HelperSelectorsForTypoCorrection(SelectedMethods,
2523                                      Sel.getAsString(), Methods[i]);
2524   }
2525   return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
2526 }
2527 
2528 /// DiagnoseDuplicateIvars -
2529 /// Check for duplicate ivars in the entire class at the start of
2530 /// \@implementation. This becomes necesssary because class extension can
2531 /// add ivars to a class in random order which will not be known until
2532 /// class's \@implementation is seen.
2533 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2534                                   ObjCInterfaceDecl *SID) {
2535   for (auto *Ivar : ID->ivars()) {
2536     if (Ivar->isInvalidDecl())
2537       continue;
2538     if (IdentifierInfo *II = Ivar->getIdentifier()) {
2539       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2540       if (prevIvar) {
2541         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2542         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2543         Ivar->setInvalidDecl();
2544       }
2545     }
2546   }
2547 }
2548 
2549 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2550   switch (CurContext->getDeclKind()) {
2551     case Decl::ObjCInterface:
2552       return Sema::OCK_Interface;
2553     case Decl::ObjCProtocol:
2554       return Sema::OCK_Protocol;
2555     case Decl::ObjCCategory:
2556       if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2557         return Sema::OCK_ClassExtension;
2558       else
2559         return Sema::OCK_Category;
2560     case Decl::ObjCImplementation:
2561       return Sema::OCK_Implementation;
2562     case Decl::ObjCCategoryImpl:
2563       return Sema::OCK_CategoryImplementation;
2564 
2565     default:
2566       return Sema::OCK_None;
2567   }
2568 }
2569 
2570 // Note: For class/category implementations, allMethods is always null.
2571 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
2572                        ArrayRef<DeclGroupPtrTy> allTUVars) {
2573   if (getObjCContainerKind() == Sema::OCK_None)
2574     return nullptr;
2575 
2576   assert(AtEnd.isValid() && "Invalid location for '@end'");
2577 
2578   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2579   Decl *ClassDecl = cast<Decl>(OCD);
2580 
2581   bool isInterfaceDeclKind =
2582         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2583          || isa<ObjCProtocolDecl>(ClassDecl);
2584   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2585 
2586   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2587   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2588   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2589 
2590   for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
2591     ObjCMethodDecl *Method =
2592       cast_or_null<ObjCMethodDecl>(allMethods[i]);
2593 
2594     if (!Method) continue;  // Already issued a diagnostic.
2595     if (Method->isInstanceMethod()) {
2596       /// Check for instance method of the same name with incompatible types
2597       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2598       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2599                               : false;
2600       if ((isInterfaceDeclKind && PrevMethod && !match)
2601           || (checkIdenticalMethods && match)) {
2602           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2603             << Method->getDeclName();
2604           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2605         Method->setInvalidDecl();
2606       } else {
2607         if (PrevMethod) {
2608           Method->setAsRedeclaration(PrevMethod);
2609           if (!Context.getSourceManager().isInSystemHeader(
2610                  Method->getLocation()))
2611             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2612               << Method->getDeclName();
2613           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2614         }
2615         InsMap[Method->getSelector()] = Method;
2616         /// The following allows us to typecheck messages to "id".
2617         AddInstanceMethodToGlobalPool(Method);
2618       }
2619     } else {
2620       /// Check for class method of the same name with incompatible types
2621       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2622       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2623                               : false;
2624       if ((isInterfaceDeclKind && PrevMethod && !match)
2625           || (checkIdenticalMethods && match)) {
2626         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2627           << Method->getDeclName();
2628         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2629         Method->setInvalidDecl();
2630       } else {
2631         if (PrevMethod) {
2632           Method->setAsRedeclaration(PrevMethod);
2633           if (!Context.getSourceManager().isInSystemHeader(
2634                  Method->getLocation()))
2635             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2636               << Method->getDeclName();
2637           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2638         }
2639         ClsMap[Method->getSelector()] = Method;
2640         AddFactoryMethodToGlobalPool(Method);
2641       }
2642     }
2643   }
2644   if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2645     // Nothing to do here.
2646   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2647     // Categories are used to extend the class by declaring new methods.
2648     // By the same token, they are also used to add new properties. No
2649     // need to compare the added property to those in the class.
2650 
2651     if (C->IsClassExtension()) {
2652       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2653       DiagnoseClassExtensionDupMethods(C, CCPrimary);
2654     }
2655   }
2656   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2657     if (CDecl->getIdentifier())
2658       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2659       // user-defined setter/getter. It also synthesizes setter/getter methods
2660       // and adds them to the DeclContext and global method pools.
2661       for (auto *I : CDecl->properties())
2662         ProcessPropertyDecl(I, CDecl);
2663     CDecl->setAtEndRange(AtEnd);
2664   }
2665   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2666     IC->setAtEndRange(AtEnd);
2667     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2668       // Any property declared in a class extension might have user
2669       // declared setter or getter in current class extension or one
2670       // of the other class extensions. Mark them as synthesized as
2671       // property will be synthesized when property with same name is
2672       // seen in the @implementation.
2673       for (const auto *Ext : IDecl->visible_extensions()) {
2674         for (const auto *Property : Ext->properties()) {
2675           // Skip over properties declared @dynamic
2676           if (const ObjCPropertyImplDecl *PIDecl
2677               = IC->FindPropertyImplDecl(Property->getIdentifier()))
2678             if (PIDecl->getPropertyImplementation()
2679                   == ObjCPropertyImplDecl::Dynamic)
2680               continue;
2681 
2682           for (const auto *Ext : IDecl->visible_extensions()) {
2683             if (ObjCMethodDecl *GetterMethod
2684                   = Ext->getInstanceMethod(Property->getGetterName()))
2685               GetterMethod->setPropertyAccessor(true);
2686             if (!Property->isReadOnly())
2687               if (ObjCMethodDecl *SetterMethod
2688                     = Ext->getInstanceMethod(Property->getSetterName()))
2689                 SetterMethod->setPropertyAccessor(true);
2690           }
2691         }
2692       }
2693       ImplMethodsVsClassMethods(S, IC, IDecl);
2694       AtomicPropertySetterGetterRules(IC, IDecl);
2695       DiagnoseOwningPropertyGetterSynthesis(IC);
2696       DiagnoseUnusedBackingIvarInAccessor(S, IC);
2697       if (IDecl->hasDesignatedInitializers())
2698         DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
2699 
2700       bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
2701       if (IDecl->getSuperClass() == nullptr) {
2702         // This class has no superclass, so check that it has been marked with
2703         // __attribute((objc_root_class)).
2704         if (!HasRootClassAttr) {
2705           SourceLocation DeclLoc(IDecl->getLocation());
2706           SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
2707           Diag(DeclLoc, diag::warn_objc_root_class_missing)
2708             << IDecl->getIdentifier();
2709           // See if NSObject is in the current scope, and if it is, suggest
2710           // adding " : NSObject " to the class declaration.
2711           NamedDecl *IF = LookupSingleName(TUScope,
2712                                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2713                                            DeclLoc, LookupOrdinaryName);
2714           ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2715           if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2716             Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2717               << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2718           } else {
2719             Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2720           }
2721         }
2722       } else if (HasRootClassAttr) {
2723         // Complain that only root classes may have this attribute.
2724         Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2725       }
2726 
2727       if (LangOpts.ObjCRuntime.isNonFragile()) {
2728         while (IDecl->getSuperClass()) {
2729           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2730           IDecl = IDecl->getSuperClass();
2731         }
2732       }
2733     }
2734     SetIvarInitializers(IC);
2735   } else if (ObjCCategoryImplDecl* CatImplClass =
2736                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2737     CatImplClass->setAtEndRange(AtEnd);
2738 
2739     // Find category interface decl and then check that all methods declared
2740     // in this interface are implemented in the category @implementation.
2741     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2742       if (ObjCCategoryDecl *Cat
2743             = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2744         ImplMethodsVsClassMethods(S, CatImplClass, Cat);
2745       }
2746     }
2747   }
2748   if (isInterfaceDeclKind) {
2749     // Reject invalid vardecls.
2750     for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2751       DeclGroupRef DG = allTUVars[i].get();
2752       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2753         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2754           if (!VDecl->hasExternalStorage())
2755             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2756         }
2757     }
2758   }
2759   ActOnObjCContainerFinishDefinition();
2760 
2761   for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2762     DeclGroupRef DG = allTUVars[i].get();
2763     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2764       (*I)->setTopLevelDeclInObjCContainer();
2765     Consumer.HandleTopLevelDeclInObjCContainer(DG);
2766   }
2767 
2768   ActOnDocumentableDecl(ClassDecl);
2769   return ClassDecl;
2770 }
2771 
2772 
2773 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2774 /// objective-c's type qualifier from the parser version of the same info.
2775 static Decl::ObjCDeclQualifier
2776 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2777   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2778 }
2779 
2780 /// \brief Check whether the declared result type of the given Objective-C
2781 /// method declaration is compatible with the method's class.
2782 ///
2783 static Sema::ResultTypeCompatibilityKind
2784 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2785                                     ObjCInterfaceDecl *CurrentClass) {
2786   QualType ResultType = Method->getReturnType();
2787 
2788   // If an Objective-C method inherits its related result type, then its
2789   // declared result type must be compatible with its own class type. The
2790   // declared result type is compatible if:
2791   if (const ObjCObjectPointerType *ResultObjectType
2792                                 = ResultType->getAs<ObjCObjectPointerType>()) {
2793     //   - it is id or qualified id, or
2794     if (ResultObjectType->isObjCIdType() ||
2795         ResultObjectType->isObjCQualifiedIdType())
2796       return Sema::RTC_Compatible;
2797 
2798     if (CurrentClass) {
2799       if (ObjCInterfaceDecl *ResultClass
2800                                       = ResultObjectType->getInterfaceDecl()) {
2801         //   - it is the same as the method's class type, or
2802         if (declaresSameEntity(CurrentClass, ResultClass))
2803           return Sema::RTC_Compatible;
2804 
2805         //   - it is a superclass of the method's class type
2806         if (ResultClass->isSuperClassOf(CurrentClass))
2807           return Sema::RTC_Compatible;
2808       }
2809     } else {
2810       // Any Objective-C pointer type might be acceptable for a protocol
2811       // method; we just don't know.
2812       return Sema::RTC_Unknown;
2813     }
2814   }
2815 
2816   return Sema::RTC_Incompatible;
2817 }
2818 
2819 namespace {
2820 /// A helper class for searching for methods which a particular method
2821 /// overrides.
2822 class OverrideSearch {
2823 public:
2824   Sema &S;
2825   ObjCMethodDecl *Method;
2826   llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
2827   bool Recursive;
2828 
2829 public:
2830   OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2831     Selector selector = method->getSelector();
2832 
2833     // Bypass this search if we've never seen an instance/class method
2834     // with this selector before.
2835     Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2836     if (it == S.MethodPool.end()) {
2837       if (!S.getExternalSource()) return;
2838       S.ReadMethodPool(selector);
2839 
2840       it = S.MethodPool.find(selector);
2841       if (it == S.MethodPool.end())
2842         return;
2843     }
2844     ObjCMethodList &list =
2845       method->isInstanceMethod() ? it->second.first : it->second.second;
2846     if (!list.Method) return;
2847 
2848     ObjCContainerDecl *container
2849       = cast<ObjCContainerDecl>(method->getDeclContext());
2850 
2851     // Prevent the search from reaching this container again.  This is
2852     // important with categories, which override methods from the
2853     // interface and each other.
2854     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2855       searchFromContainer(container);
2856       if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2857         searchFromContainer(Interface);
2858     } else {
2859       searchFromContainer(container);
2860     }
2861   }
2862 
2863   typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
2864   iterator begin() const { return Overridden.begin(); }
2865   iterator end() const { return Overridden.end(); }
2866 
2867 private:
2868   void searchFromContainer(ObjCContainerDecl *container) {
2869     if (container->isInvalidDecl()) return;
2870 
2871     switch (container->getDeclKind()) {
2872 #define OBJCCONTAINER(type, base) \
2873     case Decl::type: \
2874       searchFrom(cast<type##Decl>(container)); \
2875       break;
2876 #define ABSTRACT_DECL(expansion)
2877 #define DECL(type, base) \
2878     case Decl::type:
2879 #include "clang/AST/DeclNodes.inc"
2880       llvm_unreachable("not an ObjC container!");
2881     }
2882   }
2883 
2884   void searchFrom(ObjCProtocolDecl *protocol) {
2885     if (!protocol->hasDefinition())
2886       return;
2887 
2888     // A method in a protocol declaration overrides declarations from
2889     // referenced ("parent") protocols.
2890     search(protocol->getReferencedProtocols());
2891   }
2892 
2893   void searchFrom(ObjCCategoryDecl *category) {
2894     // A method in a category declaration overrides declarations from
2895     // the main class and from protocols the category references.
2896     // The main class is handled in the constructor.
2897     search(category->getReferencedProtocols());
2898   }
2899 
2900   void searchFrom(ObjCCategoryImplDecl *impl) {
2901     // A method in a category definition that has a category
2902     // declaration overrides declarations from the category
2903     // declaration.
2904     if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2905       search(category);
2906       if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2907         search(Interface);
2908 
2909     // Otherwise it overrides declarations from the class.
2910     } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2911       search(Interface);
2912     }
2913   }
2914 
2915   void searchFrom(ObjCInterfaceDecl *iface) {
2916     // A method in a class declaration overrides declarations from
2917     if (!iface->hasDefinition())
2918       return;
2919 
2920     //   - categories,
2921     for (auto *Cat : iface->known_categories())
2922       search(Cat);
2923 
2924     //   - the super class, and
2925     if (ObjCInterfaceDecl *super = iface->getSuperClass())
2926       search(super);
2927 
2928     //   - any referenced protocols.
2929     search(iface->getReferencedProtocols());
2930   }
2931 
2932   void searchFrom(ObjCImplementationDecl *impl) {
2933     // A method in a class implementation overrides declarations from
2934     // the class interface.
2935     if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2936       search(Interface);
2937   }
2938 
2939 
2940   void search(const ObjCProtocolList &protocols) {
2941     for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2942          i != e; ++i)
2943       search(*i);
2944   }
2945 
2946   void search(ObjCContainerDecl *container) {
2947     // Check for a method in this container which matches this selector.
2948     ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2949                                                 Method->isInstanceMethod(),
2950                                                 /*AllowHidden=*/true);
2951 
2952     // If we find one, record it and bail out.
2953     if (meth) {
2954       Overridden.insert(meth);
2955       return;
2956     }
2957 
2958     // Otherwise, search for methods that a hypothetical method here
2959     // would have overridden.
2960 
2961     // Note that we're now in a recursive case.
2962     Recursive = true;
2963 
2964     searchFromContainer(container);
2965   }
2966 };
2967 }
2968 
2969 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
2970                                     ObjCInterfaceDecl *CurrentClass,
2971                                     ResultTypeCompatibilityKind RTC) {
2972   // Search for overridden methods and merge information down from them.
2973   OverrideSearch overrides(*this, ObjCMethod);
2974   // Keep track if the method overrides any method in the class's base classes,
2975   // its protocols, or its categories' protocols; we will keep that info
2976   // in the ObjCMethodDecl.
2977   // For this info, a method in an implementation is not considered as
2978   // overriding the same method in the interface or its categories.
2979   bool hasOverriddenMethodsInBaseOrProtocol = false;
2980   for (OverrideSearch::iterator
2981          i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2982     ObjCMethodDecl *overridden = *i;
2983 
2984     if (!hasOverriddenMethodsInBaseOrProtocol) {
2985       if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
2986           CurrentClass != overridden->getClassInterface() ||
2987           overridden->isOverriding()) {
2988         hasOverriddenMethodsInBaseOrProtocol = true;
2989 
2990       } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
2991         // OverrideSearch will return as "overridden" the same method in the
2992         // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
2993         // check whether a category of a base class introduced a method with the
2994         // same selector, after the interface method declaration.
2995         // To avoid unnecessary lookups in the majority of cases, we use the
2996         // extra info bits in GlobalMethodPool to check whether there were any
2997         // category methods with this selector.
2998         GlobalMethodPool::iterator It =
2999             MethodPool.find(ObjCMethod->getSelector());
3000         if (It != MethodPool.end()) {
3001           ObjCMethodList &List =
3002             ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3003           unsigned CategCount = List.getBits();
3004           if (CategCount > 0) {
3005             // If the method is in a category we'll do lookup if there were at
3006             // least 2 category methods recorded, otherwise only one will do.
3007             if (CategCount > 1 ||
3008                 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3009               OverrideSearch overrides(*this, overridden);
3010               for (OverrideSearch::iterator
3011                      OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3012                 ObjCMethodDecl *SuperOverridden = *OI;
3013                 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3014                     CurrentClass != SuperOverridden->getClassInterface()) {
3015                   hasOverriddenMethodsInBaseOrProtocol = true;
3016                   overridden->setOverriding(true);
3017                   break;
3018                 }
3019               }
3020             }
3021           }
3022         }
3023       }
3024     }
3025 
3026     // Propagate down the 'related result type' bit from overridden methods.
3027     if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3028       ObjCMethod->SetRelatedResultType();
3029 
3030     // Then merge the declarations.
3031     mergeObjCMethodDecls(ObjCMethod, overridden);
3032 
3033     if (ObjCMethod->isImplicit() && overridden->isImplicit())
3034       continue; // Conflicting properties are detected elsewhere.
3035 
3036     // Check for overriding methods
3037     if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3038         isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3039       CheckConflictingOverridingMethod(ObjCMethod, overridden,
3040               isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3041 
3042     if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
3043         isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3044         !overridden->isImplicit() /* not meant for properties */) {
3045       ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3046                                           E = ObjCMethod->param_end();
3047       ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3048                                      PrevE = overridden->param_end();
3049       for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
3050         assert(PrevI != overridden->param_end() && "Param mismatch");
3051         QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3052         QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3053         // If type of argument of method in this class does not match its
3054         // respective argument type in the super class method, issue warning;
3055         if (!Context.typesAreCompatible(T1, T2)) {
3056           Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3057             << T1 << T2;
3058           Diag(overridden->getLocation(), diag::note_previous_declaration);
3059           break;
3060         }
3061       }
3062     }
3063   }
3064 
3065   ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3066 }
3067 
3068 Decl *Sema::ActOnMethodDeclaration(
3069     Scope *S,
3070     SourceLocation MethodLoc, SourceLocation EndLoc,
3071     tok::TokenKind MethodType,
3072     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
3073     ArrayRef<SourceLocation> SelectorLocs,
3074     Selector Sel,
3075     // optional arguments. The number of types/arguments is obtained
3076     // from the Sel.getNumArgs().
3077     ObjCArgInfo *ArgInfo,
3078     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
3079     AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
3080     bool isVariadic, bool MethodDefinition) {
3081   // Make sure we can establish a context for the method.
3082   if (!CurContext->isObjCContainer()) {
3083     Diag(MethodLoc, diag::error_missing_method_context);
3084     return nullptr;
3085   }
3086   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3087   Decl *ClassDecl = cast<Decl>(OCD);
3088   QualType resultDeclType;
3089 
3090   bool HasRelatedResultType = false;
3091   TypeSourceInfo *ReturnTInfo = nullptr;
3092   if (ReturnType) {
3093     resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
3094 
3095     if (CheckFunctionReturnType(resultDeclType, MethodLoc))
3096       return nullptr;
3097 
3098     HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
3099   } else { // get the type for "id".
3100     resultDeclType = Context.getObjCIdType();
3101     Diag(MethodLoc, diag::warn_missing_method_return_type)
3102       << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
3103   }
3104 
3105   ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
3106       Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
3107       MethodType == tok::minus, isVariadic,
3108       /*isPropertyAccessor=*/false,
3109       /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
3110       MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
3111                                            : ObjCMethodDecl::Required,
3112       HasRelatedResultType);
3113 
3114   SmallVector<ParmVarDecl*, 16> Params;
3115 
3116   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
3117     QualType ArgType;
3118     TypeSourceInfo *DI;
3119 
3120     if (!ArgInfo[i].Type) {
3121       ArgType = Context.getObjCIdType();
3122       DI = nullptr;
3123     } else {
3124       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
3125     }
3126 
3127     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
3128                    LookupOrdinaryName, ForRedeclaration);
3129     LookupName(R, S);
3130     if (R.isSingleResult()) {
3131       NamedDecl *PrevDecl = R.getFoundDecl();
3132       if (S->isDeclScope(PrevDecl)) {
3133         Diag(ArgInfo[i].NameLoc,
3134              (MethodDefinition ? diag::warn_method_param_redefinition
3135                                : diag::warn_method_param_declaration))
3136           << ArgInfo[i].Name;
3137         Diag(PrevDecl->getLocation(),
3138              diag::note_previous_declaration);
3139       }
3140     }
3141 
3142     SourceLocation StartLoc = DI
3143       ? DI->getTypeLoc().getBeginLoc()
3144       : ArgInfo[i].NameLoc;
3145 
3146     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
3147                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
3148                                         ArgType, DI, SC_None);
3149 
3150     Param->setObjCMethodScopeInfo(i);
3151 
3152     Param->setObjCDeclQualifier(
3153       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
3154 
3155     // Apply the attributes to the parameter.
3156     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
3157 
3158     if (Param->hasAttr<BlocksAttr>()) {
3159       Diag(Param->getLocation(), diag::err_block_on_nonlocal);
3160       Param->setInvalidDecl();
3161     }
3162     S->AddDecl(Param);
3163     IdResolver.AddDecl(Param);
3164 
3165     Params.push_back(Param);
3166   }
3167 
3168   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
3169     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
3170     QualType ArgType = Param->getType();
3171     if (ArgType.isNull())
3172       ArgType = Context.getObjCIdType();
3173     else
3174       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
3175       ArgType = Context.getAdjustedParameterType(ArgType);
3176 
3177     Param->setDeclContext(ObjCMethod);
3178     Params.push_back(Param);
3179   }
3180 
3181   ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
3182   ObjCMethod->setObjCDeclQualifier(
3183     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
3184 
3185   if (AttrList)
3186     ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
3187 
3188   // Add the method now.
3189   const ObjCMethodDecl *PrevMethod = nullptr;
3190   if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
3191     if (MethodType == tok::minus) {
3192       PrevMethod = ImpDecl->getInstanceMethod(Sel);
3193       ImpDecl->addInstanceMethod(ObjCMethod);
3194     } else {
3195       PrevMethod = ImpDecl->getClassMethod(Sel);
3196       ImpDecl->addClassMethod(ObjCMethod);
3197     }
3198 
3199     ObjCMethodDecl *IMD = nullptr;
3200     if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
3201       IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
3202                                 ObjCMethod->isInstanceMethod());
3203     if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
3204         !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
3205       // merge the attribute into implementation.
3206       ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
3207                                                    ObjCMethod->getLocation()));
3208     }
3209     if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
3210       ObjCMethodFamily family =
3211         ObjCMethod->getSelector().getMethodFamily();
3212       if (family == OMF_dealloc && IMD && IMD->isOverriding())
3213         Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
3214           << ObjCMethod->getDeclName();
3215     }
3216   } else {
3217     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
3218   }
3219 
3220   if (PrevMethod) {
3221     // You can never have two method definitions with the same name.
3222     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
3223       << ObjCMethod->getDeclName();
3224     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3225     ObjCMethod->setInvalidDecl();
3226     return ObjCMethod;
3227   }
3228 
3229   // If this Objective-C method does not have a related result type, but we
3230   // are allowed to infer related result types, try to do so based on the
3231   // method family.
3232   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3233   if (!CurrentClass) {
3234     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3235       CurrentClass = Cat->getClassInterface();
3236     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3237       CurrentClass = Impl->getClassInterface();
3238     else if (ObjCCategoryImplDecl *CatImpl
3239                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3240       CurrentClass = CatImpl->getClassInterface();
3241   }
3242 
3243   ResultTypeCompatibilityKind RTC
3244     = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
3245 
3246   CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
3247 
3248   bool ARCError = false;
3249   if (getLangOpts().ObjCAutoRefCount)
3250     ARCError = CheckARCMethodDecl(ObjCMethod);
3251 
3252   // Infer the related result type when possible.
3253   if (!ARCError && RTC == Sema::RTC_Compatible &&
3254       !ObjCMethod->hasRelatedResultType() &&
3255       LangOpts.ObjCInferRelatedResultType) {
3256     bool InferRelatedResultType = false;
3257     switch (ObjCMethod->getMethodFamily()) {
3258     case OMF_None:
3259     case OMF_copy:
3260     case OMF_dealloc:
3261     case OMF_finalize:
3262     case OMF_mutableCopy:
3263     case OMF_release:
3264     case OMF_retainCount:
3265     case OMF_initialize:
3266     case OMF_performSelector:
3267       break;
3268 
3269     case OMF_alloc:
3270     case OMF_new:
3271       InferRelatedResultType = ObjCMethod->isClassMethod();
3272       break;
3273 
3274     case OMF_init:
3275     case OMF_autorelease:
3276     case OMF_retain:
3277     case OMF_self:
3278       InferRelatedResultType = ObjCMethod->isInstanceMethod();
3279       break;
3280     }
3281 
3282     if (InferRelatedResultType)
3283       ObjCMethod->SetRelatedResultType();
3284   }
3285 
3286   ActOnDocumentableDecl(ObjCMethod);
3287 
3288   return ObjCMethod;
3289 }
3290 
3291 bool Sema::CheckObjCDeclScope(Decl *D) {
3292   // Following is also an error. But it is caused by a missing @end
3293   // and diagnostic is issued elsewhere.
3294   if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
3295     return false;
3296 
3297   // If we switched context to translation unit while we are still lexically in
3298   // an objc container, it means the parser missed emitting an error.
3299   if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3300     return false;
3301 
3302   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3303   D->setInvalidDecl();
3304 
3305   return true;
3306 }
3307 
3308 /// Called whenever \@defs(ClassName) is encountered in the source.  Inserts the
3309 /// instance variables of ClassName into Decls.
3310 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3311                      IdentifierInfo *ClassName,
3312                      SmallVectorImpl<Decl*> &Decls) {
3313   // Check that ClassName is a valid class
3314   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
3315   if (!Class) {
3316     Diag(DeclStart, diag::err_undef_interface) << ClassName;
3317     return;
3318   }
3319   if (LangOpts.ObjCRuntime.isNonFragile()) {
3320     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3321     return;
3322   }
3323 
3324   // Collect the instance variables
3325   SmallVector<const ObjCIvarDecl*, 32> Ivars;
3326   Context.DeepCollectObjCIvars(Class, true, Ivars);
3327   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
3328   for (unsigned i = 0; i < Ivars.size(); i++) {
3329     const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
3330     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
3331     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3332                                            /*FIXME: StartL=*/ID->getLocation(),
3333                                            ID->getLocation(),
3334                                            ID->getIdentifier(), ID->getType(),
3335                                            ID->getBitWidth());
3336     Decls.push_back(FD);
3337   }
3338 
3339   // Introduce all of these fields into the appropriate scope.
3340   for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
3341        D != Decls.end(); ++D) {
3342     FieldDecl *FD = cast<FieldDecl>(*D);
3343     if (getLangOpts().CPlusPlus)
3344       PushOnScopeChains(cast<FieldDecl>(FD), S);
3345     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
3346       Record->addDecl(FD);
3347   }
3348 }
3349 
3350 /// \brief Build a type-check a new Objective-C exception variable declaration.
3351 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3352                                       SourceLocation StartLoc,
3353                                       SourceLocation IdLoc,
3354                                       IdentifierInfo *Id,
3355                                       bool Invalid) {
3356   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3357   // duration shall not be qualified by an address-space qualifier."
3358   // Since all parameters have automatic store duration, they can not have
3359   // an address space.
3360   if (T.getAddressSpace() != 0) {
3361     Diag(IdLoc, diag::err_arg_with_address_space);
3362     Invalid = true;
3363   }
3364 
3365   // An @catch parameter must be an unqualified object pointer type;
3366   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3367   if (Invalid) {
3368     // Don't do any further checking.
3369   } else if (T->isDependentType()) {
3370     // Okay: we don't know what this type will instantiate to.
3371   } else if (!T->isObjCObjectPointerType()) {
3372     Invalid = true;
3373     Diag(IdLoc ,diag::err_catch_param_not_objc_type);
3374   } else if (T->isObjCQualifiedIdType()) {
3375     Invalid = true;
3376     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
3377   }
3378 
3379   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
3380                                  T, TInfo, SC_None);
3381   New->setExceptionVariable(true);
3382 
3383   // In ARC, infer 'retaining' for variables of retainable type.
3384   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
3385     Invalid = true;
3386 
3387   if (Invalid)
3388     New->setInvalidDecl();
3389   return New;
3390 }
3391 
3392 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
3393   const DeclSpec &DS = D.getDeclSpec();
3394 
3395   // We allow the "register" storage class on exception variables because
3396   // GCC did, but we drop it completely. Any other storage class is an error.
3397   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3398     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3399       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
3400   } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3401     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
3402       << DeclSpec::getSpecifierName(SCS);
3403   }
3404   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
3405     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
3406          diag::err_invalid_thread)
3407      << DeclSpec::getSpecifierName(TSCS);
3408   D.getMutableDeclSpec().ClearStorageClassSpecs();
3409 
3410   DiagnoseFunctionSpecifiers(D.getDeclSpec());
3411 
3412   // Check that there are no default arguments inside the type of this
3413   // exception object (C++ only).
3414   if (getLangOpts().CPlusPlus)
3415     CheckExtraCXXDefaultArguments(D);
3416 
3417   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3418   QualType ExceptionType = TInfo->getType();
3419 
3420   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3421                                         D.getSourceRange().getBegin(),
3422                                         D.getIdentifierLoc(),
3423                                         D.getIdentifier(),
3424                                         D.isInvalidType());
3425 
3426   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3427   if (D.getCXXScopeSpec().isSet()) {
3428     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3429       << D.getCXXScopeSpec().getRange();
3430     New->setInvalidDecl();
3431   }
3432 
3433   // Add the parameter declaration into this scope.
3434   S->AddDecl(New);
3435   if (D.getIdentifier())
3436     IdResolver.AddDecl(New);
3437 
3438   ProcessDeclAttributes(S, New, D);
3439 
3440   if (New->hasAttr<BlocksAttr>())
3441     Diag(New->getLocation(), diag::err_block_on_nonlocal);
3442   return New;
3443 }
3444 
3445 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3446 /// initialization.
3447 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3448                                 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
3449   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3450        Iv= Iv->getNextIvar()) {
3451     QualType QT = Context.getBaseElementType(Iv->getType());
3452     if (QT->isRecordType())
3453       Ivars.push_back(Iv);
3454   }
3455 }
3456 
3457 void Sema::DiagnoseUseOfUnimplementedSelectors() {
3458   // Load referenced selectors from the external source.
3459   if (ExternalSource) {
3460     SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3461     ExternalSource->ReadReferencedSelectors(Sels);
3462     for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3463       ReferencedSelectors[Sels[I].first] = Sels[I].second;
3464   }
3465 
3466   // Warning will be issued only when selector table is
3467   // generated (which means there is at lease one implementation
3468   // in the TU). This is to match gcc's behavior.
3469   if (ReferencedSelectors.empty() ||
3470       !Context.AnyObjCImplementation())
3471     return;
3472   for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
3473         ReferencedSelectors.begin(),
3474        E = ReferencedSelectors.end(); S != E; ++S) {
3475     Selector Sel = (*S).first;
3476     if (!LookupImplementedMethodInGlobalPool(Sel))
3477       Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
3478   }
3479   return;
3480 }
3481 
3482 ObjCIvarDecl *
3483 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3484                                      const ObjCPropertyDecl *&PDecl) const {
3485   if (Method->isClassMethod())
3486     return nullptr;
3487   const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
3488   if (!IDecl)
3489     return nullptr;
3490   Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
3491                                /*shallowCategoryLookup=*/false,
3492                                /*followSuper=*/false);
3493   if (!Method || !Method->isPropertyAccessor())
3494     return nullptr;
3495   if ((PDecl = Method->findPropertyDecl()))
3496     if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
3497       // property backing ivar must belong to property's class
3498       // or be a private ivar in class's implementation.
3499       // FIXME. fix the const-ness issue.
3500       IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
3501                                                         IV->getIdentifier());
3502       return IV;
3503     }
3504   return nullptr;
3505 }
3506 
3507 namespace {
3508   /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
3509   /// accessor references the backing ivar.
3510   class UnusedBackingIvarChecker :
3511       public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
3512   public:
3513     Sema &S;
3514     const ObjCMethodDecl *Method;
3515     const ObjCIvarDecl *IvarD;
3516     bool AccessedIvar;
3517     bool InvokedSelfMethod;
3518 
3519     UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
3520                              const ObjCIvarDecl *IvarD)
3521       : S(S), Method(Method), IvarD(IvarD),
3522         AccessedIvar(false), InvokedSelfMethod(false) {
3523       assert(IvarD);
3524     }
3525 
3526     bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
3527       if (E->getDecl() == IvarD) {
3528         AccessedIvar = true;
3529         return false;
3530       }
3531       return true;
3532     }
3533 
3534     bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
3535       if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
3536           S.isSelfExpr(E->getInstanceReceiver(), Method)) {
3537         InvokedSelfMethod = true;
3538       }
3539       return true;
3540     }
3541   };
3542 }
3543 
3544 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3545                                           const ObjCImplementationDecl *ImplD) {
3546   if (S->hasUnrecoverableErrorOccurred())
3547     return;
3548 
3549   for (const auto *CurMethod : ImplD->instance_methods()) {
3550     unsigned DIAG = diag::warn_unused_property_backing_ivar;
3551     SourceLocation Loc = CurMethod->getLocation();
3552     if (Diags.isIgnored(DIAG, Loc))
3553       continue;
3554 
3555     const ObjCPropertyDecl *PDecl;
3556     const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
3557     if (!IV)
3558       continue;
3559 
3560     UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
3561     Checker.TraverseStmt(CurMethod->getBody());
3562     if (Checker.AccessedIvar)
3563       continue;
3564 
3565     // Do not issue this warning if backing ivar is used somewhere and accessor
3566     // implementation makes a self call. This is to prevent false positive in
3567     // cases where the ivar is accessed by another method that the accessor
3568     // delegates to.
3569     if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
3570       Diag(Loc, DIAG) << IV;
3571       Diag(PDecl->getLocation(), diag::note_property_declare);
3572     }
3573   }
3574 }
3575