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