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