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