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       if (TypoCorrection Corrected =
520               CorrectTypo(DeclarationNameInfo(SuperName, SuperLoc),
521                           LookupOrdinaryName, TUScope, nullptr,
522                           llvm::make_unique<ObjCInterfaceValidatorCCC>(IDecl),
523                           CTK_ErrorRecovery)) {
524         diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
525                                     << SuperName << ClassName);
526         PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
527       }
528     }
529 
530     if (declaresSameEntity(PrevDecl, IDecl)) {
531       Diag(SuperLoc, diag::err_recursive_superclass)
532         << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
533       IDecl->setEndOfDefinitionLoc(ClassLoc);
534     } else {
535       ObjCInterfaceDecl *SuperClassDecl =
536                                 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
537 
538       // Diagnose classes that inherit from deprecated classes.
539       if (SuperClassDecl)
540         (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
541 
542       if (PrevDecl && !SuperClassDecl) {
543         // The previous declaration was not a class decl. Check if we have a
544         // typedef. If we do, get the underlying class type.
545         if (const TypedefNameDecl *TDecl =
546               dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
547           QualType T = TDecl->getUnderlyingType();
548           if (T->isObjCObjectType()) {
549             if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
550               SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
551               // This handles the following case:
552               // @interface NewI @end
553               // typedef NewI DeprI __attribute__((deprecated("blah")))
554               // @interface SI : DeprI /* warn here */ @end
555               (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
556             }
557           }
558         }
559 
560         // This handles the following case:
561         //
562         // typedef int SuperClass;
563         // @interface MyClass : SuperClass {} @end
564         //
565         if (!SuperClassDecl) {
566           Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
567           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
568         }
569       }
570 
571       if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
572         if (!SuperClassDecl)
573           Diag(SuperLoc, diag::err_undef_superclass)
574             << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
575         else if (RequireCompleteType(SuperLoc,
576                                   Context.getObjCInterfaceType(SuperClassDecl),
577                                      diag::err_forward_superclass,
578                                      SuperClassDecl->getDeclName(),
579                                      ClassName,
580                                      SourceRange(AtInterfaceLoc, ClassLoc))) {
581           SuperClassDecl = nullptr;
582         }
583       }
584       IDecl->setSuperClass(SuperClassDecl);
585       IDecl->setSuperClassLoc(SuperLoc);
586       IDecl->setEndOfDefinitionLoc(SuperLoc);
587     }
588   } else { // we have a root class.
589     IDecl->setEndOfDefinitionLoc(ClassLoc);
590   }
591 
592   // Check then save referenced protocols.
593   if (NumProtoRefs) {
594     IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
595                            ProtoLocs, Context);
596     IDecl->setEndOfDefinitionLoc(EndProtoLoc);
597   }
598 
599   CheckObjCDeclScope(IDecl);
600   return ActOnObjCContainerStartDefinition(IDecl);
601 }
602 
603 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
604 /// typedef'ed use for a qualified super class and adds them to the list
605 /// of the protocols.
606 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
607                                    IdentifierInfo *SuperName,
608                                    SourceLocation SuperLoc) {
609   if (!SuperName)
610     return;
611   NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
612                                       LookupOrdinaryName);
613   if (!IDecl)
614     return;
615 
616   if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
617     QualType T = TDecl->getUnderlyingType();
618     if (T->isObjCObjectType())
619       if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
620         ProtocolRefs.append(OPT->qual_begin(), OPT->qual_end());
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       TypoCorrection Corrected = CorrectTypo(
790           DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
791           LookupObjCProtocolName, TUScope, nullptr,
792           llvm::make_unique<DeclFilterCCC<ObjCProtocolDecl>>(),
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     TypoCorrection Corrected = CorrectTypo(
1031         DeclarationNameInfo(ClassName, ClassLoc), LookupOrdinaryName, TUScope,
1032         nullptr, llvm::make_unique<ObjCInterfaceValidatorCCC>(), CTK_NonError);
1033     if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1034       // Suggest the (potentially) correct interface name. Don't provide a
1035       // code-modification hint or use the typo name for recovery, because
1036       // this is just a warning. The program may actually be correct.
1037       diagnoseTypo(Corrected,
1038                    PDiag(diag::warn_undef_interface_suggest) << ClassName,
1039                    /*ErrorRecovery*/false);
1040     } else {
1041       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1042     }
1043   }
1044 
1045   // Check that super class name is valid class name
1046   ObjCInterfaceDecl *SDecl = nullptr;
1047   if (SuperClassname) {
1048     // Check if a different kind of symbol declared in this scope.
1049     PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1050                                 LookupOrdinaryName);
1051     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1052       Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1053         << SuperClassname;
1054       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1055     } else {
1056       SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1057       if (SDecl && !SDecl->hasDefinition())
1058         SDecl = nullptr;
1059       if (!SDecl)
1060         Diag(SuperClassLoc, diag::err_undef_superclass)
1061           << SuperClassname << ClassName;
1062       else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1063         // This implementation and its interface do not have the same
1064         // super class.
1065         Diag(SuperClassLoc, diag::err_conflicting_super_class)
1066           << SDecl->getDeclName();
1067         Diag(SDecl->getLocation(), diag::note_previous_definition);
1068       }
1069     }
1070   }
1071 
1072   if (!IDecl) {
1073     // Legacy case of @implementation with no corresponding @interface.
1074     // Build, chain & install the interface decl into the identifier.
1075 
1076     // FIXME: Do we support attributes on the @implementation? If so we should
1077     // copy them over.
1078     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1079                                       ClassName, /*PrevDecl=*/nullptr, ClassLoc,
1080                                       true);
1081     IDecl->startDefinition();
1082     if (SDecl) {
1083       IDecl->setSuperClass(SDecl);
1084       IDecl->setSuperClassLoc(SuperClassLoc);
1085       IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1086     } else {
1087       IDecl->setEndOfDefinitionLoc(ClassLoc);
1088     }
1089 
1090     PushOnScopeChains(IDecl, TUScope);
1091   } else {
1092     // Mark the interface as being completed, even if it was just as
1093     //   @class ....;
1094     // declaration; the user cannot reopen it.
1095     if (!IDecl->hasDefinition())
1096       IDecl->startDefinition();
1097   }
1098 
1099   ObjCImplementationDecl* IMPDecl =
1100     ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1101                                    ClassLoc, AtClassImplLoc, SuperClassLoc);
1102 
1103   if (CheckObjCDeclScope(IMPDecl))
1104     return ActOnObjCContainerStartDefinition(IMPDecl);
1105 
1106   // Check that there is no duplicate implementation of this class.
1107   if (IDecl->getImplementation()) {
1108     // FIXME: Don't leak everything!
1109     Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1110     Diag(IDecl->getImplementation()->getLocation(),
1111          diag::note_previous_definition);
1112     IMPDecl->setInvalidDecl();
1113   } else { // add it to the list.
1114     IDecl->setImplementation(IMPDecl);
1115     PushOnScopeChains(IMPDecl, TUScope);
1116     // Warn on implementating deprecated class under
1117     // -Wdeprecated-implementations flag.
1118     DiagnoseObjCImplementedDeprecations(*this,
1119                                         dyn_cast<NamedDecl>(IDecl),
1120                                         IMPDecl->getLocation(), 1);
1121   }
1122   return ActOnObjCContainerStartDefinition(IMPDecl);
1123 }
1124 
1125 Sema::DeclGroupPtrTy
1126 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1127   SmallVector<Decl *, 64> DeclsInGroup;
1128   DeclsInGroup.reserve(Decls.size() + 1);
1129 
1130   for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1131     Decl *Dcl = Decls[i];
1132     if (!Dcl)
1133       continue;
1134     if (Dcl->getDeclContext()->isFileContext())
1135       Dcl->setTopLevelDeclInObjCContainer();
1136     DeclsInGroup.push_back(Dcl);
1137   }
1138 
1139   DeclsInGroup.push_back(ObjCImpDecl);
1140 
1141   return BuildDeclaratorGroup(DeclsInGroup, false);
1142 }
1143 
1144 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1145                                     ObjCIvarDecl **ivars, unsigned numIvars,
1146                                     SourceLocation RBrace) {
1147   assert(ImpDecl && "missing implementation decl");
1148   ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
1149   if (!IDecl)
1150     return;
1151   /// Check case of non-existing \@interface decl.
1152   /// (legacy objective-c \@implementation decl without an \@interface decl).
1153   /// Add implementations's ivar to the synthesize class's ivar list.
1154   if (IDecl->isImplicitInterfaceDecl()) {
1155     IDecl->setEndOfDefinitionLoc(RBrace);
1156     // Add ivar's to class's DeclContext.
1157     for (unsigned i = 0, e = numIvars; i != e; ++i) {
1158       ivars[i]->setLexicalDeclContext(ImpDecl);
1159       IDecl->makeDeclVisibleInContext(ivars[i]);
1160       ImpDecl->addDecl(ivars[i]);
1161     }
1162 
1163     return;
1164   }
1165   // If implementation has empty ivar list, just return.
1166   if (numIvars == 0)
1167     return;
1168 
1169   assert(ivars && "missing @implementation ivars");
1170   if (LangOpts.ObjCRuntime.isNonFragile()) {
1171     if (ImpDecl->getSuperClass())
1172       Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1173     for (unsigned i = 0; i < numIvars; i++) {
1174       ObjCIvarDecl* ImplIvar = ivars[i];
1175       if (const ObjCIvarDecl *ClsIvar =
1176             IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1177         Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1178         Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1179         continue;
1180       }
1181       // Check class extensions (unnamed categories) for duplicate ivars.
1182       for (const auto *CDecl : IDecl->visible_extensions()) {
1183         if (const ObjCIvarDecl *ClsExtIvar =
1184             CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1185           Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1186           Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
1187           continue;
1188         }
1189       }
1190       // Instance ivar to Implementation's DeclContext.
1191       ImplIvar->setLexicalDeclContext(ImpDecl);
1192       IDecl->makeDeclVisibleInContext(ImplIvar);
1193       ImpDecl->addDecl(ImplIvar);
1194     }
1195     return;
1196   }
1197   // Check interface's Ivar list against those in the implementation.
1198   // names and types must match.
1199   //
1200   unsigned j = 0;
1201   ObjCInterfaceDecl::ivar_iterator
1202     IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1203   for (; numIvars > 0 && IVI != IVE; ++IVI) {
1204     ObjCIvarDecl* ImplIvar = ivars[j++];
1205     ObjCIvarDecl* ClsIvar = *IVI;
1206     assert (ImplIvar && "missing implementation ivar");
1207     assert (ClsIvar && "missing class ivar");
1208 
1209     // First, make sure the types match.
1210     if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1211       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1212         << ImplIvar->getIdentifier()
1213         << ImplIvar->getType() << ClsIvar->getType();
1214       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1215     } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1216                ImplIvar->getBitWidthValue(Context) !=
1217                ClsIvar->getBitWidthValue(Context)) {
1218       Diag(ImplIvar->getBitWidth()->getLocStart(),
1219            diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1220       Diag(ClsIvar->getBitWidth()->getLocStart(),
1221            diag::note_previous_definition);
1222     }
1223     // Make sure the names are identical.
1224     if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1225       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1226         << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1227       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1228     }
1229     --numIvars;
1230   }
1231 
1232   if (numIvars > 0)
1233     Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
1234   else if (IVI != IVE)
1235     Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
1236 }
1237 
1238 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
1239                                 ObjCMethodDecl *method,
1240                                 bool &IncompleteImpl,
1241                                 unsigned DiagID,
1242                                 NamedDecl *NeededFor = nullptr) {
1243   // No point warning no definition of method which is 'unavailable'.
1244   switch (method->getAvailability()) {
1245   case AR_Available:
1246   case AR_Deprecated:
1247     break;
1248 
1249       // Don't warn about unavailable or not-yet-introduced methods.
1250   case AR_NotYetIntroduced:
1251   case AR_Unavailable:
1252     return;
1253   }
1254 
1255   // FIXME: For now ignore 'IncompleteImpl'.
1256   // Previously we grouped all unimplemented methods under a single
1257   // warning, but some users strongly voiced that they would prefer
1258   // separate warnings.  We will give that approach a try, as that
1259   // matches what we do with protocols.
1260   {
1261     const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
1262     B << method;
1263     if (NeededFor)
1264       B << NeededFor;
1265   }
1266 
1267   // Issue a note to the original declaration.
1268   SourceLocation MethodLoc = method->getLocStart();
1269   if (MethodLoc.isValid())
1270     S.Diag(MethodLoc, diag::note_method_declared_at) << method;
1271 }
1272 
1273 /// Determines if type B can be substituted for type A.  Returns true if we can
1274 /// guarantee that anything that the user will do to an object of type A can
1275 /// also be done to an object of type B.  This is trivially true if the two
1276 /// types are the same, or if B is a subclass of A.  It becomes more complex
1277 /// in cases where protocols are involved.
1278 ///
1279 /// Object types in Objective-C describe the minimum requirements for an
1280 /// object, rather than providing a complete description of a type.  For
1281 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1282 /// The principle of substitutability means that we may use an instance of A
1283 /// anywhere that we may use an instance of B - it will implement all of the
1284 /// ivars of B and all of the methods of B.
1285 ///
1286 /// This substitutability is important when type checking methods, because
1287 /// the implementation may have stricter type definitions than the interface.
1288 /// The interface specifies minimum requirements, but the implementation may
1289 /// have more accurate ones.  For example, a method may privately accept
1290 /// instances of B, but only publish that it accepts instances of A.  Any
1291 /// object passed to it will be type checked against B, and so will implicitly
1292 /// by a valid A*.  Similarly, a method may return a subclass of the class that
1293 /// it is declared as returning.
1294 ///
1295 /// This is most important when considering subclassing.  A method in a
1296 /// subclass must accept any object as an argument that its superclass's
1297 /// implementation accepts.  It may, however, accept a more general type
1298 /// without breaking substitutability (i.e. you can still use the subclass
1299 /// anywhere that you can use the superclass, but not vice versa).  The
1300 /// converse requirement applies to return types: the return type for a
1301 /// subclass method must be a valid object of the kind that the superclass
1302 /// advertises, but it may be specified more accurately.  This avoids the need
1303 /// for explicit down-casting by callers.
1304 ///
1305 /// Note: This is a stricter requirement than for assignment.
1306 static bool isObjCTypeSubstitutable(ASTContext &Context,
1307                                     const ObjCObjectPointerType *A,
1308                                     const ObjCObjectPointerType *B,
1309                                     bool rejectId) {
1310   // Reject a protocol-unqualified id.
1311   if (rejectId && B->isObjCIdType()) return false;
1312 
1313   // If B is a qualified id, then A must also be a qualified id and it must
1314   // implement all of the protocols in B.  It may not be a qualified class.
1315   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1316   // stricter definition so it is not substitutable for id<A>.
1317   if (B->isObjCQualifiedIdType()) {
1318     return A->isObjCQualifiedIdType() &&
1319            Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1320                                                      QualType(B,0),
1321                                                      false);
1322   }
1323 
1324   /*
1325   // id is a special type that bypasses type checking completely.  We want a
1326   // warning when it is used in one place but not another.
1327   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1328 
1329 
1330   // If B is a qualified id, then A must also be a qualified id (which it isn't
1331   // if we've got this far)
1332   if (B->isObjCQualifiedIdType()) return false;
1333   */
1334 
1335   // Now we know that A and B are (potentially-qualified) class types.  The
1336   // normal rules for assignment apply.
1337   return Context.canAssignObjCInterfaces(A, B);
1338 }
1339 
1340 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1341   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1342 }
1343 
1344 static bool CheckMethodOverrideReturn(Sema &S,
1345                                       ObjCMethodDecl *MethodImpl,
1346                                       ObjCMethodDecl *MethodDecl,
1347                                       bool IsProtocolMethodDecl,
1348                                       bool IsOverridingMode,
1349                                       bool Warn) {
1350   if (IsProtocolMethodDecl &&
1351       (MethodDecl->getObjCDeclQualifier() !=
1352        MethodImpl->getObjCDeclQualifier())) {
1353     if (Warn) {
1354       S.Diag(MethodImpl->getLocation(),
1355              (IsOverridingMode
1356                   ? diag::warn_conflicting_overriding_ret_type_modifiers
1357                   : diag::warn_conflicting_ret_type_modifiers))
1358           << MethodImpl->getDeclName()
1359           << MethodImpl->getReturnTypeSourceRange();
1360       S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1361           << MethodDecl->getReturnTypeSourceRange();
1362     }
1363     else
1364       return false;
1365   }
1366 
1367   if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
1368                                        MethodDecl->getReturnType()))
1369     return true;
1370   if (!Warn)
1371     return false;
1372 
1373   unsigned DiagID =
1374     IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1375                      : diag::warn_conflicting_ret_types;
1376 
1377   // Mismatches between ObjC pointers go into a different warning
1378   // category, and sometimes they're even completely whitelisted.
1379   if (const ObjCObjectPointerType *ImplPtrTy =
1380           MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1381     if (const ObjCObjectPointerType *IfacePtrTy =
1382             MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1383       // Allow non-matching return types as long as they don't violate
1384       // the principle of substitutability.  Specifically, we permit
1385       // return types that are subclasses of the declared return type,
1386       // or that are more-qualified versions of the declared type.
1387       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1388         return false;
1389 
1390       DiagID =
1391         IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1392                           : diag::warn_non_covariant_ret_types;
1393     }
1394   }
1395 
1396   S.Diag(MethodImpl->getLocation(), DiagID)
1397       << MethodImpl->getDeclName() << MethodDecl->getReturnType()
1398       << MethodImpl->getReturnType()
1399       << MethodImpl->getReturnTypeSourceRange();
1400   S.Diag(MethodDecl->getLocation(), IsOverridingMode
1401                                         ? diag::note_previous_declaration
1402                                         : diag::note_previous_definition)
1403       << MethodDecl->getReturnTypeSourceRange();
1404   return false;
1405 }
1406 
1407 static bool CheckMethodOverrideParam(Sema &S,
1408                                      ObjCMethodDecl *MethodImpl,
1409                                      ObjCMethodDecl *MethodDecl,
1410                                      ParmVarDecl *ImplVar,
1411                                      ParmVarDecl *IfaceVar,
1412                                      bool IsProtocolMethodDecl,
1413                                      bool IsOverridingMode,
1414                                      bool Warn) {
1415   if (IsProtocolMethodDecl &&
1416       (ImplVar->getObjCDeclQualifier() !=
1417        IfaceVar->getObjCDeclQualifier())) {
1418     if (Warn) {
1419       if (IsOverridingMode)
1420         S.Diag(ImplVar->getLocation(),
1421                diag::warn_conflicting_overriding_param_modifiers)
1422             << getTypeRange(ImplVar->getTypeSourceInfo())
1423             << MethodImpl->getDeclName();
1424       else S.Diag(ImplVar->getLocation(),
1425              diag::warn_conflicting_param_modifiers)
1426           << getTypeRange(ImplVar->getTypeSourceInfo())
1427           << MethodImpl->getDeclName();
1428       S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1429           << getTypeRange(IfaceVar->getTypeSourceInfo());
1430     }
1431     else
1432       return false;
1433   }
1434 
1435   QualType ImplTy = ImplVar->getType();
1436   QualType IfaceTy = IfaceVar->getType();
1437 
1438   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1439     return true;
1440 
1441   if (!Warn)
1442     return false;
1443   unsigned DiagID =
1444     IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1445                      : diag::warn_conflicting_param_types;
1446 
1447   // Mismatches between ObjC pointers go into a different warning
1448   // category, and sometimes they're even completely whitelisted.
1449   if (const ObjCObjectPointerType *ImplPtrTy =
1450         ImplTy->getAs<ObjCObjectPointerType>()) {
1451     if (const ObjCObjectPointerType *IfacePtrTy =
1452           IfaceTy->getAs<ObjCObjectPointerType>()) {
1453       // Allow non-matching argument types as long as they don't
1454       // violate the principle of substitutability.  Specifically, the
1455       // implementation must accept any objects that the superclass
1456       // accepts, however it may also accept others.
1457       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1458         return false;
1459 
1460       DiagID =
1461       IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1462                        :  diag::warn_non_contravariant_param_types;
1463     }
1464   }
1465 
1466   S.Diag(ImplVar->getLocation(), DiagID)
1467     << getTypeRange(ImplVar->getTypeSourceInfo())
1468     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1469   S.Diag(IfaceVar->getLocation(),
1470          (IsOverridingMode ? diag::note_previous_declaration
1471                         : diag::note_previous_definition))
1472     << getTypeRange(IfaceVar->getTypeSourceInfo());
1473   return false;
1474 }
1475 
1476 /// In ARC, check whether the conventional meanings of the two methods
1477 /// match.  If they don't, it's a hard error.
1478 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1479                                       ObjCMethodDecl *decl) {
1480   ObjCMethodFamily implFamily = impl->getMethodFamily();
1481   ObjCMethodFamily declFamily = decl->getMethodFamily();
1482   if (implFamily == declFamily) return false;
1483 
1484   // Since conventions are sorted by selector, the only possibility is
1485   // that the types differ enough to cause one selector or the other
1486   // to fall out of the family.
1487   assert(implFamily == OMF_None || declFamily == OMF_None);
1488 
1489   // No further diagnostics required on invalid declarations.
1490   if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1491 
1492   const ObjCMethodDecl *unmatched = impl;
1493   ObjCMethodFamily family = declFamily;
1494   unsigned errorID = diag::err_arc_lost_method_convention;
1495   unsigned noteID = diag::note_arc_lost_method_convention;
1496   if (declFamily == OMF_None) {
1497     unmatched = decl;
1498     family = implFamily;
1499     errorID = diag::err_arc_gained_method_convention;
1500     noteID = diag::note_arc_gained_method_convention;
1501   }
1502 
1503   // Indexes into a %select clause in the diagnostic.
1504   enum FamilySelector {
1505     F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1506   };
1507   FamilySelector familySelector = FamilySelector();
1508 
1509   switch (family) {
1510   case OMF_None: llvm_unreachable("logic error, no method convention");
1511   case OMF_retain:
1512   case OMF_release:
1513   case OMF_autorelease:
1514   case OMF_dealloc:
1515   case OMF_finalize:
1516   case OMF_retainCount:
1517   case OMF_self:
1518   case OMF_initialize:
1519   case OMF_performSelector:
1520     // Mismatches for these methods don't change ownership
1521     // conventions, so we don't care.
1522     return false;
1523 
1524   case OMF_init: familySelector = F_init; break;
1525   case OMF_alloc: familySelector = F_alloc; break;
1526   case OMF_copy: familySelector = F_copy; break;
1527   case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1528   case OMF_new: familySelector = F_new; break;
1529   }
1530 
1531   enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1532   ReasonSelector reasonSelector;
1533 
1534   // The only reason these methods don't fall within their families is
1535   // due to unusual result types.
1536   if (unmatched->getReturnType()->isObjCObjectPointerType()) {
1537     reasonSelector = R_UnrelatedReturn;
1538   } else {
1539     reasonSelector = R_NonObjectReturn;
1540   }
1541 
1542   S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
1543   S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
1544 
1545   return true;
1546 }
1547 
1548 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1549                                        ObjCMethodDecl *MethodDecl,
1550                                        bool IsProtocolMethodDecl) {
1551   if (getLangOpts().ObjCAutoRefCount &&
1552       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1553     return;
1554 
1555   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1556                             IsProtocolMethodDecl, false,
1557                             true);
1558 
1559   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1560        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1561        EF = MethodDecl->param_end();
1562        IM != EM && IF != EF; ++IM, ++IF) {
1563     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1564                              IsProtocolMethodDecl, false, true);
1565   }
1566 
1567   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1568     Diag(ImpMethodDecl->getLocation(),
1569          diag::warn_conflicting_variadic);
1570     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1571   }
1572 }
1573 
1574 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1575                                        ObjCMethodDecl *Overridden,
1576                                        bool IsProtocolMethodDecl) {
1577 
1578   CheckMethodOverrideReturn(*this, Method, Overridden,
1579                             IsProtocolMethodDecl, true,
1580                             true);
1581 
1582   for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1583        IF = Overridden->param_begin(), EM = Method->param_end(),
1584        EF = Overridden->param_end();
1585        IM != EM && IF != EF; ++IM, ++IF) {
1586     CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1587                              IsProtocolMethodDecl, true, true);
1588   }
1589 
1590   if (Method->isVariadic() != Overridden->isVariadic()) {
1591     Diag(Method->getLocation(),
1592          diag::warn_conflicting_overriding_variadic);
1593     Diag(Overridden->getLocation(), diag::note_previous_declaration);
1594   }
1595 }
1596 
1597 /// WarnExactTypedMethods - This routine issues a warning if method
1598 /// implementation declaration matches exactly that of its declaration.
1599 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1600                                  ObjCMethodDecl *MethodDecl,
1601                                  bool IsProtocolMethodDecl) {
1602   // don't issue warning when protocol method is optional because primary
1603   // class is not required to implement it and it is safe for protocol
1604   // to implement it.
1605   if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1606     return;
1607   // don't issue warning when primary class's method is
1608   // depecated/unavailable.
1609   if (MethodDecl->hasAttr<UnavailableAttr>() ||
1610       MethodDecl->hasAttr<DeprecatedAttr>())
1611     return;
1612 
1613   bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1614                                       IsProtocolMethodDecl, false, false);
1615   if (match)
1616     for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1617          IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1618          EF = MethodDecl->param_end();
1619          IM != EM && IF != EF; ++IM, ++IF) {
1620       match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1621                                        *IM, *IF,
1622                                        IsProtocolMethodDecl, false, false);
1623       if (!match)
1624         break;
1625     }
1626   if (match)
1627     match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1628   if (match)
1629     match = !(MethodDecl->isClassMethod() &&
1630               MethodDecl->getSelector() == GetNullarySelector("load", Context));
1631 
1632   if (match) {
1633     Diag(ImpMethodDecl->getLocation(),
1634          diag::warn_category_method_impl_match);
1635     Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1636       << MethodDecl->getDeclName();
1637   }
1638 }
1639 
1640 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1641 /// improve the efficiency of selector lookups and type checking by associating
1642 /// with each protocol / interface / category the flattened instance tables. If
1643 /// we used an immutable set to keep the table then it wouldn't add significant
1644 /// memory cost and it would be handy for lookups.
1645 
1646 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
1647 typedef std::unique_ptr<ProtocolNameSet> LazyProtocolNameSet;
1648 
1649 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
1650                                            ProtocolNameSet &PNS) {
1651   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
1652     PNS.insert(PDecl->getIdentifier());
1653   for (const auto *PI : PDecl->protocols())
1654     findProtocolsWithExplicitImpls(PI, PNS);
1655 }
1656 
1657 /// Recursively populates a set with all conformed protocols in a class
1658 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
1659 /// attribute.
1660 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
1661                                            ProtocolNameSet &PNS) {
1662   if (!Super)
1663     return;
1664 
1665   for (const auto *I : Super->all_referenced_protocols())
1666     findProtocolsWithExplicitImpls(I, PNS);
1667 
1668   findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
1669 }
1670 
1671 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1672 /// Declared in protocol, and those referenced by it.
1673 static void CheckProtocolMethodDefs(Sema &S,
1674                                     SourceLocation ImpLoc,
1675                                     ObjCProtocolDecl *PDecl,
1676                                     bool& IncompleteImpl,
1677                                     const Sema::SelectorSet &InsMap,
1678                                     const Sema::SelectorSet &ClsMap,
1679                                     ObjCContainerDecl *CDecl,
1680                                     LazyProtocolNameSet &ProtocolsExplictImpl) {
1681   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1682   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1683                                : dyn_cast<ObjCInterfaceDecl>(CDecl);
1684   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1685 
1686   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1687   ObjCInterfaceDecl *NSIDecl = nullptr;
1688 
1689   // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
1690   // then we should check if any class in the super class hierarchy also
1691   // conforms to this protocol, either directly or via protocol inheritance.
1692   // If so, we can skip checking this protocol completely because we
1693   // know that a parent class already satisfies this protocol.
1694   //
1695   // Note: we could generalize this logic for all protocols, and merely
1696   // add the limit on looking at the super class chain for just
1697   // specially marked protocols.  This may be a good optimization.  This
1698   // change is restricted to 'objc_protocol_requires_explicit_implementation'
1699   // protocols for now for controlled evaluation.
1700   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
1701     if (!ProtocolsExplictImpl) {
1702       ProtocolsExplictImpl.reset(new ProtocolNameSet);
1703       findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
1704     }
1705     if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
1706         ProtocolsExplictImpl->end())
1707       return;
1708 
1709     // If no super class conforms to the protocol, we should not search
1710     // for methods in the super class to implicitly satisfy the protocol.
1711     Super = nullptr;
1712   }
1713 
1714   if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
1715     // check to see if class implements forwardInvocation method and objects
1716     // of this class are derived from 'NSProxy' so that to forward requests
1717     // from one object to another.
1718     // Under such conditions, which means that every method possible is
1719     // implemented in the class, we should not issue "Method definition not
1720     // found" warnings.
1721     // FIXME: Use a general GetUnarySelector method for this.
1722     IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
1723     Selector fISelector = S.Context.Selectors.getSelector(1, &II);
1724     if (InsMap.count(fISelector))
1725       // Is IDecl derived from 'NSProxy'? If so, no instance methods
1726       // need be implemented in the implementation.
1727       NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
1728   }
1729 
1730   // If this is a forward protocol declaration, get its definition.
1731   if (!PDecl->isThisDeclarationADefinition() &&
1732       PDecl->getDefinition())
1733     PDecl = PDecl->getDefinition();
1734 
1735   // If a method lookup fails locally we still need to look and see if
1736   // the method was implemented by a base class or an inherited
1737   // protocol. This lookup is slow, but occurs rarely in correct code
1738   // and otherwise would terminate in a warning.
1739 
1740   // check unimplemented instance methods.
1741   if (!NSIDecl)
1742     for (auto *method : PDecl->instance_methods()) {
1743       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1744           !method->isPropertyAccessor() &&
1745           !InsMap.count(method->getSelector()) &&
1746           (!Super || !Super->lookupMethod(method->getSelector(),
1747                                           true /* instance */,
1748                                           false /* shallowCategory */,
1749                                           true /* followsSuper */,
1750                                           nullptr /* category */))) {
1751             // If a method is not implemented in the category implementation but
1752             // has been declared in its primary class, superclass,
1753             // or in one of their protocols, no need to issue the warning.
1754             // This is because method will be implemented in the primary class
1755             // or one of its super class implementation.
1756 
1757             // Ugly, but necessary. Method declared in protcol might have
1758             // have been synthesized due to a property declared in the class which
1759             // uses the protocol.
1760             if (ObjCMethodDecl *MethodInClass =
1761                   IDecl->lookupMethod(method->getSelector(),
1762                                       true /* instance */,
1763                                       true /* shallowCategoryLookup */,
1764                                       false /* followSuper */))
1765               if (C || MethodInClass->isPropertyAccessor())
1766                 continue;
1767             unsigned DIAG = diag::warn_unimplemented_protocol_method;
1768             if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1769               WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
1770                                   PDecl);
1771             }
1772           }
1773     }
1774   // check unimplemented class methods
1775   for (auto *method : PDecl->class_methods()) {
1776     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1777         !ClsMap.count(method->getSelector()) &&
1778         (!Super || !Super->lookupMethod(method->getSelector(),
1779                                         false /* class method */,
1780                                         false /* shallowCategoryLookup */,
1781                                         true  /* followSuper */,
1782                                         nullptr /* category */))) {
1783       // See above comment for instance method lookups.
1784       if (C && IDecl->lookupMethod(method->getSelector(),
1785                                    false /* class */,
1786                                    true /* shallowCategoryLookup */,
1787                                    false /* followSuper */))
1788         continue;
1789 
1790       unsigned DIAG = diag::warn_unimplemented_protocol_method;
1791       if (!S.Diags.isIgnored(DIAG, ImpLoc)) {
1792         WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
1793       }
1794     }
1795   }
1796   // Check on this protocols's referenced protocols, recursively.
1797   for (auto *PI : PDecl->protocols())
1798     CheckProtocolMethodDefs(S, ImpLoc, PI, IncompleteImpl, InsMap, ClsMap,
1799                             CDecl, ProtocolsExplictImpl);
1800 }
1801 
1802 /// MatchAllMethodDeclarations - Check methods declared in interface
1803 /// or protocol against those declared in their implementations.
1804 ///
1805 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1806                                       const SelectorSet &ClsMap,
1807                                       SelectorSet &InsMapSeen,
1808                                       SelectorSet &ClsMapSeen,
1809                                       ObjCImplDecl* IMPDecl,
1810                                       ObjCContainerDecl* CDecl,
1811                                       bool &IncompleteImpl,
1812                                       bool ImmediateClass,
1813                                       bool WarnCategoryMethodImpl) {
1814   // Check and see if instance methods in class interface have been
1815   // implemented in the implementation class. If so, their types match.
1816   for (auto *I : CDecl->instance_methods()) {
1817     if (!InsMapSeen.insert(I->getSelector()).second)
1818       continue;
1819     if (!I->isPropertyAccessor() &&
1820         !InsMap.count(I->getSelector())) {
1821       if (ImmediateClass)
1822         WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1823                             diag::warn_undef_method_impl);
1824       continue;
1825     } else {
1826       ObjCMethodDecl *ImpMethodDecl =
1827         IMPDecl->getInstanceMethod(I->getSelector());
1828       assert(CDecl->getInstanceMethod(I->getSelector()) &&
1829              "Expected to find the method through lookup as well");
1830       // ImpMethodDecl may be null as in a @dynamic property.
1831       if (ImpMethodDecl) {
1832         if (!WarnCategoryMethodImpl)
1833           WarnConflictingTypedMethods(ImpMethodDecl, I,
1834                                       isa<ObjCProtocolDecl>(CDecl));
1835         else if (!I->isPropertyAccessor())
1836           WarnExactTypedMethods(ImpMethodDecl, I, isa<ObjCProtocolDecl>(CDecl));
1837       }
1838     }
1839   }
1840 
1841   // Check and see if class methods in class interface have been
1842   // implemented in the implementation class. If so, their types match.
1843   for (auto *I : CDecl->class_methods()) {
1844     if (!ClsMapSeen.insert(I->getSelector()).second)
1845       continue;
1846     if (!ClsMap.count(I->getSelector())) {
1847       if (ImmediateClass)
1848         WarnUndefinedMethod(*this, IMPDecl->getLocation(), I, IncompleteImpl,
1849                             diag::warn_undef_method_impl);
1850     } else {
1851       ObjCMethodDecl *ImpMethodDecl =
1852         IMPDecl->getClassMethod(I->getSelector());
1853       assert(CDecl->getClassMethod(I->getSelector()) &&
1854              "Expected to find the method through lookup as well");
1855       if (!WarnCategoryMethodImpl)
1856         WarnConflictingTypedMethods(ImpMethodDecl, I,
1857                                     isa<ObjCProtocolDecl>(CDecl));
1858       else
1859         WarnExactTypedMethods(ImpMethodDecl, I,
1860                               isa<ObjCProtocolDecl>(CDecl));
1861     }
1862   }
1863 
1864   if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
1865     // Also, check for methods declared in protocols inherited by
1866     // this protocol.
1867     for (auto *PI : PD->protocols())
1868       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1869                                  IMPDecl, PI, IncompleteImpl, false,
1870                                  WarnCategoryMethodImpl);
1871   }
1872 
1873   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1874     // when checking that methods in implementation match their declaration,
1875     // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1876     // extension; as well as those in categories.
1877     if (!WarnCategoryMethodImpl) {
1878       for (auto *Cat : I->visible_categories())
1879         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1880                                    IMPDecl, Cat, IncompleteImpl, false,
1881                                    WarnCategoryMethodImpl);
1882     } else {
1883       // Also methods in class extensions need be looked at next.
1884       for (auto *Ext : I->visible_extensions())
1885         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1886                                    IMPDecl, Ext, IncompleteImpl, false,
1887                                    WarnCategoryMethodImpl);
1888     }
1889 
1890     // Check for any implementation of a methods declared in protocol.
1891     for (auto *PI : I->all_referenced_protocols())
1892       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1893                                  IMPDecl, PI, IncompleteImpl, false,
1894                                  WarnCategoryMethodImpl);
1895 
1896     // FIXME. For now, we are not checking for extact match of methods
1897     // in category implementation and its primary class's super class.
1898     if (!WarnCategoryMethodImpl && I->getSuperClass())
1899       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1900                                  IMPDecl,
1901                                  I->getSuperClass(), IncompleteImpl, false);
1902   }
1903 }
1904 
1905 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1906 /// category matches with those implemented in its primary class and
1907 /// warns each time an exact match is found.
1908 void Sema::CheckCategoryVsClassMethodMatches(
1909                                   ObjCCategoryImplDecl *CatIMPDecl) {
1910   // Get category's primary class.
1911   ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1912   if (!CatDecl)
1913     return;
1914   ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1915   if (!IDecl)
1916     return;
1917   ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
1918   SelectorSet InsMap, ClsMap;
1919 
1920   for (const auto *I : CatIMPDecl->instance_methods()) {
1921     Selector Sel = I->getSelector();
1922     // When checking for methods implemented in the category, skip over
1923     // those declared in category class's super class. This is because
1924     // the super class must implement the method.
1925     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
1926       continue;
1927     InsMap.insert(Sel);
1928   }
1929 
1930   for (const auto *I : CatIMPDecl->class_methods()) {
1931     Selector Sel = I->getSelector();
1932     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
1933       continue;
1934     ClsMap.insert(Sel);
1935   }
1936   if (InsMap.empty() && ClsMap.empty())
1937     return;
1938 
1939   SelectorSet InsMapSeen, ClsMapSeen;
1940   bool IncompleteImpl = false;
1941   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1942                              CatIMPDecl, IDecl,
1943                              IncompleteImpl, false,
1944                              true /*WarnCategoryMethodImpl*/);
1945 }
1946 
1947 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1948                                      ObjCContainerDecl* CDecl,
1949                                      bool IncompleteImpl) {
1950   SelectorSet InsMap;
1951   // Check and see if instance methods in class interface have been
1952   // implemented in the implementation class.
1953   for (const auto *I : IMPDecl->instance_methods())
1954     InsMap.insert(I->getSelector());
1955 
1956   // Check and see if properties declared in the interface have either 1)
1957   // an implementation or 2) there is a @synthesize/@dynamic implementation
1958   // of the property in the @implementation.
1959   if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1960     bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
1961                                 LangOpts.ObjCRuntime.isNonFragile() &&
1962                                 !IDecl->isObjCRequiresPropertyDefs();
1963     DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
1964   }
1965 
1966   SelectorSet ClsMap;
1967   for (const auto *I : IMPDecl->class_methods())
1968     ClsMap.insert(I->getSelector());
1969 
1970   // Check for type conflict of methods declared in a class/protocol and
1971   // its implementation; if any.
1972   SelectorSet InsMapSeen, ClsMapSeen;
1973   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1974                              IMPDecl, CDecl,
1975                              IncompleteImpl, true);
1976 
1977   // check all methods implemented in category against those declared
1978   // in its primary class.
1979   if (ObjCCategoryImplDecl *CatDecl =
1980         dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
1981     CheckCategoryVsClassMethodMatches(CatDecl);
1982 
1983   // Check the protocol list for unimplemented methods in the @implementation
1984   // class.
1985   // Check and see if class methods in class interface have been
1986   // implemented in the implementation class.
1987 
1988   LazyProtocolNameSet ExplicitImplProtocols;
1989 
1990   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1991     for (auto *PI : I->all_referenced_protocols())
1992       CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), PI, IncompleteImpl,
1993                               InsMap, ClsMap, I, ExplicitImplProtocols);
1994     // Check class extensions (unnamed categories)
1995     for (auto *Ext : I->visible_extensions())
1996       ImplMethodsVsClassMethods(S, IMPDecl, Ext, IncompleteImpl);
1997   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1998     // For extended class, unimplemented methods in its protocols will
1999     // be reported in the primary class.
2000     if (!C->IsClassExtension()) {
2001       for (auto *P : C->protocols())
2002         CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), P,
2003                                 IncompleteImpl, InsMap, ClsMap, CDecl,
2004                                 ExplicitImplProtocols);
2005       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2006                                       /*SynthesizeProperties=*/false);
2007     }
2008   } else
2009     llvm_unreachable("invalid ObjCContainerDecl type.");
2010 }
2011 
2012 Sema::DeclGroupPtrTy
2013 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
2014                                    IdentifierInfo **IdentList,
2015                                    SourceLocation *IdentLocs,
2016                                    unsigned NumElts) {
2017   SmallVector<Decl *, 8> DeclsInGroup;
2018   for (unsigned i = 0; i != NumElts; ++i) {
2019     // Check for another declaration kind with the same name.
2020     NamedDecl *PrevDecl
2021       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
2022                          LookupOrdinaryName, ForRedeclaration);
2023     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2024       // GCC apparently allows the following idiom:
2025       //
2026       // typedef NSObject < XCElementTogglerP > XCElementToggler;
2027       // @class XCElementToggler;
2028       //
2029       // Here we have chosen to ignore the forward class declaration
2030       // with a warning. Since this is the implied behavior.
2031       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
2032       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
2033         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
2034         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2035       } else {
2036         // a forward class declaration matching a typedef name of a class refers
2037         // to the underlying class. Just ignore the forward class with a warning
2038         // as this will force the intended behavior which is to lookup the
2039         // typedef name.
2040         if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2041           Diag(AtClassLoc, diag::warn_forward_class_redefinition)
2042               << IdentList[i];
2043           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2044           continue;
2045         }
2046       }
2047     }
2048 
2049     // Create a declaration to describe this forward declaration.
2050     ObjCInterfaceDecl *PrevIDecl
2051       = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2052 
2053     IdentifierInfo *ClassName = IdentList[i];
2054     if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2055       // A previous decl with a different name is because of
2056       // @compatibility_alias, for example:
2057       // \code
2058       //   @class NewImage;
2059       //   @compatibility_alias OldImage NewImage;
2060       // \endcode
2061       // A lookup for 'OldImage' will return the 'NewImage' decl.
2062       //
2063       // In such a case use the real declaration name, instead of the alias one,
2064       // otherwise we will break IdentifierResolver and redecls-chain invariants.
2065       // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2066       // has been aliased.
2067       ClassName = PrevIDecl->getIdentifier();
2068     }
2069 
2070     ObjCInterfaceDecl *IDecl
2071       = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
2072                                   ClassName, PrevIDecl, IdentLocs[i]);
2073     IDecl->setAtEndRange(IdentLocs[i]);
2074 
2075     PushOnScopeChains(IDecl, TUScope);
2076     CheckObjCDeclScope(IDecl);
2077     DeclsInGroup.push_back(IDecl);
2078   }
2079 
2080   return BuildDeclaratorGroup(DeclsInGroup, false);
2081 }
2082 
2083 static bool tryMatchRecordTypes(ASTContext &Context,
2084                                 Sema::MethodMatchStrategy strategy,
2085                                 const Type *left, const Type *right);
2086 
2087 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2088                        QualType leftQT, QualType rightQT) {
2089   const Type *left =
2090     Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2091   const Type *right =
2092     Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2093 
2094   if (left == right) return true;
2095 
2096   // If we're doing a strict match, the types have to match exactly.
2097   if (strategy == Sema::MMS_strict) return false;
2098 
2099   if (left->isIncompleteType() || right->isIncompleteType()) return false;
2100 
2101   // Otherwise, use this absurdly complicated algorithm to try to
2102   // validate the basic, low-level compatibility of the two types.
2103 
2104   // As a minimum, require the sizes and alignments to match.
2105   TypeInfo LeftTI = Context.getTypeInfo(left);
2106   TypeInfo RightTI = Context.getTypeInfo(right);
2107   if (LeftTI.Width != RightTI.Width)
2108     return false;
2109 
2110   if (LeftTI.Align != RightTI.Align)
2111     return false;
2112 
2113   // Consider all the kinds of non-dependent canonical types:
2114   // - functions and arrays aren't possible as return and parameter types
2115 
2116   // - vector types of equal size can be arbitrarily mixed
2117   if (isa<VectorType>(left)) return isa<VectorType>(right);
2118   if (isa<VectorType>(right)) return false;
2119 
2120   // - references should only match references of identical type
2121   // - structs, unions, and Objective-C objects must match more-or-less
2122   //   exactly
2123   // - everything else should be a scalar
2124   if (!left->isScalarType() || !right->isScalarType())
2125     return tryMatchRecordTypes(Context, strategy, left, right);
2126 
2127   // Make scalars agree in kind, except count bools as chars, and group
2128   // all non-member pointers together.
2129   Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2130   Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2131   if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2132   if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
2133   if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2134     leftSK = Type::STK_ObjCObjectPointer;
2135   if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2136     rightSK = Type::STK_ObjCObjectPointer;
2137 
2138   // Note that data member pointers and function member pointers don't
2139   // intermix because of the size differences.
2140 
2141   return (leftSK == rightSK);
2142 }
2143 
2144 static bool tryMatchRecordTypes(ASTContext &Context,
2145                                 Sema::MethodMatchStrategy strategy,
2146                                 const Type *lt, const Type *rt) {
2147   assert(lt && rt && lt != rt);
2148 
2149   if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2150   RecordDecl *left = cast<RecordType>(lt)->getDecl();
2151   RecordDecl *right = cast<RecordType>(rt)->getDecl();
2152 
2153   // Require union-hood to match.
2154   if (left->isUnion() != right->isUnion()) return false;
2155 
2156   // Require an exact match if either is non-POD.
2157   if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2158       (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2159     return false;
2160 
2161   // Require size and alignment to match.
2162   TypeInfo LeftTI = Context.getTypeInfo(lt);
2163   TypeInfo RightTI = Context.getTypeInfo(rt);
2164   if (LeftTI.Width != RightTI.Width)
2165     return false;
2166 
2167   if (LeftTI.Align != RightTI.Align)
2168     return false;
2169 
2170   // Require fields to match.
2171   RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2172   RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2173   for (; li != le && ri != re; ++li, ++ri) {
2174     if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2175       return false;
2176   }
2177   return (li == le && ri == re);
2178 }
2179 
2180 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2181 /// returns true, or false, accordingly.
2182 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
2183 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2184                                       const ObjCMethodDecl *right,
2185                                       MethodMatchStrategy strategy) {
2186   if (!matchTypes(Context, strategy, left->getReturnType(),
2187                   right->getReturnType()))
2188     return false;
2189 
2190   // If either is hidden, it is not considered to match.
2191   if (left->isHidden() || right->isHidden())
2192     return false;
2193 
2194   if (getLangOpts().ObjCAutoRefCount &&
2195       (left->hasAttr<NSReturnsRetainedAttr>()
2196          != right->hasAttr<NSReturnsRetainedAttr>() ||
2197        left->hasAttr<NSConsumesSelfAttr>()
2198          != right->hasAttr<NSConsumesSelfAttr>()))
2199     return false;
2200 
2201   ObjCMethodDecl::param_const_iterator
2202     li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2203     re = right->param_end();
2204 
2205   for (; li != le && ri != re; ++li, ++ri) {
2206     assert(ri != right->param_end() && "Param mismatch");
2207     const ParmVarDecl *lparm = *li, *rparm = *ri;
2208 
2209     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2210       return false;
2211 
2212     if (getLangOpts().ObjCAutoRefCount &&
2213         lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2214       return false;
2215   }
2216   return true;
2217 }
2218 
2219 void Sema::addMethodToGlobalList(ObjCMethodList *List,
2220                                  ObjCMethodDecl *Method) {
2221   // Record at the head of the list whether there were 0, 1, or >= 2 methods
2222   // inside categories.
2223   if (ObjCCategoryDecl *CD =
2224           dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
2225     if (!CD->IsClassExtension() && List->getBits() < 2)
2226       List->setBits(List->getBits() + 1);
2227 
2228   // If the list is empty, make it a singleton list.
2229   if (List->getMethod() == nullptr) {
2230     List->setMethod(Method);
2231     List->setNext(nullptr);
2232     return;
2233   }
2234 
2235   // We've seen a method with this name, see if we have already seen this type
2236   // signature.
2237   ObjCMethodList *Previous = List;
2238   for (; List; Previous = List, List = List->getNext()) {
2239     // If we are building a module, keep all of the methods.
2240     if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
2241       continue;
2242 
2243     if (!MatchTwoMethodDeclarations(Method, List->getMethod()))
2244       continue;
2245 
2246     ObjCMethodDecl *PrevObjCMethod = List->getMethod();
2247 
2248     // Propagate the 'defined' bit.
2249     if (Method->isDefined())
2250       PrevObjCMethod->setDefined(true);
2251     else {
2252       // Objective-C doesn't allow an @interface for a class after its
2253       // @implementation. So if Method is not defined and there already is
2254       // an entry for this type signature, Method has to be for a different
2255       // class than PrevObjCMethod.
2256       List->setHasMoreThanOneDecl(true);
2257     }
2258 
2259     // If a method is deprecated, push it in the global pool.
2260     // This is used for better diagnostics.
2261     if (Method->isDeprecated()) {
2262       if (!PrevObjCMethod->isDeprecated())
2263         List->setMethod(Method);
2264     }
2265     // If the new method is unavailable, push it into global pool
2266     // unless previous one is deprecated.
2267     if (Method->isUnavailable()) {
2268       if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2269         List->setMethod(Method);
2270     }
2271 
2272     return;
2273   }
2274 
2275   // We have a new signature for an existing method - add it.
2276   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2277   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
2278   Previous->setNext(new (Mem) ObjCMethodList(Method));
2279 }
2280 
2281 /// \brief Read the contents of the method pool for a given selector from
2282 /// external storage.
2283 void Sema::ReadMethodPool(Selector Sel) {
2284   assert(ExternalSource && "We need an external AST source");
2285   ExternalSource->ReadMethodPool(Sel);
2286 }
2287 
2288 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
2289                                  bool instance) {
2290   // Ignore methods of invalid containers.
2291   if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
2292     return;
2293 
2294   if (ExternalSource)
2295     ReadMethodPool(Method->getSelector());
2296 
2297   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
2298   if (Pos == MethodPool.end())
2299     Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2300                                            GlobalMethods())).first;
2301 
2302   Method->setDefined(impl);
2303 
2304   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
2305   addMethodToGlobalList(&Entry, Method);
2306 }
2307 
2308 /// Determines if this is an "acceptable" loose mismatch in the global
2309 /// method pool.  This exists mostly as a hack to get around certain
2310 /// global mismatches which we can't afford to make warnings / errors.
2311 /// Really, what we want is a way to take a method out of the global
2312 /// method pool.
2313 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2314                                        ObjCMethodDecl *other) {
2315   if (!chosen->isInstanceMethod())
2316     return false;
2317 
2318   Selector sel = chosen->getSelector();
2319   if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2320     return false;
2321 
2322   // Don't complain about mismatches for -length if the method we
2323   // chose has an integral result type.
2324   return (chosen->getReturnType()->isIntegerType());
2325 }
2326 
2327 bool Sema::CollectMultipleMethodsInGlobalPool(
2328     Selector Sel, SmallVectorImpl<ObjCMethodDecl *> &Methods, bool instance) {
2329   if (ExternalSource)
2330     ReadMethodPool(Sel);
2331 
2332   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2333   if (Pos == MethodPool.end())
2334     return false;
2335   // Gather the non-hidden methods.
2336   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2337   for (ObjCMethodList *M = &MethList; M; M = M->getNext())
2338     if (M->getMethod() && !M->getMethod()->isHidden())
2339       Methods.push_back(M->getMethod());
2340   return Methods.size() > 1;
2341 }
2342 
2343 bool Sema::AreMultipleMethodsInGlobalPool(Selector Sel, bool instance) {
2344   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2345   // Test for no method in the pool which should not trigger any warning by
2346   // caller.
2347   if (Pos == MethodPool.end())
2348     return true;
2349   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2350   return MethList.hasMoreThanOneDecl();
2351 }
2352 
2353 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2354                                                bool receiverIdOrClass,
2355                                                bool warn, bool instance) {
2356   if (ExternalSource)
2357     ReadMethodPool(Sel);
2358 
2359   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2360   if (Pos == MethodPool.end())
2361     return nullptr;
2362 
2363   // Gather the non-hidden methods.
2364   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2365   SmallVector<ObjCMethodDecl *, 4> Methods;
2366   for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
2367     if (M->getMethod() && !M->getMethod()->isHidden()) {
2368       // If we're not supposed to warn about mismatches, we're done.
2369       if (!warn)
2370         return M->getMethod();
2371 
2372       Methods.push_back(M->getMethod());
2373     }
2374   }
2375 
2376   // If there aren't any visible methods, we're done.
2377   // FIXME: Recover if there are any known-but-hidden methods?
2378   if (Methods.empty())
2379     return nullptr;
2380 
2381   if (Methods.size() == 1)
2382     return Methods[0];
2383 
2384   // We found multiple methods, so we may have to complain.
2385   bool issueDiagnostic = false, issueError = false;
2386 
2387   // We support a warning which complains about *any* difference in
2388   // method signature.
2389   bool strictSelectorMatch =
2390       receiverIdOrClass && warn &&
2391       !Diags.isIgnored(diag::warn_strict_multiple_method_decl, R.getBegin());
2392   if (strictSelectorMatch) {
2393     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2394       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2395         issueDiagnostic = true;
2396         break;
2397       }
2398     }
2399   }
2400 
2401   // If we didn't see any strict differences, we won't see any loose
2402   // differences.  In ARC, however, we also need to check for loose
2403   // mismatches, because most of them are errors.
2404   if (!strictSelectorMatch ||
2405       (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2406     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2407       // This checks if the methods differ in type mismatch.
2408       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2409           !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2410         issueDiagnostic = true;
2411         if (getLangOpts().ObjCAutoRefCount)
2412           issueError = true;
2413         break;
2414       }
2415     }
2416 
2417   if (issueDiagnostic) {
2418     if (issueError)
2419       Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2420     else if (strictSelectorMatch)
2421       Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2422     else
2423       Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2424 
2425     Diag(Methods[0]->getLocStart(),
2426          issueError ? diag::note_possibility : diag::note_using)
2427       << Methods[0]->getSourceRange();
2428     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2429       Diag(Methods[I]->getLocStart(), diag::note_also_found)
2430         << Methods[I]->getSourceRange();
2431   }
2432   }
2433   return Methods[0];
2434 }
2435 
2436 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2437   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2438   if (Pos == MethodPool.end())
2439     return nullptr;
2440 
2441   GlobalMethods &Methods = Pos->second;
2442   for (const ObjCMethodList *Method = &Methods.first; Method;
2443        Method = Method->getNext())
2444     if (Method->getMethod() && Method->getMethod()->isDefined())
2445       return Method->getMethod();
2446 
2447   for (const ObjCMethodList *Method = &Methods.second; Method;
2448        Method = Method->getNext())
2449     if (Method->getMethod() && Method->getMethod()->isDefined())
2450       return Method->getMethod();
2451   return nullptr;
2452 }
2453 
2454 static void
2455 HelperSelectorsForTypoCorrection(
2456                       SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
2457                       StringRef Typo, const ObjCMethodDecl * Method) {
2458   const unsigned MaxEditDistance = 1;
2459   unsigned BestEditDistance = MaxEditDistance + 1;
2460   std::string MethodName = Method->getSelector().getAsString();
2461 
2462   unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
2463   if (MinPossibleEditDistance > 0 &&
2464       Typo.size() / MinPossibleEditDistance < 1)
2465     return;
2466   unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
2467   if (EditDistance > MaxEditDistance)
2468     return;
2469   if (EditDistance == BestEditDistance)
2470     BestMethod.push_back(Method);
2471   else if (EditDistance < BestEditDistance) {
2472     BestMethod.clear();
2473     BestMethod.push_back(Method);
2474   }
2475 }
2476 
2477 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
2478                                      QualType ObjectType) {
2479   if (ObjectType.isNull())
2480     return true;
2481   if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
2482     return true;
2483   return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) !=
2484          nullptr;
2485 }
2486 
2487 const ObjCMethodDecl *
2488 Sema::SelectorsForTypoCorrection(Selector Sel,
2489                                  QualType ObjectType) {
2490   unsigned NumArgs = Sel.getNumArgs();
2491   SmallVector<const ObjCMethodDecl *, 8> Methods;
2492   bool ObjectIsId = true, ObjectIsClass = true;
2493   if (ObjectType.isNull())
2494     ObjectIsId = ObjectIsClass = false;
2495   else if (!ObjectType->isObjCObjectPointerType())
2496     return nullptr;
2497   else if (const ObjCObjectPointerType *ObjCPtr =
2498            ObjectType->getAsObjCInterfacePointerType()) {
2499     ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
2500     ObjectIsId = ObjectIsClass = false;
2501   }
2502   else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
2503     ObjectIsClass = false;
2504   else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
2505     ObjectIsId = false;
2506   else
2507     return nullptr;
2508 
2509   for (GlobalMethodPool::iterator b = MethodPool.begin(),
2510        e = MethodPool.end(); b != e; b++) {
2511     // instance methods
2512     for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
2513       if (M->getMethod() &&
2514           (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
2515           (M->getMethod()->getSelector() != Sel)) {
2516         if (ObjectIsId)
2517           Methods.push_back(M->getMethod());
2518         else if (!ObjectIsClass &&
2519                  HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
2520                                           ObjectType))
2521           Methods.push_back(M->getMethod());
2522       }
2523     // class methods
2524     for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
2525       if (M->getMethod() &&
2526           (M->getMethod()->getSelector().getNumArgs() == NumArgs) &&
2527           (M->getMethod()->getSelector() != Sel)) {
2528         if (ObjectIsClass)
2529           Methods.push_back(M->getMethod());
2530         else if (!ObjectIsId &&
2531                  HelperIsMethodInObjCType(*this, M->getMethod()->getSelector(),
2532                                           ObjectType))
2533           Methods.push_back(M->getMethod());
2534       }
2535   }
2536 
2537   SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
2538   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
2539     HelperSelectorsForTypoCorrection(SelectedMethods,
2540                                      Sel.getAsString(), Methods[i]);
2541   }
2542   return (SelectedMethods.size() == 1) ? SelectedMethods[0] : nullptr;
2543 }
2544 
2545 /// DiagnoseDuplicateIvars -
2546 /// Check for duplicate ivars in the entire class at the start of
2547 /// \@implementation. This becomes necesssary because class extension can
2548 /// add ivars to a class in random order which will not be known until
2549 /// class's \@implementation is seen.
2550 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2551                                   ObjCInterfaceDecl *SID) {
2552   for (auto *Ivar : ID->ivars()) {
2553     if (Ivar->isInvalidDecl())
2554       continue;
2555     if (IdentifierInfo *II = Ivar->getIdentifier()) {
2556       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2557       if (prevIvar) {
2558         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2559         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2560         Ivar->setInvalidDecl();
2561       }
2562     }
2563   }
2564 }
2565 
2566 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2567   switch (CurContext->getDeclKind()) {
2568     case Decl::ObjCInterface:
2569       return Sema::OCK_Interface;
2570     case Decl::ObjCProtocol:
2571       return Sema::OCK_Protocol;
2572     case Decl::ObjCCategory:
2573       if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2574         return Sema::OCK_ClassExtension;
2575       else
2576         return Sema::OCK_Category;
2577     case Decl::ObjCImplementation:
2578       return Sema::OCK_Implementation;
2579     case Decl::ObjCCategoryImpl:
2580       return Sema::OCK_CategoryImplementation;
2581 
2582     default:
2583       return Sema::OCK_None;
2584   }
2585 }
2586 
2587 // Note: For class/category implementations, allMethods is always null.
2588 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
2589                        ArrayRef<DeclGroupPtrTy> allTUVars) {
2590   if (getObjCContainerKind() == Sema::OCK_None)
2591     return nullptr;
2592 
2593   assert(AtEnd.isValid() && "Invalid location for '@end'");
2594 
2595   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2596   Decl *ClassDecl = cast<Decl>(OCD);
2597 
2598   bool isInterfaceDeclKind =
2599         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2600          || isa<ObjCProtocolDecl>(ClassDecl);
2601   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2602 
2603   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2604   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2605   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2606 
2607   for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
2608     ObjCMethodDecl *Method =
2609       cast_or_null<ObjCMethodDecl>(allMethods[i]);
2610 
2611     if (!Method) continue;  // Already issued a diagnostic.
2612     if (Method->isInstanceMethod()) {
2613       /// Check for instance method of the same name with incompatible types
2614       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2615       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2616                               : false;
2617       if ((isInterfaceDeclKind && PrevMethod && !match)
2618           || (checkIdenticalMethods && match)) {
2619           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2620             << Method->getDeclName();
2621           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2622         Method->setInvalidDecl();
2623       } else {
2624         if (PrevMethod) {
2625           Method->setAsRedeclaration(PrevMethod);
2626           if (!Context.getSourceManager().isInSystemHeader(
2627                  Method->getLocation()))
2628             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2629               << Method->getDeclName();
2630           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2631         }
2632         InsMap[Method->getSelector()] = Method;
2633         /// The following allows us to typecheck messages to "id".
2634         AddInstanceMethodToGlobalPool(Method);
2635       }
2636     } else {
2637       /// Check for class method of the same name with incompatible types
2638       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2639       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2640                               : false;
2641       if ((isInterfaceDeclKind && PrevMethod && !match)
2642           || (checkIdenticalMethods && match)) {
2643         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2644           << Method->getDeclName();
2645         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2646         Method->setInvalidDecl();
2647       } else {
2648         if (PrevMethod) {
2649           Method->setAsRedeclaration(PrevMethod);
2650           if (!Context.getSourceManager().isInSystemHeader(
2651                  Method->getLocation()))
2652             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2653               << Method->getDeclName();
2654           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2655         }
2656         ClsMap[Method->getSelector()] = Method;
2657         AddFactoryMethodToGlobalPool(Method);
2658       }
2659     }
2660   }
2661   if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2662     // Nothing to do here.
2663   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2664     // Categories are used to extend the class by declaring new methods.
2665     // By the same token, they are also used to add new properties. No
2666     // need to compare the added property to those in the class.
2667 
2668     if (C->IsClassExtension()) {
2669       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2670       DiagnoseClassExtensionDupMethods(C, CCPrimary);
2671     }
2672   }
2673   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2674     if (CDecl->getIdentifier())
2675       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2676       // user-defined setter/getter. It also synthesizes setter/getter methods
2677       // and adds them to the DeclContext and global method pools.
2678       for (auto *I : CDecl->properties())
2679         ProcessPropertyDecl(I, CDecl);
2680     CDecl->setAtEndRange(AtEnd);
2681   }
2682   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2683     IC->setAtEndRange(AtEnd);
2684     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2685       // Any property declared in a class extension might have user
2686       // declared setter or getter in current class extension or one
2687       // of the other class extensions. Mark them as synthesized as
2688       // property will be synthesized when property with same name is
2689       // seen in the @implementation.
2690       for (const auto *Ext : IDecl->visible_extensions()) {
2691         for (const auto *Property : Ext->properties()) {
2692           // Skip over properties declared @dynamic
2693           if (const ObjCPropertyImplDecl *PIDecl
2694               = IC->FindPropertyImplDecl(Property->getIdentifier()))
2695             if (PIDecl->getPropertyImplementation()
2696                   == ObjCPropertyImplDecl::Dynamic)
2697               continue;
2698 
2699           for (const auto *Ext : IDecl->visible_extensions()) {
2700             if (ObjCMethodDecl *GetterMethod
2701                   = Ext->getInstanceMethod(Property->getGetterName()))
2702               GetterMethod->setPropertyAccessor(true);
2703             if (!Property->isReadOnly())
2704               if (ObjCMethodDecl *SetterMethod
2705                     = Ext->getInstanceMethod(Property->getSetterName()))
2706                 SetterMethod->setPropertyAccessor(true);
2707           }
2708         }
2709       }
2710       ImplMethodsVsClassMethods(S, IC, IDecl);
2711       AtomicPropertySetterGetterRules(IC, IDecl);
2712       DiagnoseOwningPropertyGetterSynthesis(IC);
2713       DiagnoseUnusedBackingIvarInAccessor(S, IC);
2714       if (IDecl->hasDesignatedInitializers())
2715         DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
2716 
2717       bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
2718       if (IDecl->getSuperClass() == nullptr) {
2719         // This class has no superclass, so check that it has been marked with
2720         // __attribute((objc_root_class)).
2721         if (!HasRootClassAttr) {
2722           SourceLocation DeclLoc(IDecl->getLocation());
2723           SourceLocation SuperClassLoc(getLocForEndOfToken(DeclLoc));
2724           Diag(DeclLoc, diag::warn_objc_root_class_missing)
2725             << IDecl->getIdentifier();
2726           // See if NSObject is in the current scope, and if it is, suggest
2727           // adding " : NSObject " to the class declaration.
2728           NamedDecl *IF = LookupSingleName(TUScope,
2729                                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2730                                            DeclLoc, LookupOrdinaryName);
2731           ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2732           if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2733             Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2734               << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2735           } else {
2736             Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2737           }
2738         }
2739       } else if (HasRootClassAttr) {
2740         // Complain that only root classes may have this attribute.
2741         Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2742       }
2743 
2744       if (LangOpts.ObjCRuntime.isNonFragile()) {
2745         while (IDecl->getSuperClass()) {
2746           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2747           IDecl = IDecl->getSuperClass();
2748         }
2749       }
2750     }
2751     SetIvarInitializers(IC);
2752   } else if (ObjCCategoryImplDecl* CatImplClass =
2753                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2754     CatImplClass->setAtEndRange(AtEnd);
2755 
2756     // Find category interface decl and then check that all methods declared
2757     // in this interface are implemented in the category @implementation.
2758     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2759       if (ObjCCategoryDecl *Cat
2760             = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2761         ImplMethodsVsClassMethods(S, CatImplClass, Cat);
2762       }
2763     }
2764   }
2765   if (isInterfaceDeclKind) {
2766     // Reject invalid vardecls.
2767     for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2768       DeclGroupRef DG = allTUVars[i].get();
2769       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2770         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2771           if (!VDecl->hasExternalStorage())
2772             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2773         }
2774     }
2775   }
2776   ActOnObjCContainerFinishDefinition();
2777 
2778   for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2779     DeclGroupRef DG = allTUVars[i].get();
2780     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2781       (*I)->setTopLevelDeclInObjCContainer();
2782     Consumer.HandleTopLevelDeclInObjCContainer(DG);
2783   }
2784 
2785   ActOnDocumentableDecl(ClassDecl);
2786   return ClassDecl;
2787 }
2788 
2789 
2790 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2791 /// objective-c's type qualifier from the parser version of the same info.
2792 static Decl::ObjCDeclQualifier
2793 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2794   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2795 }
2796 
2797 /// \brief Check whether the declared result type of the given Objective-C
2798 /// method declaration is compatible with the method's class.
2799 ///
2800 static Sema::ResultTypeCompatibilityKind
2801 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2802                                     ObjCInterfaceDecl *CurrentClass) {
2803   QualType ResultType = Method->getReturnType();
2804 
2805   // If an Objective-C method inherits its related result type, then its
2806   // declared result type must be compatible with its own class type. The
2807   // declared result type is compatible if:
2808   if (const ObjCObjectPointerType *ResultObjectType
2809                                 = ResultType->getAs<ObjCObjectPointerType>()) {
2810     //   - it is id or qualified id, or
2811     if (ResultObjectType->isObjCIdType() ||
2812         ResultObjectType->isObjCQualifiedIdType())
2813       return Sema::RTC_Compatible;
2814 
2815     if (CurrentClass) {
2816       if (ObjCInterfaceDecl *ResultClass
2817                                       = ResultObjectType->getInterfaceDecl()) {
2818         //   - it is the same as the method's class type, or
2819         if (declaresSameEntity(CurrentClass, ResultClass))
2820           return Sema::RTC_Compatible;
2821 
2822         //   - it is a superclass of the method's class type
2823         if (ResultClass->isSuperClassOf(CurrentClass))
2824           return Sema::RTC_Compatible;
2825       }
2826     } else {
2827       // Any Objective-C pointer type might be acceptable for a protocol
2828       // method; we just don't know.
2829       return Sema::RTC_Unknown;
2830     }
2831   }
2832 
2833   return Sema::RTC_Incompatible;
2834 }
2835 
2836 namespace {
2837 /// A helper class for searching for methods which a particular method
2838 /// overrides.
2839 class OverrideSearch {
2840 public:
2841   Sema &S;
2842   ObjCMethodDecl *Method;
2843   llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
2844   bool Recursive;
2845 
2846 public:
2847   OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2848     Selector selector = method->getSelector();
2849 
2850     // Bypass this search if we've never seen an instance/class method
2851     // with this selector before.
2852     Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2853     if (it == S.MethodPool.end()) {
2854       if (!S.getExternalSource()) return;
2855       S.ReadMethodPool(selector);
2856 
2857       it = S.MethodPool.find(selector);
2858       if (it == S.MethodPool.end())
2859         return;
2860     }
2861     ObjCMethodList &list =
2862       method->isInstanceMethod() ? it->second.first : it->second.second;
2863     if (!list.getMethod()) return;
2864 
2865     ObjCContainerDecl *container
2866       = cast<ObjCContainerDecl>(method->getDeclContext());
2867 
2868     // Prevent the search from reaching this container again.  This is
2869     // important with categories, which override methods from the
2870     // interface and each other.
2871     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2872       searchFromContainer(container);
2873       if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2874         searchFromContainer(Interface);
2875     } else {
2876       searchFromContainer(container);
2877     }
2878   }
2879 
2880   typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
2881   iterator begin() const { return Overridden.begin(); }
2882   iterator end() const { return Overridden.end(); }
2883 
2884 private:
2885   void searchFromContainer(ObjCContainerDecl *container) {
2886     if (container->isInvalidDecl()) return;
2887 
2888     switch (container->getDeclKind()) {
2889 #define OBJCCONTAINER(type, base) \
2890     case Decl::type: \
2891       searchFrom(cast<type##Decl>(container)); \
2892       break;
2893 #define ABSTRACT_DECL(expansion)
2894 #define DECL(type, base) \
2895     case Decl::type:
2896 #include "clang/AST/DeclNodes.inc"
2897       llvm_unreachable("not an ObjC container!");
2898     }
2899   }
2900 
2901   void searchFrom(ObjCProtocolDecl *protocol) {
2902     if (!protocol->hasDefinition())
2903       return;
2904 
2905     // A method in a protocol declaration overrides declarations from
2906     // referenced ("parent") protocols.
2907     search(protocol->getReferencedProtocols());
2908   }
2909 
2910   void searchFrom(ObjCCategoryDecl *category) {
2911     // A method in a category declaration overrides declarations from
2912     // the main class and from protocols the category references.
2913     // The main class is handled in the constructor.
2914     search(category->getReferencedProtocols());
2915   }
2916 
2917   void searchFrom(ObjCCategoryImplDecl *impl) {
2918     // A method in a category definition that has a category
2919     // declaration overrides declarations from the category
2920     // declaration.
2921     if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2922       search(category);
2923       if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2924         search(Interface);
2925 
2926     // Otherwise it overrides declarations from the class.
2927     } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2928       search(Interface);
2929     }
2930   }
2931 
2932   void searchFrom(ObjCInterfaceDecl *iface) {
2933     // A method in a class declaration overrides declarations from
2934     if (!iface->hasDefinition())
2935       return;
2936 
2937     //   - categories,
2938     for (auto *Cat : iface->known_categories())
2939       search(Cat);
2940 
2941     //   - the super class, and
2942     if (ObjCInterfaceDecl *super = iface->getSuperClass())
2943       search(super);
2944 
2945     //   - any referenced protocols.
2946     search(iface->getReferencedProtocols());
2947   }
2948 
2949   void searchFrom(ObjCImplementationDecl *impl) {
2950     // A method in a class implementation overrides declarations from
2951     // the class interface.
2952     if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2953       search(Interface);
2954   }
2955 
2956 
2957   void search(const ObjCProtocolList &protocols) {
2958     for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2959          i != e; ++i)
2960       search(*i);
2961   }
2962 
2963   void search(ObjCContainerDecl *container) {
2964     // Check for a method in this container which matches this selector.
2965     ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2966                                                 Method->isInstanceMethod(),
2967                                                 /*AllowHidden=*/true);
2968 
2969     // If we find one, record it and bail out.
2970     if (meth) {
2971       Overridden.insert(meth);
2972       return;
2973     }
2974 
2975     // Otherwise, search for methods that a hypothetical method here
2976     // would have overridden.
2977 
2978     // Note that we're now in a recursive case.
2979     Recursive = true;
2980 
2981     searchFromContainer(container);
2982   }
2983 };
2984 }
2985 
2986 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
2987                                     ObjCInterfaceDecl *CurrentClass,
2988                                     ResultTypeCompatibilityKind RTC) {
2989   // Search for overridden methods and merge information down from them.
2990   OverrideSearch overrides(*this, ObjCMethod);
2991   // Keep track if the method overrides any method in the class's base classes,
2992   // its protocols, or its categories' protocols; we will keep that info
2993   // in the ObjCMethodDecl.
2994   // For this info, a method in an implementation is not considered as
2995   // overriding the same method in the interface or its categories.
2996   bool hasOverriddenMethodsInBaseOrProtocol = false;
2997   for (OverrideSearch::iterator
2998          i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2999     ObjCMethodDecl *overridden = *i;
3000 
3001     if (!hasOverriddenMethodsInBaseOrProtocol) {
3002       if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
3003           CurrentClass != overridden->getClassInterface() ||
3004           overridden->isOverriding()) {
3005         hasOverriddenMethodsInBaseOrProtocol = true;
3006 
3007       } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
3008         // OverrideSearch will return as "overridden" the same method in the
3009         // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
3010         // check whether a category of a base class introduced a method with the
3011         // same selector, after the interface method declaration.
3012         // To avoid unnecessary lookups in the majority of cases, we use the
3013         // extra info bits in GlobalMethodPool to check whether there were any
3014         // category methods with this selector.
3015         GlobalMethodPool::iterator It =
3016             MethodPool.find(ObjCMethod->getSelector());
3017         if (It != MethodPool.end()) {
3018           ObjCMethodList &List =
3019             ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3020           unsigned CategCount = List.getBits();
3021           if (CategCount > 0) {
3022             // If the method is in a category we'll do lookup if there were at
3023             // least 2 category methods recorded, otherwise only one will do.
3024             if (CategCount > 1 ||
3025                 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3026               OverrideSearch overrides(*this, overridden);
3027               for (OverrideSearch::iterator
3028                      OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3029                 ObjCMethodDecl *SuperOverridden = *OI;
3030                 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3031                     CurrentClass != SuperOverridden->getClassInterface()) {
3032                   hasOverriddenMethodsInBaseOrProtocol = true;
3033                   overridden->setOverriding(true);
3034                   break;
3035                 }
3036               }
3037             }
3038           }
3039         }
3040       }
3041     }
3042 
3043     // Propagate down the 'related result type' bit from overridden methods.
3044     if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3045       ObjCMethod->SetRelatedResultType();
3046 
3047     // Then merge the declarations.
3048     mergeObjCMethodDecls(ObjCMethod, overridden);
3049 
3050     if (ObjCMethod->isImplicit() && overridden->isImplicit())
3051       continue; // Conflicting properties are detected elsewhere.
3052 
3053     // Check for overriding methods
3054     if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3055         isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3056       CheckConflictingOverridingMethod(ObjCMethod, overridden,
3057               isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3058 
3059     if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
3060         isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3061         !overridden->isImplicit() /* not meant for properties */) {
3062       ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3063                                           E = ObjCMethod->param_end();
3064       ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3065                                      PrevE = overridden->param_end();
3066       for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
3067         assert(PrevI != overridden->param_end() && "Param mismatch");
3068         QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3069         QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3070         // If type of argument of method in this class does not match its
3071         // respective argument type in the super class method, issue warning;
3072         if (!Context.typesAreCompatible(T1, T2)) {
3073           Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3074             << T1 << T2;
3075           Diag(overridden->getLocation(), diag::note_previous_declaration);
3076           break;
3077         }
3078       }
3079     }
3080   }
3081 
3082   ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3083 }
3084 
3085 Decl *Sema::ActOnMethodDeclaration(
3086     Scope *S,
3087     SourceLocation MethodLoc, SourceLocation EndLoc,
3088     tok::TokenKind MethodType,
3089     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
3090     ArrayRef<SourceLocation> SelectorLocs,
3091     Selector Sel,
3092     // optional arguments. The number of types/arguments is obtained
3093     // from the Sel.getNumArgs().
3094     ObjCArgInfo *ArgInfo,
3095     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
3096     AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
3097     bool isVariadic, bool MethodDefinition) {
3098   // Make sure we can establish a context for the method.
3099   if (!CurContext->isObjCContainer()) {
3100     Diag(MethodLoc, diag::error_missing_method_context);
3101     return nullptr;
3102   }
3103   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3104   Decl *ClassDecl = cast<Decl>(OCD);
3105   QualType resultDeclType;
3106 
3107   bool HasRelatedResultType = false;
3108   TypeSourceInfo *ReturnTInfo = nullptr;
3109   if (ReturnType) {
3110     resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
3111 
3112     if (CheckFunctionReturnType(resultDeclType, MethodLoc))
3113       return nullptr;
3114 
3115     HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
3116   } else { // get the type for "id".
3117     resultDeclType = Context.getObjCIdType();
3118     Diag(MethodLoc, diag::warn_missing_method_return_type)
3119       << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
3120   }
3121 
3122   ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
3123       Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
3124       MethodType == tok::minus, isVariadic,
3125       /*isPropertyAccessor=*/false,
3126       /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
3127       MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
3128                                            : ObjCMethodDecl::Required,
3129       HasRelatedResultType);
3130 
3131   SmallVector<ParmVarDecl*, 16> Params;
3132 
3133   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
3134     QualType ArgType;
3135     TypeSourceInfo *DI;
3136 
3137     if (!ArgInfo[i].Type) {
3138       ArgType = Context.getObjCIdType();
3139       DI = nullptr;
3140     } else {
3141       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
3142     }
3143 
3144     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
3145                    LookupOrdinaryName, ForRedeclaration);
3146     LookupName(R, S);
3147     if (R.isSingleResult()) {
3148       NamedDecl *PrevDecl = R.getFoundDecl();
3149       if (S->isDeclScope(PrevDecl)) {
3150         Diag(ArgInfo[i].NameLoc,
3151              (MethodDefinition ? diag::warn_method_param_redefinition
3152                                : diag::warn_method_param_declaration))
3153           << ArgInfo[i].Name;
3154         Diag(PrevDecl->getLocation(),
3155              diag::note_previous_declaration);
3156       }
3157     }
3158 
3159     SourceLocation StartLoc = DI
3160       ? DI->getTypeLoc().getBeginLoc()
3161       : ArgInfo[i].NameLoc;
3162 
3163     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
3164                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
3165                                         ArgType, DI, SC_None);
3166 
3167     Param->setObjCMethodScopeInfo(i);
3168 
3169     Param->setObjCDeclQualifier(
3170       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
3171 
3172     // Apply the attributes to the parameter.
3173     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
3174 
3175     if (Param->hasAttr<BlocksAttr>()) {
3176       Diag(Param->getLocation(), diag::err_block_on_nonlocal);
3177       Param->setInvalidDecl();
3178     }
3179     S->AddDecl(Param);
3180     IdResolver.AddDecl(Param);
3181 
3182     Params.push_back(Param);
3183   }
3184 
3185   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
3186     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
3187     QualType ArgType = Param->getType();
3188     if (ArgType.isNull())
3189       ArgType = Context.getObjCIdType();
3190     else
3191       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
3192       ArgType = Context.getAdjustedParameterType(ArgType);
3193 
3194     Param->setDeclContext(ObjCMethod);
3195     Params.push_back(Param);
3196   }
3197 
3198   ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
3199   ObjCMethod->setObjCDeclQualifier(
3200     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
3201 
3202   if (AttrList)
3203     ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
3204 
3205   // Add the method now.
3206   const ObjCMethodDecl *PrevMethod = nullptr;
3207   if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
3208     if (MethodType == tok::minus) {
3209       PrevMethod = ImpDecl->getInstanceMethod(Sel);
3210       ImpDecl->addInstanceMethod(ObjCMethod);
3211     } else {
3212       PrevMethod = ImpDecl->getClassMethod(Sel);
3213       ImpDecl->addClassMethod(ObjCMethod);
3214     }
3215 
3216     ObjCMethodDecl *IMD = nullptr;
3217     if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
3218       IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
3219                                 ObjCMethod->isInstanceMethod());
3220     if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
3221         !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
3222       // merge the attribute into implementation.
3223       ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
3224                                                    ObjCMethod->getLocation()));
3225     }
3226     if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
3227       ObjCMethodFamily family =
3228         ObjCMethod->getSelector().getMethodFamily();
3229       if (family == OMF_dealloc && IMD && IMD->isOverriding())
3230         Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
3231           << ObjCMethod->getDeclName();
3232     }
3233   } else {
3234     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
3235   }
3236 
3237   if (PrevMethod) {
3238     // You can never have two method definitions with the same name.
3239     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
3240       << ObjCMethod->getDeclName();
3241     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3242     ObjCMethod->setInvalidDecl();
3243     return ObjCMethod;
3244   }
3245 
3246   // If this Objective-C method does not have a related result type, but we
3247   // are allowed to infer related result types, try to do so based on the
3248   // method family.
3249   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3250   if (!CurrentClass) {
3251     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3252       CurrentClass = Cat->getClassInterface();
3253     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3254       CurrentClass = Impl->getClassInterface();
3255     else if (ObjCCategoryImplDecl *CatImpl
3256                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3257       CurrentClass = CatImpl->getClassInterface();
3258   }
3259 
3260   ResultTypeCompatibilityKind RTC
3261     = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
3262 
3263   CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
3264 
3265   bool ARCError = false;
3266   if (getLangOpts().ObjCAutoRefCount)
3267     ARCError = CheckARCMethodDecl(ObjCMethod);
3268 
3269   // Infer the related result type when possible.
3270   if (!ARCError && RTC == Sema::RTC_Compatible &&
3271       !ObjCMethod->hasRelatedResultType() &&
3272       LangOpts.ObjCInferRelatedResultType) {
3273     bool InferRelatedResultType = false;
3274     switch (ObjCMethod->getMethodFamily()) {
3275     case OMF_None:
3276     case OMF_copy:
3277     case OMF_dealloc:
3278     case OMF_finalize:
3279     case OMF_mutableCopy:
3280     case OMF_release:
3281     case OMF_retainCount:
3282     case OMF_initialize:
3283     case OMF_performSelector:
3284       break;
3285 
3286     case OMF_alloc:
3287     case OMF_new:
3288       InferRelatedResultType = ObjCMethod->isClassMethod();
3289       break;
3290 
3291     case OMF_init:
3292     case OMF_autorelease:
3293     case OMF_retain:
3294     case OMF_self:
3295       InferRelatedResultType = ObjCMethod->isInstanceMethod();
3296       break;
3297     }
3298 
3299     if (InferRelatedResultType)
3300       ObjCMethod->SetRelatedResultType();
3301   }
3302 
3303   ActOnDocumentableDecl(ObjCMethod);
3304 
3305   return ObjCMethod;
3306 }
3307 
3308 bool Sema::CheckObjCDeclScope(Decl *D) {
3309   // Following is also an error. But it is caused by a missing @end
3310   // and diagnostic is issued elsewhere.
3311   if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
3312     return false;
3313 
3314   // If we switched context to translation unit while we are still lexically in
3315   // an objc container, it means the parser missed emitting an error.
3316   if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3317     return false;
3318 
3319   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3320   D->setInvalidDecl();
3321 
3322   return true;
3323 }
3324 
3325 /// Called whenever \@defs(ClassName) is encountered in the source.  Inserts the
3326 /// instance variables of ClassName into Decls.
3327 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3328                      IdentifierInfo *ClassName,
3329                      SmallVectorImpl<Decl*> &Decls) {
3330   // Check that ClassName is a valid class
3331   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
3332   if (!Class) {
3333     Diag(DeclStart, diag::err_undef_interface) << ClassName;
3334     return;
3335   }
3336   if (LangOpts.ObjCRuntime.isNonFragile()) {
3337     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3338     return;
3339   }
3340 
3341   // Collect the instance variables
3342   SmallVector<const ObjCIvarDecl*, 32> Ivars;
3343   Context.DeepCollectObjCIvars(Class, true, Ivars);
3344   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
3345   for (unsigned i = 0; i < Ivars.size(); i++) {
3346     const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
3347     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
3348     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3349                                            /*FIXME: StartL=*/ID->getLocation(),
3350                                            ID->getLocation(),
3351                                            ID->getIdentifier(), ID->getType(),
3352                                            ID->getBitWidth());
3353     Decls.push_back(FD);
3354   }
3355 
3356   // Introduce all of these fields into the appropriate scope.
3357   for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
3358        D != Decls.end(); ++D) {
3359     FieldDecl *FD = cast<FieldDecl>(*D);
3360     if (getLangOpts().CPlusPlus)
3361       PushOnScopeChains(cast<FieldDecl>(FD), S);
3362     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
3363       Record->addDecl(FD);
3364   }
3365 }
3366 
3367 /// \brief Build a type-check a new Objective-C exception variable declaration.
3368 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3369                                       SourceLocation StartLoc,
3370                                       SourceLocation IdLoc,
3371                                       IdentifierInfo *Id,
3372                                       bool Invalid) {
3373   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3374   // duration shall not be qualified by an address-space qualifier."
3375   // Since all parameters have automatic store duration, they can not have
3376   // an address space.
3377   if (T.getAddressSpace() != 0) {
3378     Diag(IdLoc, diag::err_arg_with_address_space);
3379     Invalid = true;
3380   }
3381 
3382   // An @catch parameter must be an unqualified object pointer type;
3383   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3384   if (Invalid) {
3385     // Don't do any further checking.
3386   } else if (T->isDependentType()) {
3387     // Okay: we don't know what this type will instantiate to.
3388   } else if (!T->isObjCObjectPointerType()) {
3389     Invalid = true;
3390     Diag(IdLoc ,diag::err_catch_param_not_objc_type);
3391   } else if (T->isObjCQualifiedIdType()) {
3392     Invalid = true;
3393     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
3394   }
3395 
3396   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
3397                                  T, TInfo, SC_None);
3398   New->setExceptionVariable(true);
3399 
3400   // In ARC, infer 'retaining' for variables of retainable type.
3401   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
3402     Invalid = true;
3403 
3404   if (Invalid)
3405     New->setInvalidDecl();
3406   return New;
3407 }
3408 
3409 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
3410   const DeclSpec &DS = D.getDeclSpec();
3411 
3412   // We allow the "register" storage class on exception variables because
3413   // GCC did, but we drop it completely. Any other storage class is an error.
3414   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3415     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3416       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
3417   } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3418     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
3419       << DeclSpec::getSpecifierName(SCS);
3420   }
3421   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
3422     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
3423          diag::err_invalid_thread)
3424      << DeclSpec::getSpecifierName(TSCS);
3425   D.getMutableDeclSpec().ClearStorageClassSpecs();
3426 
3427   DiagnoseFunctionSpecifiers(D.getDeclSpec());
3428 
3429   // Check that there are no default arguments inside the type of this
3430   // exception object (C++ only).
3431   if (getLangOpts().CPlusPlus)
3432     CheckExtraCXXDefaultArguments(D);
3433 
3434   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3435   QualType ExceptionType = TInfo->getType();
3436 
3437   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3438                                         D.getSourceRange().getBegin(),
3439                                         D.getIdentifierLoc(),
3440                                         D.getIdentifier(),
3441                                         D.isInvalidType());
3442 
3443   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3444   if (D.getCXXScopeSpec().isSet()) {
3445     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3446       << D.getCXXScopeSpec().getRange();
3447     New->setInvalidDecl();
3448   }
3449 
3450   // Add the parameter declaration into this scope.
3451   S->AddDecl(New);
3452   if (D.getIdentifier())
3453     IdResolver.AddDecl(New);
3454 
3455   ProcessDeclAttributes(S, New, D);
3456 
3457   if (New->hasAttr<BlocksAttr>())
3458     Diag(New->getLocation(), diag::err_block_on_nonlocal);
3459   return New;
3460 }
3461 
3462 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3463 /// initialization.
3464 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3465                                 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
3466   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3467        Iv= Iv->getNextIvar()) {
3468     QualType QT = Context.getBaseElementType(Iv->getType());
3469     if (QT->isRecordType())
3470       Ivars.push_back(Iv);
3471   }
3472 }
3473 
3474 void Sema::DiagnoseUseOfUnimplementedSelectors() {
3475   // Load referenced selectors from the external source.
3476   if (ExternalSource) {
3477     SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3478     ExternalSource->ReadReferencedSelectors(Sels);
3479     for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3480       ReferencedSelectors[Sels[I].first] = Sels[I].second;
3481   }
3482 
3483   // Warning will be issued only when selector table is
3484   // generated (which means there is at lease one implementation
3485   // in the TU). This is to match gcc's behavior.
3486   if (ReferencedSelectors.empty() ||
3487       !Context.AnyObjCImplementation())
3488     return;
3489   for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
3490         ReferencedSelectors.begin(),
3491        E = ReferencedSelectors.end(); S != E; ++S) {
3492     Selector Sel = (*S).first;
3493     if (!LookupImplementedMethodInGlobalPool(Sel))
3494       Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
3495   }
3496   return;
3497 }
3498 
3499 ObjCIvarDecl *
3500 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3501                                      const ObjCPropertyDecl *&PDecl) const {
3502   if (Method->isClassMethod())
3503     return nullptr;
3504   const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
3505   if (!IDecl)
3506     return nullptr;
3507   Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
3508                                /*shallowCategoryLookup=*/false,
3509                                /*followSuper=*/false);
3510   if (!Method || !Method->isPropertyAccessor())
3511     return nullptr;
3512   if ((PDecl = Method->findPropertyDecl()))
3513     if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
3514       // property backing ivar must belong to property's class
3515       // or be a private ivar in class's implementation.
3516       // FIXME. fix the const-ness issue.
3517       IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
3518                                                         IV->getIdentifier());
3519       return IV;
3520     }
3521   return nullptr;
3522 }
3523 
3524 namespace {
3525   /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
3526   /// accessor references the backing ivar.
3527   class UnusedBackingIvarChecker :
3528       public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
3529   public:
3530     Sema &S;
3531     const ObjCMethodDecl *Method;
3532     const ObjCIvarDecl *IvarD;
3533     bool AccessedIvar;
3534     bool InvokedSelfMethod;
3535 
3536     UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
3537                              const ObjCIvarDecl *IvarD)
3538       : S(S), Method(Method), IvarD(IvarD),
3539         AccessedIvar(false), InvokedSelfMethod(false) {
3540       assert(IvarD);
3541     }
3542 
3543     bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
3544       if (E->getDecl() == IvarD) {
3545         AccessedIvar = true;
3546         return false;
3547       }
3548       return true;
3549     }
3550 
3551     bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
3552       if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
3553           S.isSelfExpr(E->getInstanceReceiver(), Method)) {
3554         InvokedSelfMethod = true;
3555       }
3556       return true;
3557     }
3558   };
3559 }
3560 
3561 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3562                                           const ObjCImplementationDecl *ImplD) {
3563   if (S->hasUnrecoverableErrorOccurred())
3564     return;
3565 
3566   for (const auto *CurMethod : ImplD->instance_methods()) {
3567     unsigned DIAG = diag::warn_unused_property_backing_ivar;
3568     SourceLocation Loc = CurMethod->getLocation();
3569     if (Diags.isIgnored(DIAG, Loc))
3570       continue;
3571 
3572     const ObjCPropertyDecl *PDecl;
3573     const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
3574     if (!IV)
3575       continue;
3576 
3577     UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
3578     Checker.TraverseStmt(CurMethod->getBody());
3579     if (Checker.AccessedIvar)
3580       continue;
3581 
3582     // Do not issue this warning if backing ivar is used somewhere and accessor
3583     // implementation makes a self call. This is to prevent false positive in
3584     // cases where the ivar is accessed by another method that the accessor
3585     // delegates to.
3586     if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
3587       Diag(Loc, DIAG) << IV;
3588       Diag(PDecl->getLocation(), diag::note_property_declare);
3589     }
3590   }
3591 }
3592