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