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