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