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