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