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