1 //===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements semantic analysis for Objective C declarations.
11 //
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Sema/SemaInternal.h"
15 #include "clang/AST/ASTConsumer.h"
16 #include "clang/AST/ASTContext.h"
17 #include "clang/AST/ASTMutationListener.h"
18 #include "clang/AST/DataRecursiveASTVisitor.h"
19 #include "clang/AST/DeclObjC.h"
20 #include "clang/AST/Expr.h"
21 #include "clang/AST/ExprObjC.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Lex/Preprocessor.h"
24 #include "clang/Sema/DeclSpec.h"
25 #include "clang/Sema/ExternalSemaSource.h"
26 #include "clang/Sema/Lookup.h"
27 #include "clang/Sema/Scope.h"
28 #include "clang/Sema/ScopeInfo.h"
29 #include "llvm/ADT/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 = 0;
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                 "init method returns a type unrelated to its receiver type",
103                 loc));
104     return true;
105   }
106 
107   // Otherwise, it's an error.
108   Diag(loc, diag::err_arc_init_method_unrelated_result_type);
109   method->setInvalidDecl();
110   return true;
111 }
112 
113 void Sema::CheckObjCMethodOverride(ObjCMethodDecl *NewMethod,
114                                    const ObjCMethodDecl *Overridden) {
115   if (Overridden->hasRelatedResultType() &&
116       !NewMethod->hasRelatedResultType()) {
117     // This can only happen when the method follows a naming convention that
118     // implies a related result type, and the original (overridden) method has
119     // a suitable return type, but the new (overriding) method does not have
120     // a suitable return type.
121     QualType ResultType = NewMethod->getReturnType();
122     SourceRange ResultTypeRange;
123     if (const TypeSourceInfo *ResultTypeInfo =
124             NewMethod->getReturnTypeSourceInfo())
125       ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
126 
127     // Figure out which class this method is part of, if any.
128     ObjCInterfaceDecl *CurrentClass
129       = dyn_cast<ObjCInterfaceDecl>(NewMethod->getDeclContext());
130     if (!CurrentClass) {
131       DeclContext *DC = NewMethod->getDeclContext();
132       if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(DC))
133         CurrentClass = Cat->getClassInterface();
134       else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(DC))
135         CurrentClass = Impl->getClassInterface();
136       else if (ObjCCategoryImplDecl *CatImpl
137                = dyn_cast<ObjCCategoryImplDecl>(DC))
138         CurrentClass = CatImpl->getClassInterface();
139     }
140 
141     if (CurrentClass) {
142       Diag(NewMethod->getLocation(),
143            diag::warn_related_result_type_compatibility_class)
144         << Context.getObjCInterfaceType(CurrentClass)
145         << ResultType
146         << ResultTypeRange;
147     } else {
148       Diag(NewMethod->getLocation(),
149            diag::warn_related_result_type_compatibility_protocol)
150         << ResultType
151         << ResultTypeRange;
152     }
153 
154     if (ObjCMethodFamily Family = Overridden->getMethodFamily())
155       Diag(Overridden->getLocation(),
156            diag::note_related_result_type_family)
157         << /*overridden method*/ 0
158         << Family;
159     else
160       Diag(Overridden->getLocation(),
161            diag::note_related_result_type_overridden);
162   }
163   if (getLangOpts().ObjCAutoRefCount) {
164     if ((NewMethod->hasAttr<NSReturnsRetainedAttr>() !=
165          Overridden->hasAttr<NSReturnsRetainedAttr>())) {
166         Diag(NewMethod->getLocation(),
167              diag::err_nsreturns_retained_attribute_mismatch) << 1;
168         Diag(Overridden->getLocation(), diag::note_previous_decl)
169         << "method";
170     }
171     if ((NewMethod->hasAttr<NSReturnsNotRetainedAttr>() !=
172               Overridden->hasAttr<NSReturnsNotRetainedAttr>())) {
173         Diag(NewMethod->getLocation(),
174              diag::err_nsreturns_retained_attribute_mismatch) << 0;
175         Diag(Overridden->getLocation(), diag::note_previous_decl)
176         << "method";
177     }
178     ObjCMethodDecl::param_const_iterator oi = Overridden->param_begin(),
179                                          oe = Overridden->param_end();
180     for (ObjCMethodDecl::param_iterator
181            ni = NewMethod->param_begin(), ne = NewMethod->param_end();
182          ni != ne && oi != oe; ++ni, ++oi) {
183       const ParmVarDecl *oldDecl = (*oi);
184       ParmVarDecl *newDecl = (*ni);
185       if (newDecl->hasAttr<NSConsumedAttr>() !=
186           oldDecl->hasAttr<NSConsumedAttr>()) {
187         Diag(newDecl->getLocation(),
188              diag::err_nsconsumed_attribute_mismatch);
189         Diag(oldDecl->getLocation(), diag::note_previous_decl)
190           << "parameter";
191       }
192     }
193   }
194 }
195 
196 /// \brief Check a method declaration for compatibility with the Objective-C
197 /// ARC conventions.
198 bool Sema::CheckARCMethodDecl(ObjCMethodDecl *method) {
199   ObjCMethodFamily family = method->getMethodFamily();
200   switch (family) {
201   case OMF_None:
202   case OMF_finalize:
203   case OMF_retain:
204   case OMF_release:
205   case OMF_autorelease:
206   case OMF_retainCount:
207   case OMF_self:
208   case OMF_performSelector:
209     return false;
210 
211   case OMF_dealloc:
212     if (!Context.hasSameType(method->getReturnType(), Context.VoidTy)) {
213       SourceRange ResultTypeRange;
214       if (const TypeSourceInfo *ResultTypeInfo =
215               method->getReturnTypeSourceInfo())
216         ResultTypeRange = ResultTypeInfo->getTypeLoc().getSourceRange();
217       if (ResultTypeRange.isInvalid())
218         Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
219             << method->getReturnType()
220             << FixItHint::CreateInsertion(method->getSelectorLoc(0), "(void)");
221       else
222         Diag(method->getLocation(), diag::error_dealloc_bad_result_type)
223             << method->getReturnType()
224             << FixItHint::CreateReplacement(ResultTypeRange, "void");
225       return true;
226     }
227     return false;
228 
229   case OMF_init:
230     // If the method doesn't obey the init rules, don't bother annotating it.
231     if (checkInitMethod(method, QualType()))
232       return true;
233 
234     method->addAttr(NSConsumesSelfAttr::CreateImplicit(Context));
235 
236     // Don't add a second copy of this attribute, but otherwise don't
237     // let it be suppressed.
238     if (method->hasAttr<NSReturnsRetainedAttr>())
239       return false;
240     break;
241 
242   case OMF_alloc:
243   case OMF_copy:
244   case OMF_mutableCopy:
245   case OMF_new:
246     if (method->hasAttr<NSReturnsRetainedAttr>() ||
247         method->hasAttr<NSReturnsNotRetainedAttr>() ||
248         method->hasAttr<NSReturnsAutoreleasedAttr>())
249       return false;
250     break;
251   }
252 
253   method->addAttr(NSReturnsRetainedAttr::CreateImplicit(Context));
254   return false;
255 }
256 
257 static void DiagnoseObjCImplementedDeprecations(Sema &S,
258                                                 NamedDecl *ND,
259                                                 SourceLocation ImplLoc,
260                                                 int select) {
261   if (ND && ND->isDeprecated()) {
262     S.Diag(ImplLoc, diag::warn_deprecated_def) << select;
263     if (select == 0)
264       S.Diag(ND->getLocation(), diag::note_method_declared_at)
265         << ND->getDeclName();
266     else
267       S.Diag(ND->getLocation(), diag::note_previous_decl) << "class";
268   }
269 }
270 
271 /// AddAnyMethodToGlobalPool - Add any method, instance or factory to global
272 /// pool.
273 void Sema::AddAnyMethodToGlobalPool(Decl *D) {
274   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
275 
276   // If we don't have a valid method decl, simply return.
277   if (!MDecl)
278     return;
279   if (MDecl->isInstanceMethod())
280     AddInstanceMethodToGlobalPool(MDecl, true);
281   else
282     AddFactoryMethodToGlobalPool(MDecl, true);
283 }
284 
285 /// HasExplicitOwnershipAttr - returns true when pointer to ObjC pointer
286 /// has explicit ownership attribute; false otherwise.
287 static bool
288 HasExplicitOwnershipAttr(Sema &S, ParmVarDecl *Param) {
289   QualType T = Param->getType();
290 
291   if (const PointerType *PT = T->getAs<PointerType>()) {
292     T = PT->getPointeeType();
293   } else if (const ReferenceType *RT = T->getAs<ReferenceType>()) {
294     T = RT->getPointeeType();
295   } else {
296     return true;
297   }
298 
299   // If we have a lifetime qualifier, but it's local, we must have
300   // inferred it. So, it is implicit.
301   return !T.getLocalQualifiers().hasObjCLifetime();
302 }
303 
304 /// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
305 /// and user declared, in the method definition's AST.
306 void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, Decl *D) {
307   assert((getCurMethodDecl() == 0) && "Methodparsing confused");
308   ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D);
309 
310   // If we don't have a valid method decl, simply return.
311   if (!MDecl)
312     return;
313 
314   // Allow all of Sema to see that we are entering a method definition.
315   PushDeclContext(FnBodyScope, MDecl);
316   PushFunctionScope();
317 
318   // Create Decl objects for each parameter, entrring them in the scope for
319   // binding to their use.
320 
321   // Insert the invisible arguments, self and _cmd!
322   MDecl->createImplicitParams(Context, MDecl->getClassInterface());
323 
324   PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
325   PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
326 
327   // The ObjC parser requires parameter names so there's no need to check.
328   CheckParmsForFunctionDef(MDecl->param_begin(), MDecl->param_end(),
329                            /*CheckParameterNames=*/false);
330 
331   // Introduce all of the other parameters into this scope.
332   for (auto *Param : MDecl->params()) {
333     if (!Param->isInvalidDecl() &&
334         getLangOpts().ObjCAutoRefCount &&
335         !HasExplicitOwnershipAttr(*this, Param))
336       Diag(Param->getLocation(), diag::warn_arc_strong_pointer_objc_pointer) <<
337             Param->getType();
338 
339     if (Param->getIdentifier())
340       PushOnScopeChains(Param, FnBodyScope);
341   }
342 
343   // In ARC, disallow definition of retain/release/autorelease/retainCount
344   if (getLangOpts().ObjCAutoRefCount) {
345     switch (MDecl->getMethodFamily()) {
346     case OMF_retain:
347     case OMF_retainCount:
348     case OMF_release:
349     case OMF_autorelease:
350       Diag(MDecl->getLocation(), diag::err_arc_illegal_method_def)
351         << 0 << MDecl->getSelector();
352       break;
353 
354     case OMF_None:
355     case OMF_dealloc:
356     case OMF_finalize:
357     case OMF_alloc:
358     case OMF_init:
359     case OMF_mutableCopy:
360     case OMF_copy:
361     case OMF_new:
362     case OMF_self:
363     case OMF_performSelector:
364       break;
365     }
366   }
367 
368   // Warn on deprecated methods under -Wdeprecated-implementations,
369   // and prepare for warning on missing super calls.
370   if (ObjCInterfaceDecl *IC = MDecl->getClassInterface()) {
371     ObjCMethodDecl *IMD =
372       IC->lookupMethod(MDecl->getSelector(), MDecl->isInstanceMethod());
373 
374     if (IMD) {
375       ObjCImplDecl *ImplDeclOfMethodDef =
376         dyn_cast<ObjCImplDecl>(MDecl->getDeclContext());
377       ObjCContainerDecl *ContDeclOfMethodDecl =
378         dyn_cast<ObjCContainerDecl>(IMD->getDeclContext());
379       ObjCImplDecl *ImplDeclOfMethodDecl = 0;
380       if (ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(ContDeclOfMethodDecl))
381         ImplDeclOfMethodDecl = OID->getImplementation();
382       else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(ContDeclOfMethodDecl))
383         ImplDeclOfMethodDecl = CD->getImplementation();
384       // No need to issue deprecated warning if deprecated mehod in class/category
385       // is being implemented in its own implementation (no overriding is involved).
386       if (!ImplDeclOfMethodDecl || ImplDeclOfMethodDecl != ImplDeclOfMethodDef)
387         DiagnoseObjCImplementedDeprecations(*this,
388                                           dyn_cast<NamedDecl>(IMD),
389                                           MDecl->getLocation(), 0);
390     }
391 
392     if (MDecl->getMethodFamily() == OMF_init) {
393       if (MDecl->isDesignatedInitializerForTheInterface()) {
394         getCurFunction()->ObjCIsDesignatedInit = true;
395         getCurFunction()->ObjCWarnForNoDesignatedInitChain =
396             IC->getSuperClass() != 0;
397       } else if (IC->hasDesignatedInitializers()) {
398         getCurFunction()->ObjCIsSecondaryInit = true;
399         getCurFunction()->ObjCWarnForNoInitDelegation = true;
400       }
401     }
402 
403     // If this is "dealloc" or "finalize", set some bit here.
404     // Then in ActOnSuperMessage() (SemaExprObjC), set it back to false.
405     // Finally, in ActOnFinishFunctionBody() (SemaDecl), warn if flag is set.
406     // Only do this if the current class actually has a superclass.
407     if (const ObjCInterfaceDecl *SuperClass = IC->getSuperClass()) {
408       ObjCMethodFamily Family = MDecl->getMethodFamily();
409       if (Family == OMF_dealloc) {
410         if (!(getLangOpts().ObjCAutoRefCount ||
411               getLangOpts().getGC() == LangOptions::GCOnly))
412           getCurFunction()->ObjCShouldCallSuper = true;
413 
414       } else if (Family == OMF_finalize) {
415         if (Context.getLangOpts().getGC() != LangOptions::NonGC)
416           getCurFunction()->ObjCShouldCallSuper = true;
417 
418       } else {
419         const ObjCMethodDecl *SuperMethod =
420           SuperClass->lookupMethod(MDecl->getSelector(),
421                                    MDecl->isInstanceMethod());
422         getCurFunction()->ObjCShouldCallSuper =
423           (SuperMethod && SuperMethod->hasAttr<ObjCRequiresSuperAttr>());
424       }
425     }
426   }
427 }
428 
429 namespace {
430 
431 // Callback to only accept typo corrections that are Objective-C classes.
432 // If an ObjCInterfaceDecl* is given to the constructor, then the validation
433 // function will reject corrections to that class.
434 class ObjCInterfaceValidatorCCC : public CorrectionCandidateCallback {
435  public:
436   ObjCInterfaceValidatorCCC() : CurrentIDecl(0) {}
437   explicit ObjCInterfaceValidatorCCC(ObjCInterfaceDecl *IDecl)
438       : CurrentIDecl(IDecl) {}
439 
440   virtual bool ValidateCandidate(const TypoCorrection &candidate) {
441     ObjCInterfaceDecl *ID = candidate.getCorrectionDeclAs<ObjCInterfaceDecl>();
442     return ID && !declaresSameEntity(ID, CurrentIDecl);
443   }
444 
445  private:
446   ObjCInterfaceDecl *CurrentIDecl;
447 };
448 
449 }
450 
451 Decl *Sema::
452 ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
453                          IdentifierInfo *ClassName, SourceLocation ClassLoc,
454                          IdentifierInfo *SuperName, SourceLocation SuperLoc,
455                          Decl * const *ProtoRefs, unsigned NumProtoRefs,
456                          const SourceLocation *ProtoLocs,
457                          SourceLocation EndProtoLoc, AttributeList *AttrList) {
458   assert(ClassName && "Missing class identifier");
459 
460   // Check for another declaration kind with the same name.
461   NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
462                                          LookupOrdinaryName, ForRedeclaration);
463 
464   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
465     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
466     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
467   }
468 
469   // Create a declaration to describe this @interface.
470   ObjCInterfaceDecl* PrevIDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
471 
472   if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
473     // A previous decl with a different name is because of
474     // @compatibility_alias, for example:
475     // \code
476     //   @class NewImage;
477     //   @compatibility_alias OldImage NewImage;
478     // \endcode
479     // A lookup for 'OldImage' will return the 'NewImage' decl.
480     //
481     // In such a case use the real declaration name, instead of the alias one,
482     // otherwise we will break IdentifierResolver and redecls-chain invariants.
483     // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
484     // has been aliased.
485     ClassName = PrevIDecl->getIdentifier();
486   }
487 
488   ObjCInterfaceDecl *IDecl
489     = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc, ClassName,
490                                 PrevIDecl, ClassLoc);
491 
492   if (PrevIDecl) {
493     // Class already seen. Was it a definition?
494     if (ObjCInterfaceDecl *Def = PrevIDecl->getDefinition()) {
495       Diag(AtInterfaceLoc, diag::err_duplicate_class_def)
496         << PrevIDecl->getDeclName();
497       Diag(Def->getLocation(), diag::note_previous_definition);
498       IDecl->setInvalidDecl();
499     }
500   }
501 
502   if (AttrList)
503     ProcessDeclAttributeList(TUScope, IDecl, AttrList);
504   PushOnScopeChains(IDecl, TUScope);
505 
506   // Start the definition of this class. If we're in a redefinition case, there
507   // may already be a definition, so we'll end up adding to it.
508   if (!IDecl->hasDefinition())
509     IDecl->startDefinition();
510 
511   if (SuperName) {
512     // Check if a different kind of symbol declared in this scope.
513     PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
514                                 LookupOrdinaryName);
515 
516     if (!PrevDecl) {
517       // Try to correct for a typo in the superclass name without correcting
518       // to the class we're defining.
519       ObjCInterfaceValidatorCCC Validator(IDecl);
520       if (TypoCorrection Corrected = CorrectTypo(
521           DeclarationNameInfo(SuperName, SuperLoc), LookupOrdinaryName, TUScope,
522           NULL, Validator)) {
523         diagnoseTypo(Corrected, PDiag(diag::err_undef_superclass_suggest)
524                                     << SuperName << ClassName);
525         PrevDecl = Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>();
526       }
527     }
528 
529     if (declaresSameEntity(PrevDecl, IDecl)) {
530       Diag(SuperLoc, diag::err_recursive_superclass)
531         << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
532       IDecl->setEndOfDefinitionLoc(ClassLoc);
533     } else {
534       ObjCInterfaceDecl *SuperClassDecl =
535                                 dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
536 
537       // Diagnose classes that inherit from deprecated classes.
538       if (SuperClassDecl)
539         (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
540 
541       if (PrevDecl && SuperClassDecl == 0) {
542         // The previous declaration was not a class decl. Check if we have a
543         // typedef. If we do, get the underlying class type.
544         if (const TypedefNameDecl *TDecl =
545               dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
546           QualType T = TDecl->getUnderlyingType();
547           if (T->isObjCObjectType()) {
548             if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
549               SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
550               // This handles the following case:
551               // @interface NewI @end
552               // typedef NewI DeprI __attribute__((deprecated("blah")))
553               // @interface SI : DeprI /* warn here */ @end
554               (void)DiagnoseUseOfDecl(const_cast<TypedefNameDecl*>(TDecl), SuperLoc);
555             }
556           }
557         }
558 
559         // This handles the following case:
560         //
561         // typedef int SuperClass;
562         // @interface MyClass : SuperClass {} @end
563         //
564         if (!SuperClassDecl) {
565           Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
566           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
567         }
568       }
569 
570       if (!dyn_cast_or_null<TypedefNameDecl>(PrevDecl)) {
571         if (!SuperClassDecl)
572           Diag(SuperLoc, diag::err_undef_superclass)
573             << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
574         else if (RequireCompleteType(SuperLoc,
575                                   Context.getObjCInterfaceType(SuperClassDecl),
576                                      diag::err_forward_superclass,
577                                      SuperClassDecl->getDeclName(),
578                                      ClassName,
579                                      SourceRange(AtInterfaceLoc, ClassLoc))) {
580           SuperClassDecl = 0;
581         }
582       }
583       IDecl->setSuperClass(SuperClassDecl);
584       IDecl->setSuperClassLoc(SuperLoc);
585       IDecl->setEndOfDefinitionLoc(SuperLoc);
586     }
587   } else { // we have a root class.
588     IDecl->setEndOfDefinitionLoc(ClassLoc);
589   }
590 
591   // Check then save referenced protocols.
592   if (NumProtoRefs) {
593     IDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
594                            ProtoLocs, Context);
595     IDecl->setEndOfDefinitionLoc(EndProtoLoc);
596   }
597 
598   CheckObjCDeclScope(IDecl);
599   return ActOnObjCContainerStartDefinition(IDecl);
600 }
601 
602 /// ActOnTypedefedProtocols - this action finds protocol list as part of the
603 /// typedef'ed use for a qualified super class and adds them to the list
604 /// of the protocols.
605 void Sema::ActOnTypedefedProtocols(SmallVectorImpl<Decl *> &ProtocolRefs,
606                                    IdentifierInfo *SuperName,
607                                    SourceLocation SuperLoc) {
608   if (!SuperName)
609     return;
610   NamedDecl* IDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
611                                       LookupOrdinaryName);
612   if (!IDecl)
613     return;
614 
615   if (const TypedefNameDecl *TDecl = dyn_cast_or_null<TypedefNameDecl>(IDecl)) {
616     QualType T = TDecl->getUnderlyingType();
617     if (T->isObjCObjectType())
618       if (const ObjCObjectType *OPT = T->getAs<ObjCObjectType>())
619         for (ObjCObjectType::qual_iterator I = OPT->qual_begin(),
620              E = OPT->qual_end(); I != E; ++I)
621           ProtocolRefs.push_back(*I);
622   }
623 }
624 
625 /// ActOnCompatibilityAlias - this action is called after complete parsing of
626 /// a \@compatibility_alias declaration. It sets up the alias relationships.
627 Decl *Sema::ActOnCompatibilityAlias(SourceLocation AtLoc,
628                                     IdentifierInfo *AliasName,
629                                     SourceLocation AliasLocation,
630                                     IdentifierInfo *ClassName,
631                                     SourceLocation ClassLocation) {
632   // Look for previous declaration of alias name
633   NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
634                                       LookupOrdinaryName, ForRedeclaration);
635   if (ADecl) {
636     Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
637     Diag(ADecl->getLocation(), diag::note_previous_declaration);
638     return 0;
639   }
640   // Check for class declaration
641   NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
642                                        LookupOrdinaryName, ForRedeclaration);
643   if (const TypedefNameDecl *TDecl =
644         dyn_cast_or_null<TypedefNameDecl>(CDeclU)) {
645     QualType T = TDecl->getUnderlyingType();
646     if (T->isObjCObjectType()) {
647       if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
648         ClassName = IDecl->getIdentifier();
649         CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
650                                   LookupOrdinaryName, ForRedeclaration);
651       }
652     }
653   }
654   ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
655   if (CDecl == 0) {
656     Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
657     if (CDeclU)
658       Diag(CDeclU->getLocation(), diag::note_previous_declaration);
659     return 0;
660   }
661 
662   // Everything checked out, instantiate a new alias declaration AST.
663   ObjCCompatibleAliasDecl *AliasDecl =
664     ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
665 
666   if (!CheckObjCDeclScope(AliasDecl))
667     PushOnScopeChains(AliasDecl, TUScope);
668 
669   return AliasDecl;
670 }
671 
672 bool Sema::CheckForwardProtocolDeclarationForCircularDependency(
673   IdentifierInfo *PName,
674   SourceLocation &Ploc, SourceLocation PrevLoc,
675   const ObjCList<ObjCProtocolDecl> &PList) {
676 
677   bool res = false;
678   for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
679        E = PList.end(); I != E; ++I) {
680     if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
681                                                  Ploc)) {
682       if (PDecl->getIdentifier() == PName) {
683         Diag(Ploc, diag::err_protocol_has_circular_dependency);
684         Diag(PrevLoc, diag::note_previous_definition);
685         res = true;
686       }
687 
688       if (!PDecl->hasDefinition())
689         continue;
690 
691       if (CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
692             PDecl->getLocation(), PDecl->getReferencedProtocols()))
693         res = true;
694     }
695   }
696   return res;
697 }
698 
699 Decl *
700 Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
701                                   IdentifierInfo *ProtocolName,
702                                   SourceLocation ProtocolLoc,
703                                   Decl * const *ProtoRefs,
704                                   unsigned NumProtoRefs,
705                                   const SourceLocation *ProtoLocs,
706                                   SourceLocation EndProtoLoc,
707                                   AttributeList *AttrList) {
708   bool err = false;
709   // FIXME: Deal with AttrList.
710   assert(ProtocolName && "Missing protocol identifier");
711   ObjCProtocolDecl *PrevDecl = LookupProtocol(ProtocolName, ProtocolLoc,
712                                               ForRedeclaration);
713   ObjCProtocolDecl *PDecl = 0;
714   if (ObjCProtocolDecl *Def = PrevDecl? PrevDecl->getDefinition() : 0) {
715     // If we already have a definition, complain.
716     Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
717     Diag(Def->getLocation(), diag::note_previous_definition);
718 
719     // Create a new protocol that is completely distinct from previous
720     // declarations, and do not make this protocol available for name lookup.
721     // That way, we'll end up completely ignoring the duplicate.
722     // FIXME: Can we turn this into an error?
723     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
724                                      ProtocolLoc, AtProtoInterfaceLoc,
725                                      /*PrevDecl=*/0);
726     PDecl->startDefinition();
727   } else {
728     if (PrevDecl) {
729       // Check for circular dependencies among protocol declarations. This can
730       // only happen if this protocol was forward-declared.
731       ObjCList<ObjCProtocolDecl> PList;
732       PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
733       err = CheckForwardProtocolDeclarationForCircularDependency(
734               ProtocolName, ProtocolLoc, PrevDecl->getLocation(), PList);
735     }
736 
737     // Create the new declaration.
738     PDecl = ObjCProtocolDecl::Create(Context, CurContext, ProtocolName,
739                                      ProtocolLoc, AtProtoInterfaceLoc,
740                                      /*PrevDecl=*/PrevDecl);
741 
742     PushOnScopeChains(PDecl, TUScope);
743     PDecl->startDefinition();
744   }
745 
746   if (AttrList)
747     ProcessDeclAttributeList(TUScope, PDecl, AttrList);
748 
749   // Merge attributes from previous declarations.
750   if (PrevDecl)
751     mergeDeclAttributes(PDecl, PrevDecl);
752 
753   if (!err && NumProtoRefs ) {
754     /// Check then save referenced protocols.
755     PDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
756                            ProtoLocs, Context);
757   }
758 
759   CheckObjCDeclScope(PDecl);
760   return ActOnObjCContainerStartDefinition(PDecl);
761 }
762 
763 /// FindProtocolDeclaration - This routine looks up protocols and
764 /// issues an error if they are not declared. It returns list of
765 /// protocol declarations in its 'Protocols' argument.
766 void
767 Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
768                               const IdentifierLocPair *ProtocolId,
769                               unsigned NumProtocols,
770                               SmallVectorImpl<Decl *> &Protocols) {
771   for (unsigned i = 0; i != NumProtocols; ++i) {
772     ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
773                                              ProtocolId[i].second);
774     if (!PDecl) {
775       DeclFilterCCC<ObjCProtocolDecl> Validator;
776       TypoCorrection Corrected = CorrectTypo(
777           DeclarationNameInfo(ProtocolId[i].first, ProtocolId[i].second),
778           LookupObjCProtocolName, TUScope, NULL, Validator);
779       if ((PDecl = Corrected.getCorrectionDeclAs<ObjCProtocolDecl>()))
780         diagnoseTypo(Corrected, PDiag(diag::err_undeclared_protocol_suggest)
781                                     << ProtocolId[i].first);
782     }
783 
784     if (!PDecl) {
785       Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
786         << ProtocolId[i].first;
787       continue;
788     }
789     // If this is a forward protocol declaration, get its definition.
790     if (!PDecl->isThisDeclarationADefinition() && PDecl->getDefinition())
791       PDecl = PDecl->getDefinition();
792 
793     (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
794 
795     // If this is a forward declaration and we are supposed to warn in this
796     // case, do it.
797     // FIXME: Recover nicely in the hidden case.
798     if (WarnOnDeclarations &&
799         (!PDecl->hasDefinition() || PDecl->getDefinition()->isHidden()))
800       Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
801         << ProtocolId[i].first;
802     Protocols.push_back(PDecl);
803   }
804 }
805 
806 /// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
807 /// a class method in its extension.
808 ///
809 void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
810                                             ObjCInterfaceDecl *ID) {
811   if (!ID)
812     return;  // Possibly due to previous error
813 
814   llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
815   for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
816        e =  ID->meth_end(); i != e; ++i) {
817     ObjCMethodDecl *MD = *i;
818     MethodMap[MD->getSelector()] = MD;
819   }
820 
821   if (MethodMap.empty())
822     return;
823   for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
824        e =  CAT->meth_end(); i != e; ++i) {
825     ObjCMethodDecl *Method = *i;
826     const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
827     if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
828       Diag(Method->getLocation(), diag::err_duplicate_method_decl)
829             << Method->getDeclName();
830       Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
831     }
832   }
833 }
834 
835 /// ActOnForwardProtocolDeclaration - Handle \@protocol foo;
836 Sema::DeclGroupPtrTy
837 Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
838                                       const IdentifierLocPair *IdentList,
839                                       unsigned NumElts,
840                                       AttributeList *attrList) {
841   SmallVector<Decl *, 8> DeclsInGroup;
842   for (unsigned i = 0; i != NumElts; ++i) {
843     IdentifierInfo *Ident = IdentList[i].first;
844     ObjCProtocolDecl *PrevDecl = LookupProtocol(Ident, IdentList[i].second,
845                                                 ForRedeclaration);
846     ObjCProtocolDecl *PDecl
847       = ObjCProtocolDecl::Create(Context, CurContext, Ident,
848                                  IdentList[i].second, AtProtocolLoc,
849                                  PrevDecl);
850 
851     PushOnScopeChains(PDecl, TUScope);
852     CheckObjCDeclScope(PDecl);
853 
854     if (attrList)
855       ProcessDeclAttributeList(TUScope, PDecl, attrList);
856 
857     if (PrevDecl)
858       mergeDeclAttributes(PDecl, PrevDecl);
859 
860     DeclsInGroup.push_back(PDecl);
861   }
862 
863   return BuildDeclaratorGroup(DeclsInGroup, false);
864 }
865 
866 Decl *Sema::
867 ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
868                             IdentifierInfo *ClassName, SourceLocation ClassLoc,
869                             IdentifierInfo *CategoryName,
870                             SourceLocation CategoryLoc,
871                             Decl * const *ProtoRefs,
872                             unsigned NumProtoRefs,
873                             const SourceLocation *ProtoLocs,
874                             SourceLocation EndProtoLoc) {
875   ObjCCategoryDecl *CDecl;
876   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
877 
878   /// Check that class of this category is already completely declared.
879 
880   if (!IDecl
881       || RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
882                              diag::err_category_forward_interface,
883                              CategoryName == 0)) {
884     // Create an invalid ObjCCategoryDecl to serve as context for
885     // the enclosing method declarations.  We mark the decl invalid
886     // to make it clear that this isn't a valid AST.
887     CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
888                                      ClassLoc, CategoryLoc, CategoryName,IDecl);
889     CDecl->setInvalidDecl();
890     CurContext->addDecl(CDecl);
891 
892     if (!IDecl)
893       Diag(ClassLoc, diag::err_undef_interface) << ClassName;
894     return ActOnObjCContainerStartDefinition(CDecl);
895   }
896 
897   if (!CategoryName && IDecl->getImplementation()) {
898     Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
899     Diag(IDecl->getImplementation()->getLocation(),
900           diag::note_implementation_declared);
901   }
902 
903   if (CategoryName) {
904     /// Check for duplicate interface declaration for this category
905     if (ObjCCategoryDecl *Previous
906           = IDecl->FindCategoryDeclaration(CategoryName)) {
907       // Class extensions can be declared multiple times, categories cannot.
908       Diag(CategoryLoc, diag::warn_dup_category_def)
909         << ClassName << CategoryName;
910       Diag(Previous->getLocation(), diag::note_previous_definition);
911     }
912   }
913 
914   CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
915                                    ClassLoc, CategoryLoc, CategoryName, IDecl);
916   // FIXME: PushOnScopeChains?
917   CurContext->addDecl(CDecl);
918 
919   if (NumProtoRefs) {
920     CDecl->setProtocolList((ObjCProtocolDecl*const*)ProtoRefs, NumProtoRefs,
921                            ProtoLocs, Context);
922     // Protocols in the class extension belong to the class.
923     if (CDecl->IsClassExtension())
924      IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl*const*)ProtoRefs,
925                                             NumProtoRefs, Context);
926   }
927 
928   CheckObjCDeclScope(CDecl);
929   return ActOnObjCContainerStartDefinition(CDecl);
930 }
931 
932 /// ActOnStartCategoryImplementation - Perform semantic checks on the
933 /// category implementation declaration and build an ObjCCategoryImplDecl
934 /// object.
935 Decl *Sema::ActOnStartCategoryImplementation(
936                       SourceLocation AtCatImplLoc,
937                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
938                       IdentifierInfo *CatName, SourceLocation CatLoc) {
939   ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
940   ObjCCategoryDecl *CatIDecl = 0;
941   if (IDecl && IDecl->hasDefinition()) {
942     CatIDecl = IDecl->FindCategoryDeclaration(CatName);
943     if (!CatIDecl) {
944       // Category @implementation with no corresponding @interface.
945       // Create and install one.
946       CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, AtCatImplLoc,
947                                           ClassLoc, CatLoc,
948                                           CatName, IDecl);
949       CatIDecl->setImplicit();
950     }
951   }
952 
953   ObjCCategoryImplDecl *CDecl =
954     ObjCCategoryImplDecl::Create(Context, CurContext, CatName, IDecl,
955                                  ClassLoc, AtCatImplLoc, CatLoc);
956   /// Check that class of this category is already completely declared.
957   if (!IDecl) {
958     Diag(ClassLoc, diag::err_undef_interface) << ClassName;
959     CDecl->setInvalidDecl();
960   } else if (RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
961                                  diag::err_undef_interface)) {
962     CDecl->setInvalidDecl();
963   }
964 
965   // FIXME: PushOnScopeChains?
966   CurContext->addDecl(CDecl);
967 
968   // If the interface is deprecated/unavailable, warn/error about it.
969   if (IDecl)
970     DiagnoseUseOfDecl(IDecl, ClassLoc);
971 
972   /// Check that CatName, category name, is not used in another implementation.
973   if (CatIDecl) {
974     if (CatIDecl->getImplementation()) {
975       Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
976         << CatName;
977       Diag(CatIDecl->getImplementation()->getLocation(),
978            diag::note_previous_definition);
979       CDecl->setInvalidDecl();
980     } else {
981       CatIDecl->setImplementation(CDecl);
982       // Warn on implementating category of deprecated class under
983       // -Wdeprecated-implementations flag.
984       DiagnoseObjCImplementedDeprecations(*this,
985                                           dyn_cast<NamedDecl>(IDecl),
986                                           CDecl->getLocation(), 2);
987     }
988   }
989 
990   CheckObjCDeclScope(CDecl);
991   return ActOnObjCContainerStartDefinition(CDecl);
992 }
993 
994 Decl *Sema::ActOnStartClassImplementation(
995                       SourceLocation AtClassImplLoc,
996                       IdentifierInfo *ClassName, SourceLocation ClassLoc,
997                       IdentifierInfo *SuperClassname,
998                       SourceLocation SuperClassLoc) {
999   ObjCInterfaceDecl *IDecl = 0;
1000   // Check for another declaration kind with the same name.
1001   NamedDecl *PrevDecl
1002     = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
1003                        ForRedeclaration);
1004   if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1005     Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
1006     Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1007   } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
1008     RequireCompleteType(ClassLoc, Context.getObjCInterfaceType(IDecl),
1009                         diag::warn_undef_interface);
1010   } else {
1011     // We did not find anything with the name ClassName; try to correct for
1012     // typos in the class name.
1013     ObjCInterfaceValidatorCCC Validator;
1014     TypoCorrection Corrected =
1015             CorrectTypo(DeclarationNameInfo(ClassName, ClassLoc),
1016                         LookupOrdinaryName, TUScope, NULL, Validator);
1017     if (Corrected.getCorrectionDeclAs<ObjCInterfaceDecl>()) {
1018       // Suggest the (potentially) correct interface name. Don't provide a
1019       // code-modification hint or use the typo name for recovery, because
1020       // this is just a warning. The program may actually be correct.
1021       diagnoseTypo(Corrected,
1022                    PDiag(diag::warn_undef_interface_suggest) << ClassName,
1023                    /*ErrorRecovery*/false);
1024     } else {
1025       Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
1026     }
1027   }
1028 
1029   // Check that super class name is valid class name
1030   ObjCInterfaceDecl* SDecl = 0;
1031   if (SuperClassname) {
1032     // Check if a different kind of symbol declared in this scope.
1033     PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
1034                                 LookupOrdinaryName);
1035     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1036       Diag(SuperClassLoc, diag::err_redefinition_different_kind)
1037         << SuperClassname;
1038       Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1039     } else {
1040       SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1041       if (SDecl && !SDecl->hasDefinition())
1042         SDecl = 0;
1043       if (!SDecl)
1044         Diag(SuperClassLoc, diag::err_undef_superclass)
1045           << SuperClassname << ClassName;
1046       else if (IDecl && !declaresSameEntity(IDecl->getSuperClass(), SDecl)) {
1047         // This implementation and its interface do not have the same
1048         // super class.
1049         Diag(SuperClassLoc, diag::err_conflicting_super_class)
1050           << SDecl->getDeclName();
1051         Diag(SDecl->getLocation(), diag::note_previous_definition);
1052       }
1053     }
1054   }
1055 
1056   if (!IDecl) {
1057     // Legacy case of @implementation with no corresponding @interface.
1058     // Build, chain & install the interface decl into the identifier.
1059 
1060     // FIXME: Do we support attributes on the @implementation? If so we should
1061     // copy them over.
1062     IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
1063                                       ClassName, /*PrevDecl=*/0, ClassLoc,
1064                                       true);
1065     IDecl->startDefinition();
1066     if (SDecl) {
1067       IDecl->setSuperClass(SDecl);
1068       IDecl->setSuperClassLoc(SuperClassLoc);
1069       IDecl->setEndOfDefinitionLoc(SuperClassLoc);
1070     } else {
1071       IDecl->setEndOfDefinitionLoc(ClassLoc);
1072     }
1073 
1074     PushOnScopeChains(IDecl, TUScope);
1075   } else {
1076     // Mark the interface as being completed, even if it was just as
1077     //   @class ....;
1078     // declaration; the user cannot reopen it.
1079     if (!IDecl->hasDefinition())
1080       IDecl->startDefinition();
1081   }
1082 
1083   ObjCImplementationDecl* IMPDecl =
1084     ObjCImplementationDecl::Create(Context, CurContext, IDecl, SDecl,
1085                                    ClassLoc, AtClassImplLoc, SuperClassLoc);
1086 
1087   if (CheckObjCDeclScope(IMPDecl))
1088     return ActOnObjCContainerStartDefinition(IMPDecl);
1089 
1090   // Check that there is no duplicate implementation of this class.
1091   if (IDecl->getImplementation()) {
1092     // FIXME: Don't leak everything!
1093     Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
1094     Diag(IDecl->getImplementation()->getLocation(),
1095          diag::note_previous_definition);
1096     IMPDecl->setInvalidDecl();
1097   } else { // add it to the list.
1098     IDecl->setImplementation(IMPDecl);
1099     PushOnScopeChains(IMPDecl, TUScope);
1100     // Warn on implementating deprecated class under
1101     // -Wdeprecated-implementations flag.
1102     DiagnoseObjCImplementedDeprecations(*this,
1103                                         dyn_cast<NamedDecl>(IDecl),
1104                                         IMPDecl->getLocation(), 1);
1105   }
1106   return ActOnObjCContainerStartDefinition(IMPDecl);
1107 }
1108 
1109 Sema::DeclGroupPtrTy
1110 Sema::ActOnFinishObjCImplementation(Decl *ObjCImpDecl, ArrayRef<Decl *> Decls) {
1111   SmallVector<Decl *, 64> DeclsInGroup;
1112   DeclsInGroup.reserve(Decls.size() + 1);
1113 
1114   for (unsigned i = 0, e = Decls.size(); i != e; ++i) {
1115     Decl *Dcl = Decls[i];
1116     if (!Dcl)
1117       continue;
1118     if (Dcl->getDeclContext()->isFileContext())
1119       Dcl->setTopLevelDeclInObjCContainer();
1120     DeclsInGroup.push_back(Dcl);
1121   }
1122 
1123   DeclsInGroup.push_back(ObjCImpDecl);
1124 
1125   return BuildDeclaratorGroup(DeclsInGroup, false);
1126 }
1127 
1128 void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
1129                                     ObjCIvarDecl **ivars, unsigned numIvars,
1130                                     SourceLocation RBrace) {
1131   assert(ImpDecl && "missing implementation decl");
1132   ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
1133   if (!IDecl)
1134     return;
1135   /// Check case of non-existing \@interface decl.
1136   /// (legacy objective-c \@implementation decl without an \@interface decl).
1137   /// Add implementations's ivar to the synthesize class's ivar list.
1138   if (IDecl->isImplicitInterfaceDecl()) {
1139     IDecl->setEndOfDefinitionLoc(RBrace);
1140     // Add ivar's to class's DeclContext.
1141     for (unsigned i = 0, e = numIvars; i != e; ++i) {
1142       ivars[i]->setLexicalDeclContext(ImpDecl);
1143       IDecl->makeDeclVisibleInContext(ivars[i]);
1144       ImpDecl->addDecl(ivars[i]);
1145     }
1146 
1147     return;
1148   }
1149   // If implementation has empty ivar list, just return.
1150   if (numIvars == 0)
1151     return;
1152 
1153   assert(ivars && "missing @implementation ivars");
1154   if (LangOpts.ObjCRuntime.isNonFragile()) {
1155     if (ImpDecl->getSuperClass())
1156       Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
1157     for (unsigned i = 0; i < numIvars; i++) {
1158       ObjCIvarDecl* ImplIvar = ivars[i];
1159       if (const ObjCIvarDecl *ClsIvar =
1160             IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1161         Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1162         Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1163         continue;
1164       }
1165       // Check class extensions (unnamed categories) for duplicate ivars.
1166       for (ObjCInterfaceDecl::visible_extensions_iterator
1167            Ext = IDecl->visible_extensions_begin(),
1168            ExtEnd = IDecl->visible_extensions_end();
1169          Ext != ExtEnd; ++Ext) {
1170         ObjCCategoryDecl *CDecl = *Ext;
1171         if (const ObjCIvarDecl *ClsExtIvar =
1172             CDecl->getIvarDecl(ImplIvar->getIdentifier())) {
1173           Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
1174           Diag(ClsExtIvar->getLocation(), diag::note_previous_definition);
1175           continue;
1176         }
1177       }
1178       // Instance ivar to Implementation's DeclContext.
1179       ImplIvar->setLexicalDeclContext(ImpDecl);
1180       IDecl->makeDeclVisibleInContext(ImplIvar);
1181       ImpDecl->addDecl(ImplIvar);
1182     }
1183     return;
1184   }
1185   // Check interface's Ivar list against those in the implementation.
1186   // names and types must match.
1187   //
1188   unsigned j = 0;
1189   ObjCInterfaceDecl::ivar_iterator
1190     IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
1191   for (; numIvars > 0 && IVI != IVE; ++IVI) {
1192     ObjCIvarDecl* ImplIvar = ivars[j++];
1193     ObjCIvarDecl* ClsIvar = *IVI;
1194     assert (ImplIvar && "missing implementation ivar");
1195     assert (ClsIvar && "missing class ivar");
1196 
1197     // First, make sure the types match.
1198     if (!Context.hasSameType(ImplIvar->getType(), ClsIvar->getType())) {
1199       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
1200         << ImplIvar->getIdentifier()
1201         << ImplIvar->getType() << ClsIvar->getType();
1202       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1203     } else if (ImplIvar->isBitField() && ClsIvar->isBitField() &&
1204                ImplIvar->getBitWidthValue(Context) !=
1205                ClsIvar->getBitWidthValue(Context)) {
1206       Diag(ImplIvar->getBitWidth()->getLocStart(),
1207            diag::err_conflicting_ivar_bitwidth) << ImplIvar->getIdentifier();
1208       Diag(ClsIvar->getBitWidth()->getLocStart(),
1209            diag::note_previous_definition);
1210     }
1211     // Make sure the names are identical.
1212     if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
1213       Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
1214         << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
1215       Diag(ClsIvar->getLocation(), diag::note_previous_definition);
1216     }
1217     --numIvars;
1218   }
1219 
1220   if (numIvars > 0)
1221     Diag(ivars[j]->getLocation(), diag::err_inconsistent_ivar_count);
1222   else if (IVI != IVE)
1223     Diag(IVI->getLocation(), diag::err_inconsistent_ivar_count);
1224 }
1225 
1226 static void WarnUndefinedMethod(Sema &S, SourceLocation ImpLoc,
1227                                 ObjCMethodDecl *method,
1228                                 bool &IncompleteImpl,
1229                                 unsigned DiagID,
1230                                 NamedDecl *NeededFor = 0) {
1231   // No point warning no definition of method which is 'unavailable'.
1232   switch (method->getAvailability()) {
1233   case AR_Available:
1234   case AR_Deprecated:
1235     break;
1236 
1237       // Don't warn about unavailable or not-yet-introduced methods.
1238   case AR_NotYetIntroduced:
1239   case AR_Unavailable:
1240     return;
1241   }
1242 
1243   // FIXME: For now ignore 'IncompleteImpl'.
1244   // Previously we grouped all unimplemented methods under a single
1245   // warning, but some users strongly voiced that they would prefer
1246   // separate warnings.  We will give that approach a try, as that
1247   // matches what we do with protocols.
1248   {
1249     const Sema::SemaDiagnosticBuilder &B = S.Diag(ImpLoc, DiagID);
1250     B << method;
1251     if (NeededFor)
1252       B << NeededFor;
1253   }
1254 
1255   // Issue a note to the original declaration.
1256   SourceLocation MethodLoc = method->getLocStart();
1257   if (MethodLoc.isValid())
1258     S.Diag(MethodLoc, diag::note_method_declared_at) << method;
1259 }
1260 
1261 /// Determines if type B can be substituted for type A.  Returns true if we can
1262 /// guarantee that anything that the user will do to an object of type A can
1263 /// also be done to an object of type B.  This is trivially true if the two
1264 /// types are the same, or if B is a subclass of A.  It becomes more complex
1265 /// in cases where protocols are involved.
1266 ///
1267 /// Object types in Objective-C describe the minimum requirements for an
1268 /// object, rather than providing a complete description of a type.  For
1269 /// example, if A is a subclass of B, then B* may refer to an instance of A.
1270 /// The principle of substitutability means that we may use an instance of A
1271 /// anywhere that we may use an instance of B - it will implement all of the
1272 /// ivars of B and all of the methods of B.
1273 ///
1274 /// This substitutability is important when type checking methods, because
1275 /// the implementation may have stricter type definitions than the interface.
1276 /// The interface specifies minimum requirements, but the implementation may
1277 /// have more accurate ones.  For example, a method may privately accept
1278 /// instances of B, but only publish that it accepts instances of A.  Any
1279 /// object passed to it will be type checked against B, and so will implicitly
1280 /// by a valid A*.  Similarly, a method may return a subclass of the class that
1281 /// it is declared as returning.
1282 ///
1283 /// This is most important when considering subclassing.  A method in a
1284 /// subclass must accept any object as an argument that its superclass's
1285 /// implementation accepts.  It may, however, accept a more general type
1286 /// without breaking substitutability (i.e. you can still use the subclass
1287 /// anywhere that you can use the superclass, but not vice versa).  The
1288 /// converse requirement applies to return types: the return type for a
1289 /// subclass method must be a valid object of the kind that the superclass
1290 /// advertises, but it may be specified more accurately.  This avoids the need
1291 /// for explicit down-casting by callers.
1292 ///
1293 /// Note: This is a stricter requirement than for assignment.
1294 static bool isObjCTypeSubstitutable(ASTContext &Context,
1295                                     const ObjCObjectPointerType *A,
1296                                     const ObjCObjectPointerType *B,
1297                                     bool rejectId) {
1298   // Reject a protocol-unqualified id.
1299   if (rejectId && B->isObjCIdType()) return false;
1300 
1301   // If B is a qualified id, then A must also be a qualified id and it must
1302   // implement all of the protocols in B.  It may not be a qualified class.
1303   // For example, MyClass<A> can be assigned to id<A>, but MyClass<A> is a
1304   // stricter definition so it is not substitutable for id<A>.
1305   if (B->isObjCQualifiedIdType()) {
1306     return A->isObjCQualifiedIdType() &&
1307            Context.ObjCQualifiedIdTypesAreCompatible(QualType(A, 0),
1308                                                      QualType(B,0),
1309                                                      false);
1310   }
1311 
1312   /*
1313   // id is a special type that bypasses type checking completely.  We want a
1314   // warning when it is used in one place but not another.
1315   if (C.isObjCIdType(A) || C.isObjCIdType(B)) return false;
1316 
1317 
1318   // If B is a qualified id, then A must also be a qualified id (which it isn't
1319   // if we've got this far)
1320   if (B->isObjCQualifiedIdType()) return false;
1321   */
1322 
1323   // Now we know that A and B are (potentially-qualified) class types.  The
1324   // normal rules for assignment apply.
1325   return Context.canAssignObjCInterfaces(A, B);
1326 }
1327 
1328 static SourceRange getTypeRange(TypeSourceInfo *TSI) {
1329   return (TSI ? TSI->getTypeLoc().getSourceRange() : SourceRange());
1330 }
1331 
1332 static bool CheckMethodOverrideReturn(Sema &S,
1333                                       ObjCMethodDecl *MethodImpl,
1334                                       ObjCMethodDecl *MethodDecl,
1335                                       bool IsProtocolMethodDecl,
1336                                       bool IsOverridingMode,
1337                                       bool Warn) {
1338   if (IsProtocolMethodDecl &&
1339       (MethodDecl->getObjCDeclQualifier() !=
1340        MethodImpl->getObjCDeclQualifier())) {
1341     if (Warn) {
1342       S.Diag(MethodImpl->getLocation(),
1343              (IsOverridingMode
1344                   ? diag::warn_conflicting_overriding_ret_type_modifiers
1345                   : diag::warn_conflicting_ret_type_modifiers))
1346           << MethodImpl->getDeclName()
1347           << getTypeRange(MethodImpl->getReturnTypeSourceInfo());
1348       S.Diag(MethodDecl->getLocation(), diag::note_previous_declaration)
1349           << getTypeRange(MethodDecl->getReturnTypeSourceInfo());
1350     }
1351     else
1352       return false;
1353   }
1354 
1355   if (S.Context.hasSameUnqualifiedType(MethodImpl->getReturnType(),
1356                                        MethodDecl->getReturnType()))
1357     return true;
1358   if (!Warn)
1359     return false;
1360 
1361   unsigned DiagID =
1362     IsOverridingMode ? diag::warn_conflicting_overriding_ret_types
1363                      : diag::warn_conflicting_ret_types;
1364 
1365   // Mismatches between ObjC pointers go into a different warning
1366   // category, and sometimes they're even completely whitelisted.
1367   if (const ObjCObjectPointerType *ImplPtrTy =
1368           MethodImpl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1369     if (const ObjCObjectPointerType *IfacePtrTy =
1370             MethodDecl->getReturnType()->getAs<ObjCObjectPointerType>()) {
1371       // Allow non-matching return types as long as they don't violate
1372       // the principle of substitutability.  Specifically, we permit
1373       // return types that are subclasses of the declared return type,
1374       // or that are more-qualified versions of the declared type.
1375       if (isObjCTypeSubstitutable(S.Context, IfacePtrTy, ImplPtrTy, false))
1376         return false;
1377 
1378       DiagID =
1379         IsOverridingMode ? diag::warn_non_covariant_overriding_ret_types
1380                           : diag::warn_non_covariant_ret_types;
1381     }
1382   }
1383 
1384   S.Diag(MethodImpl->getLocation(), DiagID)
1385       << MethodImpl->getDeclName() << MethodDecl->getReturnType()
1386       << MethodImpl->getReturnType()
1387       << getTypeRange(MethodImpl->getReturnTypeSourceInfo());
1388   S.Diag(MethodDecl->getLocation(), IsOverridingMode
1389                                         ? diag::note_previous_declaration
1390                                         : diag::note_previous_definition)
1391       << getTypeRange(MethodDecl->getReturnTypeSourceInfo());
1392   return false;
1393 }
1394 
1395 static bool CheckMethodOverrideParam(Sema &S,
1396                                      ObjCMethodDecl *MethodImpl,
1397                                      ObjCMethodDecl *MethodDecl,
1398                                      ParmVarDecl *ImplVar,
1399                                      ParmVarDecl *IfaceVar,
1400                                      bool IsProtocolMethodDecl,
1401                                      bool IsOverridingMode,
1402                                      bool Warn) {
1403   if (IsProtocolMethodDecl &&
1404       (ImplVar->getObjCDeclQualifier() !=
1405        IfaceVar->getObjCDeclQualifier())) {
1406     if (Warn) {
1407       if (IsOverridingMode)
1408         S.Diag(ImplVar->getLocation(),
1409                diag::warn_conflicting_overriding_param_modifiers)
1410             << getTypeRange(ImplVar->getTypeSourceInfo())
1411             << MethodImpl->getDeclName();
1412       else S.Diag(ImplVar->getLocation(),
1413              diag::warn_conflicting_param_modifiers)
1414           << getTypeRange(ImplVar->getTypeSourceInfo())
1415           << MethodImpl->getDeclName();
1416       S.Diag(IfaceVar->getLocation(), diag::note_previous_declaration)
1417           << getTypeRange(IfaceVar->getTypeSourceInfo());
1418     }
1419     else
1420       return false;
1421   }
1422 
1423   QualType ImplTy = ImplVar->getType();
1424   QualType IfaceTy = IfaceVar->getType();
1425 
1426   if (S.Context.hasSameUnqualifiedType(ImplTy, IfaceTy))
1427     return true;
1428 
1429   if (!Warn)
1430     return false;
1431   unsigned DiagID =
1432     IsOverridingMode ? diag::warn_conflicting_overriding_param_types
1433                      : diag::warn_conflicting_param_types;
1434 
1435   // Mismatches between ObjC pointers go into a different warning
1436   // category, and sometimes they're even completely whitelisted.
1437   if (const ObjCObjectPointerType *ImplPtrTy =
1438         ImplTy->getAs<ObjCObjectPointerType>()) {
1439     if (const ObjCObjectPointerType *IfacePtrTy =
1440           IfaceTy->getAs<ObjCObjectPointerType>()) {
1441       // Allow non-matching argument types as long as they don't
1442       // violate the principle of substitutability.  Specifically, the
1443       // implementation must accept any objects that the superclass
1444       // accepts, however it may also accept others.
1445       if (isObjCTypeSubstitutable(S.Context, ImplPtrTy, IfacePtrTy, true))
1446         return false;
1447 
1448       DiagID =
1449       IsOverridingMode ? diag::warn_non_contravariant_overriding_param_types
1450                        :  diag::warn_non_contravariant_param_types;
1451     }
1452   }
1453 
1454   S.Diag(ImplVar->getLocation(), DiagID)
1455     << getTypeRange(ImplVar->getTypeSourceInfo())
1456     << MethodImpl->getDeclName() << IfaceTy << ImplTy;
1457   S.Diag(IfaceVar->getLocation(),
1458          (IsOverridingMode ? diag::note_previous_declaration
1459                         : diag::note_previous_definition))
1460     << getTypeRange(IfaceVar->getTypeSourceInfo());
1461   return false;
1462 }
1463 
1464 /// In ARC, check whether the conventional meanings of the two methods
1465 /// match.  If they don't, it's a hard error.
1466 static bool checkMethodFamilyMismatch(Sema &S, ObjCMethodDecl *impl,
1467                                       ObjCMethodDecl *decl) {
1468   ObjCMethodFamily implFamily = impl->getMethodFamily();
1469   ObjCMethodFamily declFamily = decl->getMethodFamily();
1470   if (implFamily == declFamily) return false;
1471 
1472   // Since conventions are sorted by selector, the only possibility is
1473   // that the types differ enough to cause one selector or the other
1474   // to fall out of the family.
1475   assert(implFamily == OMF_None || declFamily == OMF_None);
1476 
1477   // No further diagnostics required on invalid declarations.
1478   if (impl->isInvalidDecl() || decl->isInvalidDecl()) return true;
1479 
1480   const ObjCMethodDecl *unmatched = impl;
1481   ObjCMethodFamily family = declFamily;
1482   unsigned errorID = diag::err_arc_lost_method_convention;
1483   unsigned noteID = diag::note_arc_lost_method_convention;
1484   if (declFamily == OMF_None) {
1485     unmatched = decl;
1486     family = implFamily;
1487     errorID = diag::err_arc_gained_method_convention;
1488     noteID = diag::note_arc_gained_method_convention;
1489   }
1490 
1491   // Indexes into a %select clause in the diagnostic.
1492   enum FamilySelector {
1493     F_alloc, F_copy, F_mutableCopy = F_copy, F_init, F_new
1494   };
1495   FamilySelector familySelector = FamilySelector();
1496 
1497   switch (family) {
1498   case OMF_None: llvm_unreachable("logic error, no method convention");
1499   case OMF_retain:
1500   case OMF_release:
1501   case OMF_autorelease:
1502   case OMF_dealloc:
1503   case OMF_finalize:
1504   case OMF_retainCount:
1505   case OMF_self:
1506   case OMF_performSelector:
1507     // Mismatches for these methods don't change ownership
1508     // conventions, so we don't care.
1509     return false;
1510 
1511   case OMF_init: familySelector = F_init; break;
1512   case OMF_alloc: familySelector = F_alloc; break;
1513   case OMF_copy: familySelector = F_copy; break;
1514   case OMF_mutableCopy: familySelector = F_mutableCopy; break;
1515   case OMF_new: familySelector = F_new; break;
1516   }
1517 
1518   enum ReasonSelector { R_NonObjectReturn, R_UnrelatedReturn };
1519   ReasonSelector reasonSelector;
1520 
1521   // The only reason these methods don't fall within their families is
1522   // due to unusual result types.
1523   if (unmatched->getReturnType()->isObjCObjectPointerType()) {
1524     reasonSelector = R_UnrelatedReturn;
1525   } else {
1526     reasonSelector = R_NonObjectReturn;
1527   }
1528 
1529   S.Diag(impl->getLocation(), errorID) << int(familySelector) << int(reasonSelector);
1530   S.Diag(decl->getLocation(), noteID) << int(familySelector) << int(reasonSelector);
1531 
1532   return true;
1533 }
1534 
1535 void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1536                                        ObjCMethodDecl *MethodDecl,
1537                                        bool IsProtocolMethodDecl) {
1538   if (getLangOpts().ObjCAutoRefCount &&
1539       checkMethodFamilyMismatch(*this, ImpMethodDecl, MethodDecl))
1540     return;
1541 
1542   CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1543                             IsProtocolMethodDecl, false,
1544                             true);
1545 
1546   for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1547        IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1548        EF = MethodDecl->param_end();
1549        IM != EM && IF != EF; ++IM, ++IF) {
1550     CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl, *IM, *IF,
1551                              IsProtocolMethodDecl, false, true);
1552   }
1553 
1554   if (ImpMethodDecl->isVariadic() != MethodDecl->isVariadic()) {
1555     Diag(ImpMethodDecl->getLocation(),
1556          diag::warn_conflicting_variadic);
1557     Diag(MethodDecl->getLocation(), diag::note_previous_declaration);
1558   }
1559 }
1560 
1561 void Sema::CheckConflictingOverridingMethod(ObjCMethodDecl *Method,
1562                                        ObjCMethodDecl *Overridden,
1563                                        bool IsProtocolMethodDecl) {
1564 
1565   CheckMethodOverrideReturn(*this, Method, Overridden,
1566                             IsProtocolMethodDecl, true,
1567                             true);
1568 
1569   for (ObjCMethodDecl::param_iterator IM = Method->param_begin(),
1570        IF = Overridden->param_begin(), EM = Method->param_end(),
1571        EF = Overridden->param_end();
1572        IM != EM && IF != EF; ++IM, ++IF) {
1573     CheckMethodOverrideParam(*this, Method, Overridden, *IM, *IF,
1574                              IsProtocolMethodDecl, true, true);
1575   }
1576 
1577   if (Method->isVariadic() != Overridden->isVariadic()) {
1578     Diag(Method->getLocation(),
1579          diag::warn_conflicting_overriding_variadic);
1580     Diag(Overridden->getLocation(), diag::note_previous_declaration);
1581   }
1582 }
1583 
1584 /// WarnExactTypedMethods - This routine issues a warning if method
1585 /// implementation declaration matches exactly that of its declaration.
1586 void Sema::WarnExactTypedMethods(ObjCMethodDecl *ImpMethodDecl,
1587                                  ObjCMethodDecl *MethodDecl,
1588                                  bool IsProtocolMethodDecl) {
1589   // don't issue warning when protocol method is optional because primary
1590   // class is not required to implement it and it is safe for protocol
1591   // to implement it.
1592   if (MethodDecl->getImplementationControl() == ObjCMethodDecl::Optional)
1593     return;
1594   // don't issue warning when primary class's method is
1595   // depecated/unavailable.
1596   if (MethodDecl->hasAttr<UnavailableAttr>() ||
1597       MethodDecl->hasAttr<DeprecatedAttr>())
1598     return;
1599 
1600   bool match = CheckMethodOverrideReturn(*this, ImpMethodDecl, MethodDecl,
1601                                       IsProtocolMethodDecl, false, false);
1602   if (match)
1603     for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
1604          IF = MethodDecl->param_begin(), EM = ImpMethodDecl->param_end(),
1605          EF = MethodDecl->param_end();
1606          IM != EM && IF != EF; ++IM, ++IF) {
1607       match = CheckMethodOverrideParam(*this, ImpMethodDecl, MethodDecl,
1608                                        *IM, *IF,
1609                                        IsProtocolMethodDecl, false, false);
1610       if (!match)
1611         break;
1612     }
1613   if (match)
1614     match = (ImpMethodDecl->isVariadic() == MethodDecl->isVariadic());
1615   if (match)
1616     match = !(MethodDecl->isClassMethod() &&
1617               MethodDecl->getSelector() == GetNullarySelector("load", Context));
1618 
1619   if (match) {
1620     Diag(ImpMethodDecl->getLocation(),
1621          diag::warn_category_method_impl_match);
1622     Diag(MethodDecl->getLocation(), diag::note_method_declared_at)
1623       << MethodDecl->getDeclName();
1624   }
1625 }
1626 
1627 /// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
1628 /// improve the efficiency of selector lookups and type checking by associating
1629 /// with each protocol / interface / category the flattened instance tables. If
1630 /// we used an immutable set to keep the table then it wouldn't add significant
1631 /// memory cost and it would be handy for lookups.
1632 
1633 typedef llvm::DenseSet<IdentifierInfo*> ProtocolNameSet;
1634 typedef llvm::OwningPtr<ProtocolNameSet> LazyProtocolNameSet;
1635 
1636 
1637 
1638 static void findProtocolsWithExplicitImpls(const ObjCProtocolDecl *PDecl,
1639                                            ProtocolNameSet &PNS) {
1640   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>())
1641     PNS.insert(PDecl->getIdentifier());
1642   for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1643        PE = PDecl->protocol_end(); PI != PE; ++PI)
1644     findProtocolsWithExplicitImpls(*PI, PNS);
1645 }
1646 
1647 /// Recursively populates a set with all conformed protocols in a class
1648 /// hierarchy that have the 'objc_protocol_requires_explicit_implementation'
1649 /// attribute.
1650 static void findProtocolsWithExplicitImpls(const ObjCInterfaceDecl *Super,
1651                                            ProtocolNameSet &PNS) {
1652   if (!Super)
1653     return;
1654 
1655   for (ObjCInterfaceDecl::all_protocol_iterator
1656         I = Super->all_referenced_protocol_begin(),
1657         E = Super->all_referenced_protocol_end(); I != E; ++I) {
1658     findProtocolsWithExplicitImpls(*I, PNS);
1659   }
1660 
1661   findProtocolsWithExplicitImpls(Super->getSuperClass(), PNS);
1662 }
1663 
1664 /// CheckProtocolMethodDefs - This routine checks unimplemented methods
1665 /// Declared in protocol, and those referenced by it.
1666 static void CheckProtocolMethodDefs(Sema &S,
1667                                     SourceLocation ImpLoc,
1668                                     ObjCProtocolDecl *PDecl,
1669                                     bool& IncompleteImpl,
1670                                     const Sema::SelectorSet &InsMap,
1671                                     const Sema::SelectorSet &ClsMap,
1672                                     ObjCContainerDecl *CDecl,
1673                                     LazyProtocolNameSet &ProtocolsExplictImpl) {
1674   ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl);
1675   ObjCInterfaceDecl *IDecl = C ? C->getClassInterface()
1676                                : dyn_cast<ObjCInterfaceDecl>(CDecl);
1677   assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
1678 
1679   ObjCInterfaceDecl *Super = IDecl->getSuperClass();
1680   ObjCInterfaceDecl *NSIDecl = 0;
1681 
1682   // If this protocol is marked 'objc_protocol_requires_explicit_implementation'
1683   // then we should check if any class in the super class hierarchy also
1684   // conforms to this protocol, either directly or via protocol inheritance.
1685   // If so, we can skip checking this protocol completely because we
1686   // know that a parent class already satisfies this protocol.
1687   //
1688   // Note: we could generalize this logic for all protocols, and merely
1689   // add the limit on looking at the super class chain for just
1690   // specially marked protocols.  This may be a good optimization.  This
1691   // change is restricted to 'objc_protocol_requires_explicit_implementation'
1692   // protocols for now for controlled evaluation.
1693   if (PDecl->hasAttr<ObjCExplicitProtocolImplAttr>()) {
1694     if (!ProtocolsExplictImpl.isValid()) {
1695       ProtocolsExplictImpl.reset(new ProtocolNameSet);
1696       findProtocolsWithExplicitImpls(Super, *ProtocolsExplictImpl);
1697     }
1698     if (ProtocolsExplictImpl->find(PDecl->getIdentifier()) !=
1699         ProtocolsExplictImpl->end())
1700       return;
1701 
1702     // If no super class conforms to the protocol, we should not search
1703     // for methods in the super class to implicitly satisfy the protocol.
1704     Super = NULL;
1705   }
1706 
1707   if (S.getLangOpts().ObjCRuntime.isNeXTFamily()) {
1708     // check to see if class implements forwardInvocation method and objects
1709     // of this class are derived from 'NSProxy' so that to forward requests
1710     // from one object to another.
1711     // Under such conditions, which means that every method possible is
1712     // implemented in the class, we should not issue "Method definition not
1713     // found" warnings.
1714     // FIXME: Use a general GetUnarySelector method for this.
1715     IdentifierInfo* II = &S.Context.Idents.get("forwardInvocation");
1716     Selector fISelector = S.Context.Selectors.getSelector(1, &II);
1717     if (InsMap.count(fISelector))
1718       // Is IDecl derived from 'NSProxy'? If so, no instance methods
1719       // need be implemented in the implementation.
1720       NSIDecl = IDecl->lookupInheritedClass(&S.Context.Idents.get("NSProxy"));
1721   }
1722 
1723   // If this is a forward protocol declaration, get its definition.
1724   if (!PDecl->isThisDeclarationADefinition() &&
1725       PDecl->getDefinition())
1726     PDecl = PDecl->getDefinition();
1727 
1728   // If a method lookup fails locally we still need to look and see if
1729   // the method was implemented by a base class or an inherited
1730   // protocol. This lookup is slow, but occurs rarely in correct code
1731   // and otherwise would terminate in a warning.
1732 
1733   // check unimplemented instance methods.
1734   if (!NSIDecl)
1735     for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
1736          E = PDecl->instmeth_end(); I != E; ++I) {
1737       ObjCMethodDecl *method = *I;
1738       if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1739           !method->isPropertyAccessor() &&
1740           !InsMap.count(method->getSelector()) &&
1741           (!Super || !Super->lookupMethod(method->getSelector(),
1742                                           true /* instance */,
1743                                           false /* shallowCategory */,
1744                                           true /* followsSuper */,
1745                                           NULL /* category */))) {
1746             // If a method is not implemented in the category implementation but
1747             // has been declared in its primary class, superclass,
1748             // or in one of their protocols, no need to issue the warning.
1749             // This is because method will be implemented in the primary class
1750             // or one of its super class implementation.
1751 
1752             // Ugly, but necessary. Method declared in protcol might have
1753             // have been synthesized due to a property declared in the class which
1754             // uses the protocol.
1755             if (ObjCMethodDecl *MethodInClass =
1756                   IDecl->lookupMethod(method->getSelector(),
1757                                       true /* instance */,
1758                                       true /* shallowCategoryLookup */,
1759                                       false /* followSuper */))
1760               if (C || MethodInClass->isPropertyAccessor())
1761                 continue;
1762             unsigned DIAG = diag::warn_unimplemented_protocol_method;
1763             if (S.Diags.getDiagnosticLevel(DIAG, ImpLoc)
1764                 != DiagnosticsEngine::Ignored) {
1765               WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG,
1766                                   PDecl);
1767             }
1768           }
1769     }
1770   // check unimplemented class methods
1771   for (ObjCProtocolDecl::classmeth_iterator
1772          I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1773        I != E; ++I) {
1774     ObjCMethodDecl *method = *I;
1775     if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
1776         !ClsMap.count(method->getSelector()) &&
1777         (!Super || !Super->lookupMethod(method->getSelector(),
1778                                         false /* class method */,
1779                                         false /* shallowCategoryLookup */,
1780                                         true  /* followSuper */,
1781                                         NULL /* category */))) {
1782       // See above comment for instance method lookups.
1783       if (C && IDecl->lookupMethod(method->getSelector(),
1784                                    false /* class */,
1785                                    true /* shallowCategoryLookup */,
1786                                    false /* followSuper */))
1787         continue;
1788 
1789       unsigned DIAG = diag::warn_unimplemented_protocol_method;
1790       if (S.Diags.getDiagnosticLevel(DIAG, ImpLoc) !=
1791             DiagnosticsEngine::Ignored) {
1792         WarnUndefinedMethod(S, ImpLoc, method, IncompleteImpl, DIAG, PDecl);
1793       }
1794     }
1795   }
1796   // Check on this protocols's referenced protocols, recursively.
1797   for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
1798        E = PDecl->protocol_end(); PI != E; ++PI)
1799     CheckProtocolMethodDefs(S, ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap,
1800                             CDecl, ProtocolsExplictImpl);
1801 }
1802 
1803 /// MatchAllMethodDeclarations - Check methods declared in interface
1804 /// or protocol against those declared in their implementations.
1805 ///
1806 void Sema::MatchAllMethodDeclarations(const SelectorSet &InsMap,
1807                                       const SelectorSet &ClsMap,
1808                                       SelectorSet &InsMapSeen,
1809                                       SelectorSet &ClsMapSeen,
1810                                       ObjCImplDecl* IMPDecl,
1811                                       ObjCContainerDecl* CDecl,
1812                                       bool &IncompleteImpl,
1813                                       bool ImmediateClass,
1814                                       bool WarnCategoryMethodImpl) {
1815   // Check and see if instance methods in class interface have been
1816   // implemented in the implementation class. If so, their types match.
1817   for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
1818        E = CDecl->instmeth_end(); I != E; ++I) {
1819     if (!InsMapSeen.insert((*I)->getSelector()))
1820       continue;
1821     if (!(*I)->isPropertyAccessor() &&
1822         !InsMap.count((*I)->getSelector())) {
1823       if (ImmediateClass)
1824         WarnUndefinedMethod(*this, IMPDecl->getLocation(), *I, IncompleteImpl,
1825                             diag::warn_undef_method_impl);
1826       continue;
1827     } else {
1828       ObjCMethodDecl *ImpMethodDecl =
1829         IMPDecl->getInstanceMethod((*I)->getSelector());
1830       assert(CDecl->getInstanceMethod((*I)->getSelector()) &&
1831              "Expected to find the method through lookup as well");
1832       ObjCMethodDecl *MethodDecl = *I;
1833       // ImpMethodDecl may be null as in a @dynamic property.
1834       if (ImpMethodDecl) {
1835         if (!WarnCategoryMethodImpl)
1836           WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1837                                       isa<ObjCProtocolDecl>(CDecl));
1838         else if (!MethodDecl->isPropertyAccessor())
1839           WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1840                                 isa<ObjCProtocolDecl>(CDecl));
1841       }
1842     }
1843   }
1844 
1845   // Check and see if class methods in class interface have been
1846   // implemented in the implementation class. If so, their types match.
1847   for (ObjCInterfaceDecl::classmeth_iterator I = CDecl->classmeth_begin(),
1848                                              E = CDecl->classmeth_end();
1849        I != E; ++I) {
1850     if (!ClsMapSeen.insert((*I)->getSelector()))
1851       continue;
1852     if (!ClsMap.count((*I)->getSelector())) {
1853       if (ImmediateClass)
1854         WarnUndefinedMethod(*this, IMPDecl->getLocation(), *I, IncompleteImpl,
1855                             diag::warn_undef_method_impl);
1856     } else {
1857       ObjCMethodDecl *ImpMethodDecl =
1858         IMPDecl->getClassMethod((*I)->getSelector());
1859       assert(CDecl->getClassMethod((*I)->getSelector()) &&
1860              "Expected to find the method through lookup as well");
1861       ObjCMethodDecl *MethodDecl = *I;
1862       if (!WarnCategoryMethodImpl)
1863         WarnConflictingTypedMethods(ImpMethodDecl, MethodDecl,
1864                                     isa<ObjCProtocolDecl>(CDecl));
1865       else
1866         WarnExactTypedMethods(ImpMethodDecl, MethodDecl,
1867                               isa<ObjCProtocolDecl>(CDecl));
1868     }
1869   }
1870 
1871   if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl> (CDecl)) {
1872     // Also, check for methods declared in protocols inherited by
1873     // this protocol.
1874     for (ObjCProtocolDecl::protocol_iterator
1875           PI = PD->protocol_begin(), E = PD->protocol_end(); PI != E; ++PI)
1876       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1877                                  IMPDecl, (*PI), IncompleteImpl, false,
1878                                  WarnCategoryMethodImpl);
1879   }
1880 
1881   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
1882     // when checking that methods in implementation match their declaration,
1883     // i.e. when WarnCategoryMethodImpl is false, check declarations in class
1884     // extension; as well as those in categories.
1885     if (!WarnCategoryMethodImpl) {
1886       for (ObjCInterfaceDecl::visible_categories_iterator
1887              Cat = I->visible_categories_begin(),
1888            CatEnd = I->visible_categories_end();
1889            Cat != CatEnd; ++Cat) {
1890         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1891                                    IMPDecl, *Cat, IncompleteImpl, false,
1892                                    WarnCategoryMethodImpl);
1893       }
1894     } else {
1895       // Also methods in class extensions need be looked at next.
1896       for (ObjCInterfaceDecl::visible_extensions_iterator
1897              Ext = I->visible_extensions_begin(),
1898              ExtEnd = I->visible_extensions_end();
1899            Ext != ExtEnd; ++Ext) {
1900         MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1901                                    IMPDecl, *Ext, IncompleteImpl, false,
1902                                    WarnCategoryMethodImpl);
1903       }
1904     }
1905 
1906     // Check for any implementation of a methods declared in protocol.
1907     for (ObjCInterfaceDecl::all_protocol_iterator
1908           PI = I->all_referenced_protocol_begin(),
1909           E = I->all_referenced_protocol_end(); PI != E; ++PI)
1910       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1911                                  IMPDecl,
1912                                  (*PI), IncompleteImpl, false,
1913                                  WarnCategoryMethodImpl);
1914 
1915     // FIXME. For now, we are not checking for extact match of methods
1916     // in category implementation and its primary class's super class.
1917     if (!WarnCategoryMethodImpl && I->getSuperClass())
1918       MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1919                                  IMPDecl,
1920                                  I->getSuperClass(), IncompleteImpl, false);
1921   }
1922 }
1923 
1924 /// CheckCategoryVsClassMethodMatches - Checks that methods implemented in
1925 /// category matches with those implemented in its primary class and
1926 /// warns each time an exact match is found.
1927 void Sema::CheckCategoryVsClassMethodMatches(
1928                                   ObjCCategoryImplDecl *CatIMPDecl) {
1929   // Get category's primary class.
1930   ObjCCategoryDecl *CatDecl = CatIMPDecl->getCategoryDecl();
1931   if (!CatDecl)
1932     return;
1933   ObjCInterfaceDecl *IDecl = CatDecl->getClassInterface();
1934   if (!IDecl)
1935     return;
1936   ObjCInterfaceDecl *SuperIDecl = IDecl->getSuperClass();
1937   SelectorSet InsMap, ClsMap;
1938 
1939   for (ObjCImplementationDecl::instmeth_iterator
1940        I = CatIMPDecl->instmeth_begin(),
1941        E = CatIMPDecl->instmeth_end(); I!=E; ++I) {
1942     Selector Sel = (*I)->getSelector();
1943     // When checking for methods implemented in the category, skip over
1944     // those declared in category class's super class. This is because
1945     // the super class must implement the method.
1946     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, true))
1947       continue;
1948     InsMap.insert(Sel);
1949   }
1950 
1951   for (ObjCImplementationDecl::classmeth_iterator
1952        I = CatIMPDecl->classmeth_begin(),
1953        E = CatIMPDecl->classmeth_end(); I != E; ++I) {
1954     Selector Sel = (*I)->getSelector();
1955     if (SuperIDecl && SuperIDecl->lookupMethod(Sel, false))
1956       continue;
1957     ClsMap.insert(Sel);
1958   }
1959   if (InsMap.empty() && ClsMap.empty())
1960     return;
1961 
1962   SelectorSet InsMapSeen, ClsMapSeen;
1963   bool IncompleteImpl = false;
1964   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
1965                              CatIMPDecl, IDecl,
1966                              IncompleteImpl, false,
1967                              true /*WarnCategoryMethodImpl*/);
1968 }
1969 
1970 void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
1971                                      ObjCContainerDecl* CDecl,
1972                                      bool IncompleteImpl) {
1973   SelectorSet InsMap;
1974   // Check and see if instance methods in class interface have been
1975   // implemented in the implementation class.
1976   for (ObjCImplementationDecl::instmeth_iterator
1977          I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
1978     InsMap.insert((*I)->getSelector());
1979 
1980   // Check and see if properties declared in the interface have either 1)
1981   // an implementation or 2) there is a @synthesize/@dynamic implementation
1982   // of the property in the @implementation.
1983   if (const ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl)) {
1984     bool SynthesizeProperties = LangOpts.ObjCDefaultSynthProperties &&
1985                                 LangOpts.ObjCRuntime.isNonFragile() &&
1986                                 !IDecl->isObjCRequiresPropertyDefs();
1987     DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, SynthesizeProperties);
1988   }
1989 
1990   SelectorSet ClsMap;
1991   for (ObjCImplementationDecl::classmeth_iterator
1992        I = IMPDecl->classmeth_begin(),
1993        E = IMPDecl->classmeth_end(); I != E; ++I)
1994     ClsMap.insert((*I)->getSelector());
1995 
1996   // Check for type conflict of methods declared in a class/protocol and
1997   // its implementation; if any.
1998   SelectorSet InsMapSeen, ClsMapSeen;
1999   MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
2000                              IMPDecl, CDecl,
2001                              IncompleteImpl, true);
2002 
2003   // check all methods implemented in category against those declared
2004   // in its primary class.
2005   if (ObjCCategoryImplDecl *CatDecl =
2006         dyn_cast<ObjCCategoryImplDecl>(IMPDecl))
2007     CheckCategoryVsClassMethodMatches(CatDecl);
2008 
2009   // Check the protocol list for unimplemented methods in the @implementation
2010   // class.
2011   // Check and see if class methods in class interface have been
2012   // implemented in the implementation class.
2013 
2014   LazyProtocolNameSet ExplicitImplProtocols;
2015 
2016   if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
2017     for (ObjCInterfaceDecl::all_protocol_iterator
2018           PI = I->all_referenced_protocol_begin(),
2019           E = I->all_referenced_protocol_end(); PI != E; ++PI)
2020       CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), *PI,
2021                               IncompleteImpl, InsMap, ClsMap, I,
2022                               ExplicitImplProtocols);
2023     // Check class extensions (unnamed categories)
2024     for (ObjCInterfaceDecl::visible_extensions_iterator
2025            Ext = I->visible_extensions_begin(),
2026            ExtEnd = I->visible_extensions_end();
2027          Ext != ExtEnd; ++Ext) {
2028       ImplMethodsVsClassMethods(S, IMPDecl, *Ext, IncompleteImpl);
2029     }
2030   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
2031     // For extended class, unimplemented methods in its protocols will
2032     // be reported in the primary class.
2033     if (!C->IsClassExtension()) {
2034       for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
2035            E = C->protocol_end(); PI != E; ++PI)
2036         CheckProtocolMethodDefs(*this, IMPDecl->getLocation(), *PI,
2037                                 IncompleteImpl, InsMap, ClsMap, CDecl,
2038                                 ExplicitImplProtocols);
2039       DiagnoseUnimplementedProperties(S, IMPDecl, CDecl,
2040                                       /* SynthesizeProperties */ false);
2041     }
2042   } else
2043     llvm_unreachable("invalid ObjCContainerDecl type.");
2044 }
2045 
2046 /// ActOnForwardClassDeclaration -
2047 Sema::DeclGroupPtrTy
2048 Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
2049                                    IdentifierInfo **IdentList,
2050                                    SourceLocation *IdentLocs,
2051                                    unsigned NumElts) {
2052   SmallVector<Decl *, 8> DeclsInGroup;
2053   for (unsigned i = 0; i != NumElts; ++i) {
2054     // Check for another declaration kind with the same name.
2055     NamedDecl *PrevDecl
2056       = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
2057                          LookupOrdinaryName, ForRedeclaration);
2058     if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
2059       // GCC apparently allows the following idiom:
2060       //
2061       // typedef NSObject < XCElementTogglerP > XCElementToggler;
2062       // @class XCElementToggler;
2063       //
2064       // Here we have chosen to ignore the forward class declaration
2065       // with a warning. Since this is the implied behavior.
2066       TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(PrevDecl);
2067       if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
2068         Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
2069         Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2070       } else {
2071         // a forward class declaration matching a typedef name of a class refers
2072         // to the underlying class. Just ignore the forward class with a warning
2073         // as this will force the intended behavior which is to lookup the typedef
2074         // name.
2075         if (isa<ObjCObjectType>(TDD->getUnderlyingType())) {
2076           Diag(AtClassLoc, diag::warn_forward_class_redefinition) << IdentList[i];
2077           Diag(PrevDecl->getLocation(), diag::note_previous_definition);
2078           continue;
2079         }
2080       }
2081     }
2082 
2083     // Create a declaration to describe this forward declaration.
2084     ObjCInterfaceDecl *PrevIDecl
2085       = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
2086 
2087     IdentifierInfo *ClassName = IdentList[i];
2088     if (PrevIDecl && PrevIDecl->getIdentifier() != ClassName) {
2089       // A previous decl with a different name is because of
2090       // @compatibility_alias, for example:
2091       // \code
2092       //   @class NewImage;
2093       //   @compatibility_alias OldImage NewImage;
2094       // \endcode
2095       // A lookup for 'OldImage' will return the 'NewImage' decl.
2096       //
2097       // In such a case use the real declaration name, instead of the alias one,
2098       // otherwise we will break IdentifierResolver and redecls-chain invariants.
2099       // FIXME: If necessary, add a bit to indicate that this ObjCInterfaceDecl
2100       // has been aliased.
2101       ClassName = PrevIDecl->getIdentifier();
2102     }
2103 
2104     ObjCInterfaceDecl *IDecl
2105       = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
2106                                   ClassName, PrevIDecl, IdentLocs[i]);
2107     IDecl->setAtEndRange(IdentLocs[i]);
2108 
2109     PushOnScopeChains(IDecl, TUScope);
2110     CheckObjCDeclScope(IDecl);
2111     DeclsInGroup.push_back(IDecl);
2112   }
2113 
2114   return BuildDeclaratorGroup(DeclsInGroup, false);
2115 }
2116 
2117 static bool tryMatchRecordTypes(ASTContext &Context,
2118                                 Sema::MethodMatchStrategy strategy,
2119                                 const Type *left, const Type *right);
2120 
2121 static bool matchTypes(ASTContext &Context, Sema::MethodMatchStrategy strategy,
2122                        QualType leftQT, QualType rightQT) {
2123   const Type *left =
2124     Context.getCanonicalType(leftQT).getUnqualifiedType().getTypePtr();
2125   const Type *right =
2126     Context.getCanonicalType(rightQT).getUnqualifiedType().getTypePtr();
2127 
2128   if (left == right) return true;
2129 
2130   // If we're doing a strict match, the types have to match exactly.
2131   if (strategy == Sema::MMS_strict) return false;
2132 
2133   if (left->isIncompleteType() || right->isIncompleteType()) return false;
2134 
2135   // Otherwise, use this absurdly complicated algorithm to try to
2136   // validate the basic, low-level compatibility of the two types.
2137 
2138   // As a minimum, require the sizes and alignments to match.
2139   if (Context.getTypeInfo(left) != Context.getTypeInfo(right))
2140     return false;
2141 
2142   // Consider all the kinds of non-dependent canonical types:
2143   // - functions and arrays aren't possible as return and parameter types
2144 
2145   // - vector types of equal size can be arbitrarily mixed
2146   if (isa<VectorType>(left)) return isa<VectorType>(right);
2147   if (isa<VectorType>(right)) return false;
2148 
2149   // - references should only match references of identical type
2150   // - structs, unions, and Objective-C objects must match more-or-less
2151   //   exactly
2152   // - everything else should be a scalar
2153   if (!left->isScalarType() || !right->isScalarType())
2154     return tryMatchRecordTypes(Context, strategy, left, right);
2155 
2156   // Make scalars agree in kind, except count bools as chars, and group
2157   // all non-member pointers together.
2158   Type::ScalarTypeKind leftSK = left->getScalarTypeKind();
2159   Type::ScalarTypeKind rightSK = right->getScalarTypeKind();
2160   if (leftSK == Type::STK_Bool) leftSK = Type::STK_Integral;
2161   if (rightSK == Type::STK_Bool) rightSK = Type::STK_Integral;
2162   if (leftSK == Type::STK_CPointer || leftSK == Type::STK_BlockPointer)
2163     leftSK = Type::STK_ObjCObjectPointer;
2164   if (rightSK == Type::STK_CPointer || rightSK == Type::STK_BlockPointer)
2165     rightSK = Type::STK_ObjCObjectPointer;
2166 
2167   // Note that data member pointers and function member pointers don't
2168   // intermix because of the size differences.
2169 
2170   return (leftSK == rightSK);
2171 }
2172 
2173 static bool tryMatchRecordTypes(ASTContext &Context,
2174                                 Sema::MethodMatchStrategy strategy,
2175                                 const Type *lt, const Type *rt) {
2176   assert(lt && rt && lt != rt);
2177 
2178   if (!isa<RecordType>(lt) || !isa<RecordType>(rt)) return false;
2179   RecordDecl *left = cast<RecordType>(lt)->getDecl();
2180   RecordDecl *right = cast<RecordType>(rt)->getDecl();
2181 
2182   // Require union-hood to match.
2183   if (left->isUnion() != right->isUnion()) return false;
2184 
2185   // Require an exact match if either is non-POD.
2186   if ((isa<CXXRecordDecl>(left) && !cast<CXXRecordDecl>(left)->isPOD()) ||
2187       (isa<CXXRecordDecl>(right) && !cast<CXXRecordDecl>(right)->isPOD()))
2188     return false;
2189 
2190   // Require size and alignment to match.
2191   if (Context.getTypeInfo(lt) != Context.getTypeInfo(rt)) return false;
2192 
2193   // Require fields to match.
2194   RecordDecl::field_iterator li = left->field_begin(), le = left->field_end();
2195   RecordDecl::field_iterator ri = right->field_begin(), re = right->field_end();
2196   for (; li != le && ri != re; ++li, ++ri) {
2197     if (!matchTypes(Context, strategy, li->getType(), ri->getType()))
2198       return false;
2199   }
2200   return (li == le && ri == re);
2201 }
2202 
2203 /// MatchTwoMethodDeclarations - Checks that two methods have matching type and
2204 /// returns true, or false, accordingly.
2205 /// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
2206 bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *left,
2207                                       const ObjCMethodDecl *right,
2208                                       MethodMatchStrategy strategy) {
2209   if (!matchTypes(Context, strategy, left->getReturnType(),
2210                   right->getReturnType()))
2211     return false;
2212 
2213   // If either is hidden, it is not considered to match.
2214   if (left->isHidden() || right->isHidden())
2215     return false;
2216 
2217   if (getLangOpts().ObjCAutoRefCount &&
2218       (left->hasAttr<NSReturnsRetainedAttr>()
2219          != right->hasAttr<NSReturnsRetainedAttr>() ||
2220        left->hasAttr<NSConsumesSelfAttr>()
2221          != right->hasAttr<NSConsumesSelfAttr>()))
2222     return false;
2223 
2224   ObjCMethodDecl::param_const_iterator
2225     li = left->param_begin(), le = left->param_end(), ri = right->param_begin(),
2226     re = right->param_end();
2227 
2228   for (; li != le && ri != re; ++li, ++ri) {
2229     assert(ri != right->param_end() && "Param mismatch");
2230     const ParmVarDecl *lparm = *li, *rparm = *ri;
2231 
2232     if (!matchTypes(Context, strategy, lparm->getType(), rparm->getType()))
2233       return false;
2234 
2235     if (getLangOpts().ObjCAutoRefCount &&
2236         lparm->hasAttr<NSConsumedAttr>() != rparm->hasAttr<NSConsumedAttr>())
2237       return false;
2238   }
2239   return true;
2240 }
2241 
2242 void Sema::addMethodToGlobalList(ObjCMethodList *List, ObjCMethodDecl *Method) {
2243   // Record at the head of the list whether there were 0, 1, or >= 2 methods
2244   // inside categories.
2245   if (ObjCCategoryDecl *
2246         CD = dyn_cast<ObjCCategoryDecl>(Method->getDeclContext()))
2247     if (!CD->IsClassExtension() && List->getBits() < 2)
2248         List->setBits(List->getBits()+1);
2249 
2250   // If the list is empty, make it a singleton list.
2251   if (List->Method == 0) {
2252     List->Method = Method;
2253     List->setNext(0);
2254     return;
2255   }
2256 
2257   // We've seen a method with this name, see if we have already seen this type
2258   // signature.
2259   ObjCMethodList *Previous = List;
2260   for (; List; Previous = List, List = List->getNext()) {
2261     // If we are building a module, keep all of the methods.
2262     if (getLangOpts().Modules && !getLangOpts().CurrentModule.empty())
2263       continue;
2264 
2265     if (!MatchTwoMethodDeclarations(Method, List->Method))
2266       continue;
2267 
2268     ObjCMethodDecl *PrevObjCMethod = List->Method;
2269 
2270     // Propagate the 'defined' bit.
2271     if (Method->isDefined())
2272       PrevObjCMethod->setDefined(true);
2273 
2274     // If a method is deprecated, push it in the global pool.
2275     // This is used for better diagnostics.
2276     if (Method->isDeprecated()) {
2277       if (!PrevObjCMethod->isDeprecated())
2278         List->Method = Method;
2279     }
2280     // If new method is unavailable, push it into global pool
2281     // unless previous one is deprecated.
2282     if (Method->isUnavailable()) {
2283       if (PrevObjCMethod->getAvailability() < AR_Deprecated)
2284         List->Method = Method;
2285     }
2286 
2287     return;
2288   }
2289 
2290   // We have a new signature for an existing method - add it.
2291   // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
2292   ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
2293   Previous->setNext(new (Mem) ObjCMethodList(Method, 0));
2294 }
2295 
2296 /// \brief Read the contents of the method pool for a given selector from
2297 /// external storage.
2298 void Sema::ReadMethodPool(Selector Sel) {
2299   assert(ExternalSource && "We need an external AST source");
2300   ExternalSource->ReadMethodPool(Sel);
2301 }
2302 
2303 void Sema::AddMethodToGlobalPool(ObjCMethodDecl *Method, bool impl,
2304                                  bool instance) {
2305   // Ignore methods of invalid containers.
2306   if (cast<Decl>(Method->getDeclContext())->isInvalidDecl())
2307     return;
2308 
2309   if (ExternalSource)
2310     ReadMethodPool(Method->getSelector());
2311 
2312   GlobalMethodPool::iterator Pos = MethodPool.find(Method->getSelector());
2313   if (Pos == MethodPool.end())
2314     Pos = MethodPool.insert(std::make_pair(Method->getSelector(),
2315                                            GlobalMethods())).first;
2316 
2317   Method->setDefined(impl);
2318 
2319   ObjCMethodList &Entry = instance ? Pos->second.first : Pos->second.second;
2320   addMethodToGlobalList(&Entry, Method);
2321 }
2322 
2323 /// Determines if this is an "acceptable" loose mismatch in the global
2324 /// method pool.  This exists mostly as a hack to get around certain
2325 /// global mismatches which we can't afford to make warnings / errors.
2326 /// Really, what we want is a way to take a method out of the global
2327 /// method pool.
2328 static bool isAcceptableMethodMismatch(ObjCMethodDecl *chosen,
2329                                        ObjCMethodDecl *other) {
2330   if (!chosen->isInstanceMethod())
2331     return false;
2332 
2333   Selector sel = chosen->getSelector();
2334   if (!sel.isUnarySelector() || sel.getNameForSlot(0) != "length")
2335     return false;
2336 
2337   // Don't complain about mismatches for -length if the method we
2338   // chose has an integral result type.
2339   return (chosen->getReturnType()->isIntegerType());
2340 }
2341 
2342 ObjCMethodDecl *Sema::LookupMethodInGlobalPool(Selector Sel, SourceRange R,
2343                                                bool receiverIdOrClass,
2344                                                bool warn, bool instance) {
2345   if (ExternalSource)
2346     ReadMethodPool(Sel);
2347 
2348   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2349   if (Pos == MethodPool.end())
2350     return 0;
2351 
2352   // Gather the non-hidden methods.
2353   ObjCMethodList &MethList = instance ? Pos->second.first : Pos->second.second;
2354   SmallVector<ObjCMethodDecl *, 4> Methods;
2355   for (ObjCMethodList *M = &MethList; M; M = M->getNext()) {
2356     if (M->Method && !M->Method->isHidden()) {
2357       // If we're not supposed to warn about mismatches, we're done.
2358       if (!warn)
2359         return M->Method;
2360 
2361       Methods.push_back(M->Method);
2362     }
2363   }
2364 
2365   // If there aren't any visible methods, we're done.
2366   // FIXME: Recover if there are any known-but-hidden methods?
2367   if (Methods.empty())
2368     return 0;
2369 
2370   if (Methods.size() == 1)
2371     return Methods[0];
2372 
2373   // We found multiple methods, so we may have to complain.
2374   bool issueDiagnostic = false, issueError = false;
2375 
2376   // We support a warning which complains about *any* difference in
2377   // method signature.
2378   bool strictSelectorMatch =
2379     (receiverIdOrClass && warn &&
2380      (Diags.getDiagnosticLevel(diag::warn_strict_multiple_method_decl,
2381                                R.getBegin())
2382         != DiagnosticsEngine::Ignored));
2383   if (strictSelectorMatch) {
2384     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2385       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_strict)) {
2386         issueDiagnostic = true;
2387         break;
2388       }
2389     }
2390   }
2391 
2392   // If we didn't see any strict differences, we won't see any loose
2393   // differences.  In ARC, however, we also need to check for loose
2394   // mismatches, because most of them are errors.
2395   if (!strictSelectorMatch ||
2396       (issueDiagnostic && getLangOpts().ObjCAutoRefCount))
2397     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2398       // This checks if the methods differ in type mismatch.
2399       if (!MatchTwoMethodDeclarations(Methods[0], Methods[I], MMS_loose) &&
2400           !isAcceptableMethodMismatch(Methods[0], Methods[I])) {
2401         issueDiagnostic = true;
2402         if (getLangOpts().ObjCAutoRefCount)
2403           issueError = true;
2404         break;
2405       }
2406     }
2407 
2408   if (issueDiagnostic) {
2409     if (issueError)
2410       Diag(R.getBegin(), diag::err_arc_multiple_method_decl) << Sel << R;
2411     else if (strictSelectorMatch)
2412       Diag(R.getBegin(), diag::warn_strict_multiple_method_decl) << Sel << R;
2413     else
2414       Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
2415 
2416     Diag(Methods[0]->getLocStart(),
2417          issueError ? diag::note_possibility : diag::note_using)
2418       << Methods[0]->getSourceRange();
2419     for (unsigned I = 1, N = Methods.size(); I != N; ++I) {
2420       Diag(Methods[I]->getLocStart(), diag::note_also_found)
2421         << Methods[I]->getSourceRange();
2422   }
2423   }
2424   return Methods[0];
2425 }
2426 
2427 ObjCMethodDecl *Sema::LookupImplementedMethodInGlobalPool(Selector Sel) {
2428   GlobalMethodPool::iterator Pos = MethodPool.find(Sel);
2429   if (Pos == MethodPool.end())
2430     return 0;
2431 
2432   GlobalMethods &Methods = Pos->second;
2433 
2434   if (Methods.first.Method && Methods.first.Method->isDefined())
2435     return Methods.first.Method;
2436   if (Methods.second.Method && Methods.second.Method->isDefined())
2437     return Methods.second.Method;
2438   return 0;
2439 }
2440 
2441 static void
2442 HelperSelectorsForTypoCorrection(
2443                       SmallVectorImpl<const ObjCMethodDecl *> &BestMethod,
2444                       StringRef Typo, const ObjCMethodDecl * Method) {
2445   const unsigned MaxEditDistance = 1;
2446   unsigned BestEditDistance = MaxEditDistance + 1;
2447   std::string MethodName = Method->getSelector().getAsString();
2448 
2449   unsigned MinPossibleEditDistance = abs((int)MethodName.size() - (int)Typo.size());
2450   if (MinPossibleEditDistance > 0 &&
2451       Typo.size() / MinPossibleEditDistance < 1)
2452     return;
2453   unsigned EditDistance = Typo.edit_distance(MethodName, true, MaxEditDistance);
2454   if (EditDistance > MaxEditDistance)
2455     return;
2456   if (EditDistance == BestEditDistance)
2457     BestMethod.push_back(Method);
2458   else if (EditDistance < BestEditDistance) {
2459     BestMethod.clear();
2460     BestMethod.push_back(Method);
2461   }
2462 }
2463 
2464 static bool HelperIsMethodInObjCType(Sema &S, Selector Sel,
2465                                      QualType ObjectType) {
2466   if (ObjectType.isNull())
2467     return true;
2468   if (S.LookupMethodInObjectType(Sel, ObjectType, true/*Instance method*/))
2469     return true;
2470   return S.LookupMethodInObjectType(Sel, ObjectType, false/*Class method*/) != 0;
2471 }
2472 
2473 const ObjCMethodDecl *
2474 Sema::SelectorsForTypoCorrection(Selector Sel,
2475                                  QualType ObjectType) {
2476   unsigned NumArgs = Sel.getNumArgs();
2477   SmallVector<const ObjCMethodDecl *, 8> Methods;
2478   bool ObjectIsId = true, ObjectIsClass = true;
2479   if (ObjectType.isNull())
2480     ObjectIsId = ObjectIsClass = false;
2481   else if (!ObjectType->isObjCObjectPointerType())
2482     return 0;
2483   else if (const ObjCObjectPointerType *ObjCPtr =
2484            ObjectType->getAsObjCInterfacePointerType()) {
2485     ObjectType = QualType(ObjCPtr->getInterfaceType(), 0);
2486     ObjectIsId = ObjectIsClass = false;
2487   }
2488   else if (ObjectType->isObjCIdType() || ObjectType->isObjCQualifiedIdType())
2489     ObjectIsClass = false;
2490   else if (ObjectType->isObjCClassType() || ObjectType->isObjCQualifiedClassType())
2491     ObjectIsId = false;
2492   else
2493     return 0;
2494 
2495   for (GlobalMethodPool::iterator b = MethodPool.begin(),
2496        e = MethodPool.end(); b != e; b++) {
2497     // instance methods
2498     for (ObjCMethodList *M = &b->second.first; M; M=M->getNext())
2499       if (M->Method &&
2500           (M->Method->getSelector().getNumArgs() == NumArgs) &&
2501           (M->Method->getSelector() != Sel)) {
2502         if (ObjectIsId)
2503           Methods.push_back(M->Method);
2504         else if (!ObjectIsClass &&
2505                  HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2506           Methods.push_back(M->Method);
2507       }
2508     // class methods
2509     for (ObjCMethodList *M = &b->second.second; M; M=M->getNext())
2510       if (M->Method &&
2511           (M->Method->getSelector().getNumArgs() == NumArgs) &&
2512           (M->Method->getSelector() != Sel)) {
2513         if (ObjectIsClass)
2514           Methods.push_back(M->Method);
2515         else if (!ObjectIsId &&
2516                  HelperIsMethodInObjCType(*this, M->Method->getSelector(), ObjectType))
2517           Methods.push_back(M->Method);
2518       }
2519   }
2520 
2521   SmallVector<const ObjCMethodDecl *, 8> SelectedMethods;
2522   for (unsigned i = 0, e = Methods.size(); i < e; i++) {
2523     HelperSelectorsForTypoCorrection(SelectedMethods,
2524                                      Sel.getAsString(), Methods[i]);
2525   }
2526   return (SelectedMethods.size() == 1) ? SelectedMethods[0] : NULL;
2527 }
2528 
2529 /// DiagnoseDuplicateIvars -
2530 /// Check for duplicate ivars in the entire class at the start of
2531 /// \@implementation. This becomes necesssary because class extension can
2532 /// add ivars to a class in random order which will not be known until
2533 /// class's \@implementation is seen.
2534 void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
2535                                   ObjCInterfaceDecl *SID) {
2536   for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
2537        IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
2538     ObjCIvarDecl* Ivar = *IVI;
2539     if (Ivar->isInvalidDecl())
2540       continue;
2541     if (IdentifierInfo *II = Ivar->getIdentifier()) {
2542       ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
2543       if (prevIvar) {
2544         Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
2545         Diag(prevIvar->getLocation(), diag::note_previous_declaration);
2546         Ivar->setInvalidDecl();
2547       }
2548     }
2549   }
2550 }
2551 
2552 Sema::ObjCContainerKind Sema::getObjCContainerKind() const {
2553   switch (CurContext->getDeclKind()) {
2554     case Decl::ObjCInterface:
2555       return Sema::OCK_Interface;
2556     case Decl::ObjCProtocol:
2557       return Sema::OCK_Protocol;
2558     case Decl::ObjCCategory:
2559       if (dyn_cast<ObjCCategoryDecl>(CurContext)->IsClassExtension())
2560         return Sema::OCK_ClassExtension;
2561       else
2562         return Sema::OCK_Category;
2563     case Decl::ObjCImplementation:
2564       return Sema::OCK_Implementation;
2565     case Decl::ObjCCategoryImpl:
2566       return Sema::OCK_CategoryImplementation;
2567 
2568     default:
2569       return Sema::OCK_None;
2570   }
2571 }
2572 
2573 // Note: For class/category implementations, allMethods is always null.
2574 Decl *Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd, ArrayRef<Decl *> allMethods,
2575                        ArrayRef<DeclGroupPtrTy> allTUVars) {
2576   if (getObjCContainerKind() == Sema::OCK_None)
2577     return 0;
2578 
2579   assert(AtEnd.isValid() && "Invalid location for '@end'");
2580 
2581   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
2582   Decl *ClassDecl = cast<Decl>(OCD);
2583 
2584   bool isInterfaceDeclKind =
2585         isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
2586          || isa<ObjCProtocolDecl>(ClassDecl);
2587   bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
2588 
2589   // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
2590   llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
2591   llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
2592 
2593   for (unsigned i = 0, e = allMethods.size(); i != e; i++ ) {
2594     ObjCMethodDecl *Method =
2595       cast_or_null<ObjCMethodDecl>(allMethods[i]);
2596 
2597     if (!Method) continue;  // Already issued a diagnostic.
2598     if (Method->isInstanceMethod()) {
2599       /// Check for instance method of the same name with incompatible types
2600       const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
2601       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2602                               : false;
2603       if ((isInterfaceDeclKind && PrevMethod && !match)
2604           || (checkIdenticalMethods && match)) {
2605           Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2606             << Method->getDeclName();
2607           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2608         Method->setInvalidDecl();
2609       } else {
2610         if (PrevMethod) {
2611           Method->setAsRedeclaration(PrevMethod);
2612           if (!Context.getSourceManager().isInSystemHeader(
2613                  Method->getLocation()))
2614             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2615               << Method->getDeclName();
2616           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2617         }
2618         InsMap[Method->getSelector()] = Method;
2619         /// The following allows us to typecheck messages to "id".
2620         AddInstanceMethodToGlobalPool(Method);
2621       }
2622     } else {
2623       /// Check for class method of the same name with incompatible types
2624       const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
2625       bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
2626                               : false;
2627       if ((isInterfaceDeclKind && PrevMethod && !match)
2628           || (checkIdenticalMethods && match)) {
2629         Diag(Method->getLocation(), diag::err_duplicate_method_decl)
2630           << Method->getDeclName();
2631         Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2632         Method->setInvalidDecl();
2633       } else {
2634         if (PrevMethod) {
2635           Method->setAsRedeclaration(PrevMethod);
2636           if (!Context.getSourceManager().isInSystemHeader(
2637                  Method->getLocation()))
2638             Diag(Method->getLocation(), diag::warn_duplicate_method_decl)
2639               << Method->getDeclName();
2640           Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
2641         }
2642         ClsMap[Method->getSelector()] = Method;
2643         AddFactoryMethodToGlobalPool(Method);
2644       }
2645     }
2646   }
2647   if (isa<ObjCInterfaceDecl>(ClassDecl)) {
2648     // Nothing to do here.
2649   } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
2650     // Categories are used to extend the class by declaring new methods.
2651     // By the same token, they are also used to add new properties. No
2652     // need to compare the added property to those in the class.
2653 
2654     if (C->IsClassExtension()) {
2655       ObjCInterfaceDecl *CCPrimary = C->getClassInterface();
2656       DiagnoseClassExtensionDupMethods(C, CCPrimary);
2657     }
2658   }
2659   if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
2660     if (CDecl->getIdentifier())
2661       // ProcessPropertyDecl is responsible for diagnosing conflicts with any
2662       // user-defined setter/getter. It also synthesizes setter/getter methods
2663       // and adds them to the DeclContext and global method pools.
2664       for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
2665                                             E = CDecl->prop_end();
2666            I != E; ++I)
2667         ProcessPropertyDecl(*I, CDecl);
2668     CDecl->setAtEndRange(AtEnd);
2669   }
2670   if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
2671     IC->setAtEndRange(AtEnd);
2672     if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
2673       // Any property declared in a class extension might have user
2674       // declared setter or getter in current class extension or one
2675       // of the other class extensions. Mark them as synthesized as
2676       // property will be synthesized when property with same name is
2677       // seen in the @implementation.
2678       for (ObjCInterfaceDecl::visible_extensions_iterator
2679              Ext = IDecl->visible_extensions_begin(),
2680              ExtEnd = IDecl->visible_extensions_end();
2681            Ext != ExtEnd; ++Ext) {
2682         for (ObjCContainerDecl::prop_iterator I = Ext->prop_begin(),
2683              E = Ext->prop_end(); I != E; ++I) {
2684           ObjCPropertyDecl *Property = *I;
2685           // Skip over properties declared @dynamic
2686           if (const ObjCPropertyImplDecl *PIDecl
2687               = IC->FindPropertyImplDecl(Property->getIdentifier()))
2688             if (PIDecl->getPropertyImplementation()
2689                   == ObjCPropertyImplDecl::Dynamic)
2690               continue;
2691 
2692           for (ObjCInterfaceDecl::visible_extensions_iterator
2693                  Ext = IDecl->visible_extensions_begin(),
2694                  ExtEnd = IDecl->visible_extensions_end();
2695                Ext != ExtEnd; ++Ext) {
2696             if (ObjCMethodDecl *GetterMethod
2697                   = Ext->getInstanceMethod(Property->getGetterName()))
2698               GetterMethod->setPropertyAccessor(true);
2699             if (!Property->isReadOnly())
2700               if (ObjCMethodDecl *SetterMethod
2701                     = Ext->getInstanceMethod(Property->getSetterName()))
2702                 SetterMethod->setPropertyAccessor(true);
2703           }
2704         }
2705       }
2706       ImplMethodsVsClassMethods(S, IC, IDecl);
2707       AtomicPropertySetterGetterRules(IC, IDecl);
2708       DiagnoseOwningPropertyGetterSynthesis(IC);
2709       DiagnoseUnusedBackingIvarInAccessor(S, IC);
2710       if (IDecl->hasDesignatedInitializers())
2711         DiagnoseMissingDesignatedInitOverrides(IC, IDecl);
2712 
2713       bool HasRootClassAttr = IDecl->hasAttr<ObjCRootClassAttr>();
2714       if (IDecl->getSuperClass() == NULL) {
2715         // This class has no superclass, so check that it has been marked with
2716         // __attribute((objc_root_class)).
2717         if (!HasRootClassAttr) {
2718           SourceLocation DeclLoc(IDecl->getLocation());
2719           SourceLocation SuperClassLoc(PP.getLocForEndOfToken(DeclLoc));
2720           Diag(DeclLoc, diag::warn_objc_root_class_missing)
2721             << IDecl->getIdentifier();
2722           // See if NSObject is in the current scope, and if it is, suggest
2723           // adding " : NSObject " to the class declaration.
2724           NamedDecl *IF = LookupSingleName(TUScope,
2725                                            NSAPIObj->getNSClassId(NSAPI::ClassId_NSObject),
2726                                            DeclLoc, LookupOrdinaryName);
2727           ObjCInterfaceDecl *NSObjectDecl = dyn_cast_or_null<ObjCInterfaceDecl>(IF);
2728           if (NSObjectDecl && NSObjectDecl->getDefinition()) {
2729             Diag(SuperClassLoc, diag::note_objc_needs_superclass)
2730               << FixItHint::CreateInsertion(SuperClassLoc, " : NSObject ");
2731           } else {
2732             Diag(SuperClassLoc, diag::note_objc_needs_superclass);
2733           }
2734         }
2735       } else if (HasRootClassAttr) {
2736         // Complain that only root classes may have this attribute.
2737         Diag(IDecl->getLocation(), diag::err_objc_root_class_subclass);
2738       }
2739 
2740       if (LangOpts.ObjCRuntime.isNonFragile()) {
2741         while (IDecl->getSuperClass()) {
2742           DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
2743           IDecl = IDecl->getSuperClass();
2744         }
2745       }
2746     }
2747     SetIvarInitializers(IC);
2748   } else if (ObjCCategoryImplDecl* CatImplClass =
2749                                    dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
2750     CatImplClass->setAtEndRange(AtEnd);
2751 
2752     // Find category interface decl and then check that all methods declared
2753     // in this interface are implemented in the category @implementation.
2754     if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
2755       if (ObjCCategoryDecl *Cat
2756             = IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier())) {
2757         ImplMethodsVsClassMethods(S, CatImplClass, Cat);
2758       }
2759     }
2760   }
2761   if (isInterfaceDeclKind) {
2762     // Reject invalid vardecls.
2763     for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2764       DeclGroupRef DG = allTUVars[i].get();
2765       for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2766         if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
2767           if (!VDecl->hasExternalStorage())
2768             Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
2769         }
2770     }
2771   }
2772   ActOnObjCContainerFinishDefinition();
2773 
2774   for (unsigned i = 0, e = allTUVars.size(); i != e; i++) {
2775     DeclGroupRef DG = allTUVars[i].get();
2776     for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
2777       (*I)->setTopLevelDeclInObjCContainer();
2778     Consumer.HandleTopLevelDeclInObjCContainer(DG);
2779   }
2780 
2781   ActOnDocumentableDecl(ClassDecl);
2782   return ClassDecl;
2783 }
2784 
2785 
2786 /// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
2787 /// objective-c's type qualifier from the parser version of the same info.
2788 static Decl::ObjCDeclQualifier
2789 CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
2790   return (Decl::ObjCDeclQualifier) (unsigned) PQTVal;
2791 }
2792 
2793 /// \brief Check whether the declared result type of the given Objective-C
2794 /// method declaration is compatible with the method's class.
2795 ///
2796 static Sema::ResultTypeCompatibilityKind
2797 CheckRelatedResultTypeCompatibility(Sema &S, ObjCMethodDecl *Method,
2798                                     ObjCInterfaceDecl *CurrentClass) {
2799   QualType ResultType = Method->getReturnType();
2800 
2801   // If an Objective-C method inherits its related result type, then its
2802   // declared result type must be compatible with its own class type. The
2803   // declared result type is compatible if:
2804   if (const ObjCObjectPointerType *ResultObjectType
2805                                 = ResultType->getAs<ObjCObjectPointerType>()) {
2806     //   - it is id or qualified id, or
2807     if (ResultObjectType->isObjCIdType() ||
2808         ResultObjectType->isObjCQualifiedIdType())
2809       return Sema::RTC_Compatible;
2810 
2811     if (CurrentClass) {
2812       if (ObjCInterfaceDecl *ResultClass
2813                                       = ResultObjectType->getInterfaceDecl()) {
2814         //   - it is the same as the method's class type, or
2815         if (declaresSameEntity(CurrentClass, ResultClass))
2816           return Sema::RTC_Compatible;
2817 
2818         //   - it is a superclass of the method's class type
2819         if (ResultClass->isSuperClassOf(CurrentClass))
2820           return Sema::RTC_Compatible;
2821       }
2822     } else {
2823       // Any Objective-C pointer type might be acceptable for a protocol
2824       // method; we just don't know.
2825       return Sema::RTC_Unknown;
2826     }
2827   }
2828 
2829   return Sema::RTC_Incompatible;
2830 }
2831 
2832 namespace {
2833 /// A helper class for searching for methods which a particular method
2834 /// overrides.
2835 class OverrideSearch {
2836 public:
2837   Sema &S;
2838   ObjCMethodDecl *Method;
2839   llvm::SmallPtrSet<ObjCMethodDecl*, 4> Overridden;
2840   bool Recursive;
2841 
2842 public:
2843   OverrideSearch(Sema &S, ObjCMethodDecl *method) : S(S), Method(method) {
2844     Selector selector = method->getSelector();
2845 
2846     // Bypass this search if we've never seen an instance/class method
2847     // with this selector before.
2848     Sema::GlobalMethodPool::iterator it = S.MethodPool.find(selector);
2849     if (it == S.MethodPool.end()) {
2850       if (!S.getExternalSource()) return;
2851       S.ReadMethodPool(selector);
2852 
2853       it = S.MethodPool.find(selector);
2854       if (it == S.MethodPool.end())
2855         return;
2856     }
2857     ObjCMethodList &list =
2858       method->isInstanceMethod() ? it->second.first : it->second.second;
2859     if (!list.Method) return;
2860 
2861     ObjCContainerDecl *container
2862       = cast<ObjCContainerDecl>(method->getDeclContext());
2863 
2864     // Prevent the search from reaching this container again.  This is
2865     // important with categories, which override methods from the
2866     // interface and each other.
2867     if (ObjCCategoryDecl *Category = dyn_cast<ObjCCategoryDecl>(container)) {
2868       searchFromContainer(container);
2869       if (ObjCInterfaceDecl *Interface = Category->getClassInterface())
2870         searchFromContainer(Interface);
2871     } else {
2872       searchFromContainer(container);
2873     }
2874   }
2875 
2876   typedef llvm::SmallPtrSet<ObjCMethodDecl*, 128>::iterator iterator;
2877   iterator begin() const { return Overridden.begin(); }
2878   iterator end() const { return Overridden.end(); }
2879 
2880 private:
2881   void searchFromContainer(ObjCContainerDecl *container) {
2882     if (container->isInvalidDecl()) return;
2883 
2884     switch (container->getDeclKind()) {
2885 #define OBJCCONTAINER(type, base) \
2886     case Decl::type: \
2887       searchFrom(cast<type##Decl>(container)); \
2888       break;
2889 #define ABSTRACT_DECL(expansion)
2890 #define DECL(type, base) \
2891     case Decl::type:
2892 #include "clang/AST/DeclNodes.inc"
2893       llvm_unreachable("not an ObjC container!");
2894     }
2895   }
2896 
2897   void searchFrom(ObjCProtocolDecl *protocol) {
2898     if (!protocol->hasDefinition())
2899       return;
2900 
2901     // A method in a protocol declaration overrides declarations from
2902     // referenced ("parent") protocols.
2903     search(protocol->getReferencedProtocols());
2904   }
2905 
2906   void searchFrom(ObjCCategoryDecl *category) {
2907     // A method in a category declaration overrides declarations from
2908     // the main class and from protocols the category references.
2909     // The main class is handled in the constructor.
2910     search(category->getReferencedProtocols());
2911   }
2912 
2913   void searchFrom(ObjCCategoryImplDecl *impl) {
2914     // A method in a category definition that has a category
2915     // declaration overrides declarations from the category
2916     // declaration.
2917     if (ObjCCategoryDecl *category = impl->getCategoryDecl()) {
2918       search(category);
2919       if (ObjCInterfaceDecl *Interface = category->getClassInterface())
2920         search(Interface);
2921 
2922     // Otherwise it overrides declarations from the class.
2923     } else if (ObjCInterfaceDecl *Interface = impl->getClassInterface()) {
2924       search(Interface);
2925     }
2926   }
2927 
2928   void searchFrom(ObjCInterfaceDecl *iface) {
2929     // A method in a class declaration overrides declarations from
2930     if (!iface->hasDefinition())
2931       return;
2932 
2933     //   - categories,
2934     for (ObjCInterfaceDecl::known_categories_iterator
2935            cat = iface->known_categories_begin(),
2936            catEnd = iface->known_categories_end();
2937          cat != catEnd; ++cat) {
2938       search(*cat);
2939     }
2940 
2941     //   - the super class, and
2942     if (ObjCInterfaceDecl *super = iface->getSuperClass())
2943       search(super);
2944 
2945     //   - any referenced protocols.
2946     search(iface->getReferencedProtocols());
2947   }
2948 
2949   void searchFrom(ObjCImplementationDecl *impl) {
2950     // A method in a class implementation overrides declarations from
2951     // the class interface.
2952     if (ObjCInterfaceDecl *Interface = impl->getClassInterface())
2953       search(Interface);
2954   }
2955 
2956 
2957   void search(const ObjCProtocolList &protocols) {
2958     for (ObjCProtocolList::iterator i = protocols.begin(), e = protocols.end();
2959          i != e; ++i)
2960       search(*i);
2961   }
2962 
2963   void search(ObjCContainerDecl *container) {
2964     // Check for a method in this container which matches this selector.
2965     ObjCMethodDecl *meth = container->getMethod(Method->getSelector(),
2966                                                 Method->isInstanceMethod(),
2967                                                 /*AllowHidden=*/true);
2968 
2969     // If we find one, record it and bail out.
2970     if (meth) {
2971       Overridden.insert(meth);
2972       return;
2973     }
2974 
2975     // Otherwise, search for methods that a hypothetical method here
2976     // would have overridden.
2977 
2978     // Note that we're now in a recursive case.
2979     Recursive = true;
2980 
2981     searchFromContainer(container);
2982   }
2983 };
2984 }
2985 
2986 void Sema::CheckObjCMethodOverrides(ObjCMethodDecl *ObjCMethod,
2987                                     ObjCInterfaceDecl *CurrentClass,
2988                                     ResultTypeCompatibilityKind RTC) {
2989   // Search for overridden methods and merge information down from them.
2990   OverrideSearch overrides(*this, ObjCMethod);
2991   // Keep track if the method overrides any method in the class's base classes,
2992   // its protocols, or its categories' protocols; we will keep that info
2993   // in the ObjCMethodDecl.
2994   // For this info, a method in an implementation is not considered as
2995   // overriding the same method in the interface or its categories.
2996   bool hasOverriddenMethodsInBaseOrProtocol = false;
2997   for (OverrideSearch::iterator
2998          i = overrides.begin(), e = overrides.end(); i != e; ++i) {
2999     ObjCMethodDecl *overridden = *i;
3000 
3001     if (!hasOverriddenMethodsInBaseOrProtocol) {
3002       if (isa<ObjCProtocolDecl>(overridden->getDeclContext()) ||
3003           CurrentClass != overridden->getClassInterface() ||
3004           overridden->isOverriding()) {
3005         hasOverriddenMethodsInBaseOrProtocol = true;
3006 
3007       } else if (isa<ObjCImplDecl>(ObjCMethod->getDeclContext())) {
3008         // OverrideSearch will return as "overridden" the same method in the
3009         // interface. For hasOverriddenMethodsInBaseOrProtocol, we need to
3010         // check whether a category of a base class introduced a method with the
3011         // same selector, after the interface method declaration.
3012         // To avoid unnecessary lookups in the majority of cases, we use the
3013         // extra info bits in GlobalMethodPool to check whether there were any
3014         // category methods with this selector.
3015         GlobalMethodPool::iterator It =
3016             MethodPool.find(ObjCMethod->getSelector());
3017         if (It != MethodPool.end()) {
3018           ObjCMethodList &List =
3019             ObjCMethod->isInstanceMethod()? It->second.first: It->second.second;
3020           unsigned CategCount = List.getBits();
3021           if (CategCount > 0) {
3022             // If the method is in a category we'll do lookup if there were at
3023             // least 2 category methods recorded, otherwise only one will do.
3024             if (CategCount > 1 ||
3025                 !isa<ObjCCategoryImplDecl>(overridden->getDeclContext())) {
3026               OverrideSearch overrides(*this, overridden);
3027               for (OverrideSearch::iterator
3028                      OI= overrides.begin(), OE= overrides.end(); OI!=OE; ++OI) {
3029                 ObjCMethodDecl *SuperOverridden = *OI;
3030                 if (isa<ObjCProtocolDecl>(SuperOverridden->getDeclContext()) ||
3031                     CurrentClass != SuperOverridden->getClassInterface()) {
3032                   hasOverriddenMethodsInBaseOrProtocol = true;
3033                   overridden->setOverriding(true);
3034                   break;
3035                 }
3036               }
3037             }
3038           }
3039         }
3040       }
3041     }
3042 
3043     // Propagate down the 'related result type' bit from overridden methods.
3044     if (RTC != Sema::RTC_Incompatible && overridden->hasRelatedResultType())
3045       ObjCMethod->SetRelatedResultType();
3046 
3047     // Then merge the declarations.
3048     mergeObjCMethodDecls(ObjCMethod, overridden);
3049 
3050     if (ObjCMethod->isImplicit() && overridden->isImplicit())
3051       continue; // Conflicting properties are detected elsewhere.
3052 
3053     // Check for overriding methods
3054     if (isa<ObjCInterfaceDecl>(ObjCMethod->getDeclContext()) ||
3055         isa<ObjCImplementationDecl>(ObjCMethod->getDeclContext()))
3056       CheckConflictingOverridingMethod(ObjCMethod, overridden,
3057               isa<ObjCProtocolDecl>(overridden->getDeclContext()));
3058 
3059     if (CurrentClass && overridden->getDeclContext() != CurrentClass &&
3060         isa<ObjCInterfaceDecl>(overridden->getDeclContext()) &&
3061         !overridden->isImplicit() /* not meant for properties */) {
3062       ObjCMethodDecl::param_iterator ParamI = ObjCMethod->param_begin(),
3063                                           E = ObjCMethod->param_end();
3064       ObjCMethodDecl::param_iterator PrevI = overridden->param_begin(),
3065                                      PrevE = overridden->param_end();
3066       for (; ParamI != E && PrevI != PrevE; ++ParamI, ++PrevI) {
3067         assert(PrevI != overridden->param_end() && "Param mismatch");
3068         QualType T1 = Context.getCanonicalType((*ParamI)->getType());
3069         QualType T2 = Context.getCanonicalType((*PrevI)->getType());
3070         // If type of argument of method in this class does not match its
3071         // respective argument type in the super class method, issue warning;
3072         if (!Context.typesAreCompatible(T1, T2)) {
3073           Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
3074             << T1 << T2;
3075           Diag(overridden->getLocation(), diag::note_previous_declaration);
3076           break;
3077         }
3078       }
3079     }
3080   }
3081 
3082   ObjCMethod->setOverriding(hasOverriddenMethodsInBaseOrProtocol);
3083 }
3084 
3085 Decl *Sema::ActOnMethodDeclaration(
3086     Scope *S,
3087     SourceLocation MethodLoc, SourceLocation EndLoc,
3088     tok::TokenKind MethodType,
3089     ObjCDeclSpec &ReturnQT, ParsedType ReturnType,
3090     ArrayRef<SourceLocation> SelectorLocs,
3091     Selector Sel,
3092     // optional arguments. The number of types/arguments is obtained
3093     // from the Sel.getNumArgs().
3094     ObjCArgInfo *ArgInfo,
3095     DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
3096     AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
3097     bool isVariadic, bool MethodDefinition) {
3098   // Make sure we can establish a context for the method.
3099   if (!CurContext->isObjCContainer()) {
3100     Diag(MethodLoc, diag::error_missing_method_context);
3101     return 0;
3102   }
3103   ObjCContainerDecl *OCD = dyn_cast<ObjCContainerDecl>(CurContext);
3104   Decl *ClassDecl = cast<Decl>(OCD);
3105   QualType resultDeclType;
3106 
3107   bool HasRelatedResultType = false;
3108   TypeSourceInfo *ReturnTInfo = 0;
3109   if (ReturnType) {
3110     resultDeclType = GetTypeFromParser(ReturnType, &ReturnTInfo);
3111 
3112     if (CheckFunctionReturnType(resultDeclType, MethodLoc))
3113       return 0;
3114 
3115     HasRelatedResultType = (resultDeclType == Context.getObjCInstanceType());
3116   } else { // get the type for "id".
3117     resultDeclType = Context.getObjCIdType();
3118     Diag(MethodLoc, diag::warn_missing_method_return_type)
3119       << FixItHint::CreateInsertion(SelectorLocs.front(), "(id)");
3120   }
3121 
3122   ObjCMethodDecl *ObjCMethod = ObjCMethodDecl::Create(
3123       Context, MethodLoc, EndLoc, Sel, resultDeclType, ReturnTInfo, CurContext,
3124       MethodType == tok::minus, isVariadic,
3125       /*isPropertyAccessor=*/false,
3126       /*isImplicitlyDeclared=*/false, /*isDefined=*/false,
3127       MethodDeclKind == tok::objc_optional ? ObjCMethodDecl::Optional
3128                                            : ObjCMethodDecl::Required,
3129       HasRelatedResultType);
3130 
3131   SmallVector<ParmVarDecl*, 16> Params;
3132 
3133   for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
3134     QualType ArgType;
3135     TypeSourceInfo *DI;
3136 
3137     if (!ArgInfo[i].Type) {
3138       ArgType = Context.getObjCIdType();
3139       DI = 0;
3140     } else {
3141       ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
3142     }
3143 
3144     LookupResult R(*this, ArgInfo[i].Name, ArgInfo[i].NameLoc,
3145                    LookupOrdinaryName, ForRedeclaration);
3146     LookupName(R, S);
3147     if (R.isSingleResult()) {
3148       NamedDecl *PrevDecl = R.getFoundDecl();
3149       if (S->isDeclScope(PrevDecl)) {
3150         Diag(ArgInfo[i].NameLoc,
3151              (MethodDefinition ? diag::warn_method_param_redefinition
3152                                : diag::warn_method_param_declaration))
3153           << ArgInfo[i].Name;
3154         Diag(PrevDecl->getLocation(),
3155              diag::note_previous_declaration);
3156       }
3157     }
3158 
3159     SourceLocation StartLoc = DI
3160       ? DI->getTypeLoc().getBeginLoc()
3161       : ArgInfo[i].NameLoc;
3162 
3163     ParmVarDecl* Param = CheckParameter(ObjCMethod, StartLoc,
3164                                         ArgInfo[i].NameLoc, ArgInfo[i].Name,
3165                                         ArgType, DI, SC_None);
3166 
3167     Param->setObjCMethodScopeInfo(i);
3168 
3169     Param->setObjCDeclQualifier(
3170       CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
3171 
3172     // Apply the attributes to the parameter.
3173     ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
3174 
3175     if (Param->hasAttr<BlocksAttr>()) {
3176       Diag(Param->getLocation(), diag::err_block_on_nonlocal);
3177       Param->setInvalidDecl();
3178     }
3179     S->AddDecl(Param);
3180     IdResolver.AddDecl(Param);
3181 
3182     Params.push_back(Param);
3183   }
3184 
3185   for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
3186     ParmVarDecl *Param = cast<ParmVarDecl>(CParamInfo[i].Param);
3187     QualType ArgType = Param->getType();
3188     if (ArgType.isNull())
3189       ArgType = Context.getObjCIdType();
3190     else
3191       // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
3192       ArgType = Context.getAdjustedParameterType(ArgType);
3193 
3194     Param->setDeclContext(ObjCMethod);
3195     Params.push_back(Param);
3196   }
3197 
3198   ObjCMethod->setMethodParams(Context, Params, SelectorLocs);
3199   ObjCMethod->setObjCDeclQualifier(
3200     CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
3201 
3202   if (AttrList)
3203     ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
3204 
3205   // Add the method now.
3206   const ObjCMethodDecl *PrevMethod = 0;
3207   if (ObjCImplDecl *ImpDecl = dyn_cast<ObjCImplDecl>(ClassDecl)) {
3208     if (MethodType == tok::minus) {
3209       PrevMethod = ImpDecl->getInstanceMethod(Sel);
3210       ImpDecl->addInstanceMethod(ObjCMethod);
3211     } else {
3212       PrevMethod = ImpDecl->getClassMethod(Sel);
3213       ImpDecl->addClassMethod(ObjCMethod);
3214     }
3215 
3216     ObjCMethodDecl *IMD = 0;
3217     if (ObjCInterfaceDecl *IDecl = ImpDecl->getClassInterface())
3218       IMD = IDecl->lookupMethod(ObjCMethod->getSelector(),
3219                                 ObjCMethod->isInstanceMethod());
3220     if (IMD && IMD->hasAttr<ObjCRequiresSuperAttr>() &&
3221         !ObjCMethod->hasAttr<ObjCRequiresSuperAttr>()) {
3222       // merge the attribute into implementation.
3223       ObjCMethod->addAttr(ObjCRequiresSuperAttr::CreateImplicit(Context,
3224                                                    ObjCMethod->getLocation()));
3225     }
3226     if (isa<ObjCCategoryImplDecl>(ImpDecl)) {
3227       ObjCMethodFamily family =
3228         ObjCMethod->getSelector().getMethodFamily();
3229       if (family == OMF_dealloc && IMD && IMD->isOverriding())
3230         Diag(ObjCMethod->getLocation(), diag::warn_dealloc_in_category)
3231           << ObjCMethod->getDeclName();
3232     }
3233   } else {
3234     cast<DeclContext>(ClassDecl)->addDecl(ObjCMethod);
3235   }
3236 
3237   if (PrevMethod) {
3238     // You can never have two method definitions with the same name.
3239     Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
3240       << ObjCMethod->getDeclName();
3241     Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
3242     ObjCMethod->setInvalidDecl();
3243     return ObjCMethod;
3244   }
3245 
3246   // If this Objective-C method does not have a related result type, but we
3247   // are allowed to infer related result types, try to do so based on the
3248   // method family.
3249   ObjCInterfaceDecl *CurrentClass = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
3250   if (!CurrentClass) {
3251     if (ObjCCategoryDecl *Cat = dyn_cast<ObjCCategoryDecl>(ClassDecl))
3252       CurrentClass = Cat->getClassInterface();
3253     else if (ObjCImplDecl *Impl = dyn_cast<ObjCImplDecl>(ClassDecl))
3254       CurrentClass = Impl->getClassInterface();
3255     else if (ObjCCategoryImplDecl *CatImpl
3256                                    = dyn_cast<ObjCCategoryImplDecl>(ClassDecl))
3257       CurrentClass = CatImpl->getClassInterface();
3258   }
3259 
3260   ResultTypeCompatibilityKind RTC
3261     = CheckRelatedResultTypeCompatibility(*this, ObjCMethod, CurrentClass);
3262 
3263   CheckObjCMethodOverrides(ObjCMethod, CurrentClass, RTC);
3264 
3265   bool ARCError = false;
3266   if (getLangOpts().ObjCAutoRefCount)
3267     ARCError = CheckARCMethodDecl(ObjCMethod);
3268 
3269   // Infer the related result type when possible.
3270   if (!ARCError && RTC == Sema::RTC_Compatible &&
3271       !ObjCMethod->hasRelatedResultType() &&
3272       LangOpts.ObjCInferRelatedResultType) {
3273     bool InferRelatedResultType = false;
3274     switch (ObjCMethod->getMethodFamily()) {
3275     case OMF_None:
3276     case OMF_copy:
3277     case OMF_dealloc:
3278     case OMF_finalize:
3279     case OMF_mutableCopy:
3280     case OMF_release:
3281     case OMF_retainCount:
3282     case OMF_performSelector:
3283       break;
3284 
3285     case OMF_alloc:
3286     case OMF_new:
3287       InferRelatedResultType = ObjCMethod->isClassMethod();
3288       break;
3289 
3290     case OMF_init:
3291     case OMF_autorelease:
3292     case OMF_retain:
3293     case OMF_self:
3294       InferRelatedResultType = ObjCMethod->isInstanceMethod();
3295       break;
3296     }
3297 
3298     if (InferRelatedResultType)
3299       ObjCMethod->SetRelatedResultType();
3300   }
3301 
3302   ActOnDocumentableDecl(ObjCMethod);
3303 
3304   return ObjCMethod;
3305 }
3306 
3307 bool Sema::CheckObjCDeclScope(Decl *D) {
3308   // Following is also an error. But it is caused by a missing @end
3309   // and diagnostic is issued elsewhere.
3310   if (isa<ObjCContainerDecl>(CurContext->getRedeclContext()))
3311     return false;
3312 
3313   // If we switched context to translation unit while we are still lexically in
3314   // an objc container, it means the parser missed emitting an error.
3315   if (isa<TranslationUnitDecl>(getCurLexicalContext()->getRedeclContext()))
3316     return false;
3317 
3318   Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
3319   D->setInvalidDecl();
3320 
3321   return true;
3322 }
3323 
3324 /// Called whenever \@defs(ClassName) is encountered in the source.  Inserts the
3325 /// instance variables of ClassName into Decls.
3326 void Sema::ActOnDefs(Scope *S, Decl *TagD, SourceLocation DeclStart,
3327                      IdentifierInfo *ClassName,
3328                      SmallVectorImpl<Decl*> &Decls) {
3329   // Check that ClassName is a valid class
3330   ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
3331   if (!Class) {
3332     Diag(DeclStart, diag::err_undef_interface) << ClassName;
3333     return;
3334   }
3335   if (LangOpts.ObjCRuntime.isNonFragile()) {
3336     Diag(DeclStart, diag::err_atdef_nonfragile_interface);
3337     return;
3338   }
3339 
3340   // Collect the instance variables
3341   SmallVector<const ObjCIvarDecl*, 32> Ivars;
3342   Context.DeepCollectObjCIvars(Class, true, Ivars);
3343   // For each ivar, create a fresh ObjCAtDefsFieldDecl.
3344   for (unsigned i = 0; i < Ivars.size(); i++) {
3345     const FieldDecl* ID = cast<FieldDecl>(Ivars[i]);
3346     RecordDecl *Record = dyn_cast<RecordDecl>(TagD);
3347     Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record,
3348                                            /*FIXME: StartL=*/ID->getLocation(),
3349                                            ID->getLocation(),
3350                                            ID->getIdentifier(), ID->getType(),
3351                                            ID->getBitWidth());
3352     Decls.push_back(FD);
3353   }
3354 
3355   // Introduce all of these fields into the appropriate scope.
3356   for (SmallVectorImpl<Decl*>::iterator D = Decls.begin();
3357        D != Decls.end(); ++D) {
3358     FieldDecl *FD = cast<FieldDecl>(*D);
3359     if (getLangOpts().CPlusPlus)
3360       PushOnScopeChains(cast<FieldDecl>(FD), S);
3361     else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD))
3362       Record->addDecl(FD);
3363   }
3364 }
3365 
3366 /// \brief Build a type-check a new Objective-C exception variable declaration.
3367 VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo, QualType T,
3368                                       SourceLocation StartLoc,
3369                                       SourceLocation IdLoc,
3370                                       IdentifierInfo *Id,
3371                                       bool Invalid) {
3372   // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
3373   // duration shall not be qualified by an address-space qualifier."
3374   // Since all parameters have automatic store duration, they can not have
3375   // an address space.
3376   if (T.getAddressSpace() != 0) {
3377     Diag(IdLoc, diag::err_arg_with_address_space);
3378     Invalid = true;
3379   }
3380 
3381   // An @catch parameter must be an unqualified object pointer type;
3382   // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
3383   if (Invalid) {
3384     // Don't do any further checking.
3385   } else if (T->isDependentType()) {
3386     // Okay: we don't know what this type will instantiate to.
3387   } else if (!T->isObjCObjectPointerType()) {
3388     Invalid = true;
3389     Diag(IdLoc ,diag::err_catch_param_not_objc_type);
3390   } else if (T->isObjCQualifiedIdType()) {
3391     Invalid = true;
3392     Diag(IdLoc, diag::err_illegal_qualifiers_on_catch_parm);
3393   }
3394 
3395   VarDecl *New = VarDecl::Create(Context, CurContext, StartLoc, IdLoc, Id,
3396                                  T, TInfo, SC_None);
3397   New->setExceptionVariable(true);
3398 
3399   // In ARC, infer 'retaining' for variables of retainable type.
3400   if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(New))
3401     Invalid = true;
3402 
3403   if (Invalid)
3404     New->setInvalidDecl();
3405   return New;
3406 }
3407 
3408 Decl *Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
3409   const DeclSpec &DS = D.getDeclSpec();
3410 
3411   // We allow the "register" storage class on exception variables because
3412   // GCC did, but we drop it completely. Any other storage class is an error.
3413   if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
3414     Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
3415       << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
3416   } else if (DeclSpec::SCS SCS = DS.getStorageClassSpec()) {
3417     Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
3418       << DeclSpec::getSpecifierName(SCS);
3419   }
3420   if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
3421     Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
3422          diag::err_invalid_thread)
3423      << DeclSpec::getSpecifierName(TSCS);
3424   D.getMutableDeclSpec().ClearStorageClassSpecs();
3425 
3426   DiagnoseFunctionSpecifiers(D.getDeclSpec());
3427 
3428   // Check that there are no default arguments inside the type of this
3429   // exception object (C++ only).
3430   if (getLangOpts().CPlusPlus)
3431     CheckExtraCXXDefaultArguments(D);
3432 
3433   TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
3434   QualType ExceptionType = TInfo->getType();
3435 
3436   VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType,
3437                                         D.getSourceRange().getBegin(),
3438                                         D.getIdentifierLoc(),
3439                                         D.getIdentifier(),
3440                                         D.isInvalidType());
3441 
3442   // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
3443   if (D.getCXXScopeSpec().isSet()) {
3444     Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
3445       << D.getCXXScopeSpec().getRange();
3446     New->setInvalidDecl();
3447   }
3448 
3449   // Add the parameter declaration into this scope.
3450   S->AddDecl(New);
3451   if (D.getIdentifier())
3452     IdResolver.AddDecl(New);
3453 
3454   ProcessDeclAttributes(S, New, D);
3455 
3456   if (New->hasAttr<BlocksAttr>())
3457     Diag(New->getLocation(), diag::err_block_on_nonlocal);
3458   return New;
3459 }
3460 
3461 /// CollectIvarsToConstructOrDestruct - Collect those ivars which require
3462 /// initialization.
3463 void Sema::CollectIvarsToConstructOrDestruct(ObjCInterfaceDecl *OI,
3464                                 SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
3465   for (ObjCIvarDecl *Iv = OI->all_declared_ivar_begin(); Iv;
3466        Iv= Iv->getNextIvar()) {
3467     QualType QT = Context.getBaseElementType(Iv->getType());
3468     if (QT->isRecordType())
3469       Ivars.push_back(Iv);
3470   }
3471 }
3472 
3473 void Sema::DiagnoseUseOfUnimplementedSelectors() {
3474   // Load referenced selectors from the external source.
3475   if (ExternalSource) {
3476     SmallVector<std::pair<Selector, SourceLocation>, 4> Sels;
3477     ExternalSource->ReadReferencedSelectors(Sels);
3478     for (unsigned I = 0, N = Sels.size(); I != N; ++I)
3479       ReferencedSelectors[Sels[I].first] = Sels[I].second;
3480   }
3481 
3482   // Warning will be issued only when selector table is
3483   // generated (which means there is at lease one implementation
3484   // in the TU). This is to match gcc's behavior.
3485   if (ReferencedSelectors.empty() ||
3486       !Context.AnyObjCImplementation())
3487     return;
3488   for (llvm::DenseMap<Selector, SourceLocation>::iterator S =
3489         ReferencedSelectors.begin(),
3490        E = ReferencedSelectors.end(); S != E; ++S) {
3491     Selector Sel = (*S).first;
3492     if (!LookupImplementedMethodInGlobalPool(Sel))
3493       Diag((*S).second, diag::warn_unimplemented_selector) << Sel;
3494   }
3495   return;
3496 }
3497 
3498 ObjCIvarDecl *
3499 Sema::GetIvarBackingPropertyAccessor(const ObjCMethodDecl *Method,
3500                                      const ObjCPropertyDecl *&PDecl) const {
3501   if (Method->isClassMethod())
3502     return 0;
3503   const ObjCInterfaceDecl *IDecl = Method->getClassInterface();
3504   if (!IDecl)
3505     return 0;
3506   Method = IDecl->lookupMethod(Method->getSelector(), /*isInstance=*/true,
3507                                /*shallowCategoryLookup=*/false,
3508                                /*followSuper=*/false);
3509   if (!Method || !Method->isPropertyAccessor())
3510     return 0;
3511   if ((PDecl = Method->findPropertyDecl()))
3512     if (ObjCIvarDecl *IV = PDecl->getPropertyIvarDecl()) {
3513       // property backing ivar must belong to property's class
3514       // or be a private ivar in class's implementation.
3515       // FIXME. fix the const-ness issue.
3516       IV = const_cast<ObjCInterfaceDecl *>(IDecl)->lookupInstanceVariable(
3517                                                         IV->getIdentifier());
3518       return IV;
3519     }
3520   return 0;
3521 }
3522 
3523 namespace {
3524   /// Used by Sema::DiagnoseUnusedBackingIvarInAccessor to check if a property
3525   /// accessor references the backing ivar.
3526   class UnusedBackingIvarChecker :
3527       public DataRecursiveASTVisitor<UnusedBackingIvarChecker> {
3528   public:
3529     Sema &S;
3530     const ObjCMethodDecl *Method;
3531     const ObjCIvarDecl *IvarD;
3532     bool AccessedIvar;
3533     bool InvokedSelfMethod;
3534 
3535     UnusedBackingIvarChecker(Sema &S, const ObjCMethodDecl *Method,
3536                              const ObjCIvarDecl *IvarD)
3537       : S(S), Method(Method), IvarD(IvarD),
3538         AccessedIvar(false), InvokedSelfMethod(false) {
3539       assert(IvarD);
3540     }
3541 
3542     bool VisitObjCIvarRefExpr(ObjCIvarRefExpr *E) {
3543       if (E->getDecl() == IvarD) {
3544         AccessedIvar = true;
3545         return false;
3546       }
3547       return true;
3548     }
3549 
3550     bool VisitObjCMessageExpr(ObjCMessageExpr *E) {
3551       if (E->getReceiverKind() == ObjCMessageExpr::Instance &&
3552           S.isSelfExpr(E->getInstanceReceiver(), Method)) {
3553         InvokedSelfMethod = true;
3554       }
3555       return true;
3556     }
3557   };
3558 }
3559 
3560 void Sema::DiagnoseUnusedBackingIvarInAccessor(Scope *S,
3561                                           const ObjCImplementationDecl *ImplD) {
3562   if (S->hasUnrecoverableErrorOccurred())
3563     return;
3564 
3565   for (ObjCImplementationDecl::instmeth_iterator
3566          MI = ImplD->instmeth_begin(),
3567          ME = ImplD->instmeth_end(); MI != ME; ++MI) {
3568     const ObjCMethodDecl *CurMethod = *MI;
3569     unsigned DIAG = diag::warn_unused_property_backing_ivar;
3570     SourceLocation Loc = CurMethod->getLocation();
3571     if (Diags.getDiagnosticLevel(DIAG, Loc) == DiagnosticsEngine::Ignored)
3572       continue;
3573 
3574     const ObjCPropertyDecl *PDecl;
3575     const ObjCIvarDecl *IV = GetIvarBackingPropertyAccessor(CurMethod, PDecl);
3576     if (!IV)
3577       continue;
3578 
3579     UnusedBackingIvarChecker Checker(*this, CurMethod, IV);
3580     Checker.TraverseStmt(CurMethod->getBody());
3581     if (Checker.AccessedIvar)
3582       continue;
3583 
3584     // Do not issue this warning if backing ivar is used somewhere and accessor
3585     // implementation makes a self call. This is to prevent false positive in
3586     // cases where the ivar is accessed by another method that the accessor
3587     // delegates to.
3588     if (!IV->isReferenced() || !Checker.InvokedSelfMethod) {
3589       Diag(Loc, DIAG) << IV;
3590       Diag(PDecl->getLocation(), diag::note_property_declare);
3591     }
3592   }
3593 }
3594