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