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