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