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