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