SemaDeclObjC.cpp revision 78713d86faeaaabb8aeb1683353e791defd3a3bf
1//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//  This file implements semantic analysis for Objective C declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
15#include "Lookup.h"
16#include "clang/Sema/ExternalSemaSource.h"
17#include "clang/AST/Expr.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/AST/DeclObjC.h"
20#include "clang/Parse/DeclSpec.h"
21using namespace clang;
22
23/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
24/// and user declared, in the method definition's AST.
25void Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) {
26  assert(getCurMethodDecl() == 0 && "Method parsing confused");
27  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D.getAs<Decl>());
28
29  // If we don't have a valid method decl, simply return.
30  if (!MDecl)
31    return;
32
33  // Allow the rest of sema to find private method decl implementations.
34  if (MDecl->isInstanceMethod())
35    AddInstanceMethodToGlobalPool(MDecl);
36  else
37    AddFactoryMethodToGlobalPool(MDecl);
38
39  // Allow all of Sema to see that we are entering a method definition.
40  PushDeclContext(FnBodyScope, MDecl);
41  PushFunctionScope();
42
43  // Create Decl objects for each parameter, entrring them in the scope for
44  // binding to their use.
45
46  // Insert the invisible arguments, self and _cmd!
47  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
48
49  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
50  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
51
52  // Introduce all of the other parameters into this scope.
53  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
54       E = MDecl->param_end(); PI != E; ++PI)
55    if ((*PI)->getIdentifier())
56      PushOnScopeChains(*PI, FnBodyScope);
57}
58
59Sema::DeclPtrTy Sema::
60ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
61                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
62                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
63                         const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs,
64                         const SourceLocation *ProtoLocs,
65                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
66  assert(ClassName && "Missing class identifier");
67
68  // Check for another declaration kind with the same name.
69  NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
70  if (PrevDecl && PrevDecl->isTemplateParameter()) {
71    // Maybe we will complain about the shadowed template parameter.
72    DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl);
73    // Just pretend that we didn't see the previous declaration.
74    PrevDecl = 0;
75  }
76
77  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
78    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
79    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
80  }
81
82  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
83  if (IDecl) {
84    // Class already seen. Is it a forward declaration?
85    if (!IDecl->isForwardDecl()) {
86      IDecl->setInvalidDecl();
87      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
88      Diag(IDecl->getLocation(), diag::note_previous_definition);
89
90      // Return the previous class interface.
91      // FIXME: don't leak the objects passed in!
92      return DeclPtrTy::make(IDecl);
93    } else {
94      IDecl->setLocation(AtInterfaceLoc);
95      IDecl->setForwardDecl(false);
96      IDecl->setClassLoc(ClassLoc);
97
98      // Since this ObjCInterfaceDecl was created by a forward declaration,
99      // we now add it to the DeclContext since it wasn't added before
100      // (see ActOnForwardClassDeclaration).
101      IDecl->setLexicalDeclContext(CurContext);
102      CurContext->addDecl(IDecl);
103
104      if (AttrList)
105        ProcessDeclAttributeList(TUScope, IDecl, AttrList);
106    }
107  } else {
108    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
109                                      ClassName, ClassLoc);
110    if (AttrList)
111      ProcessDeclAttributeList(TUScope, IDecl, AttrList);
112
113    PushOnScopeChains(IDecl, TUScope);
114  }
115
116  if (SuperName) {
117    // Check if a different kind of symbol declared in this scope.
118    PrevDecl = LookupSingleName(TUScope, SuperName, LookupOrdinaryName);
119
120    if (!PrevDecl) {
121      // Try to correct for a typo in the superclass name.
122      LookupResult R(*this, SuperName, SuperLoc, LookupOrdinaryName);
123      if (CorrectTypo(R, TUScope, 0) &&
124          (PrevDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
125        Diag(SuperLoc, diag::err_undef_superclass_suggest)
126          << SuperName << ClassName << PrevDecl->getDeclName();
127        Diag(PrevDecl->getLocation(), diag::note_previous_decl)
128          << PrevDecl->getDeclName();
129      }
130    }
131
132    if (PrevDecl == IDecl) {
133      Diag(SuperLoc, diag::err_recursive_superclass)
134        << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
135      IDecl->setLocEnd(ClassLoc);
136    } else {
137      ObjCInterfaceDecl *SuperClassDecl =
138                                dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
139
140      // Diagnose classes that inherit from deprecated classes.
141      if (SuperClassDecl)
142        (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
143
144      if (PrevDecl && SuperClassDecl == 0) {
145        // The previous declaration was not a class decl. Check if we have a
146        // typedef. If we do, get the underlying class type.
147        if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
148          QualType T = TDecl->getUnderlyingType();
149          if (T->isObjCInterfaceType()) {
150            if (NamedDecl *IDecl = T->getAs<ObjCInterfaceType>()->getDecl())
151              SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
152          }
153        }
154
155        // This handles the following case:
156        //
157        // typedef int SuperClass;
158        // @interface MyClass : SuperClass {} @end
159        //
160        if (!SuperClassDecl) {
161          Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
162          Diag(PrevDecl->getLocation(), diag::note_previous_definition);
163        }
164      }
165
166      if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
167        if (!SuperClassDecl)
168          Diag(SuperLoc, diag::err_undef_superclass)
169            << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
170        else if (SuperClassDecl->isForwardDecl())
171          Diag(SuperLoc, diag::err_undef_superclass)
172            << SuperClassDecl->getDeclName() << ClassName
173            << SourceRange(AtInterfaceLoc, ClassLoc);
174      }
175      IDecl->setSuperClass(SuperClassDecl);
176      IDecl->setSuperClassLoc(SuperLoc);
177      IDecl->setLocEnd(SuperLoc);
178    }
179  } else { // we have a root class.
180    IDecl->setLocEnd(ClassLoc);
181  }
182
183  /// Check then save referenced protocols.
184  if (NumProtoRefs) {
185    IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
186                           ProtoLocs, Context);
187    IDecl->setLocEnd(EndProtoLoc);
188  }
189
190  CheckObjCDeclScope(IDecl);
191  return DeclPtrTy::make(IDecl);
192}
193
194/// ActOnCompatiblityAlias - this action is called after complete parsing of
195/// @compatibility_alias declaration. It sets up the alias relationships.
196Sema::DeclPtrTy Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
197                                             IdentifierInfo *AliasName,
198                                             SourceLocation AliasLocation,
199                                             IdentifierInfo *ClassName,
200                                             SourceLocation ClassLocation) {
201  // Look for previous declaration of alias name
202  NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, LookupOrdinaryName);
203  if (ADecl) {
204    if (isa<ObjCCompatibleAliasDecl>(ADecl))
205      Diag(AliasLocation, diag::warn_previous_alias_decl);
206    else
207      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
208    Diag(ADecl->getLocation(), diag::note_previous_declaration);
209    return DeclPtrTy();
210  }
211  // Check for class declaration
212  NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
213  if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
214    QualType T = TDecl->getUnderlyingType();
215    if (T->isObjCInterfaceType()) {
216      if (NamedDecl *IDecl = T->getAs<ObjCInterfaceType>()->getDecl()) {
217        ClassName = IDecl->getIdentifier();
218        CDeclU = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
219      }
220    }
221  }
222  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
223  if (CDecl == 0) {
224    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
225    if (CDeclU)
226      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
227    return DeclPtrTy();
228  }
229
230  // Everything checked out, instantiate a new alias declaration AST.
231  ObjCCompatibleAliasDecl *AliasDecl =
232    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
233
234  if (!CheckObjCDeclScope(AliasDecl))
235    PushOnScopeChains(AliasDecl, TUScope);
236
237  return DeclPtrTy::make(AliasDecl);
238}
239
240void Sema::CheckForwardProtocolDeclarationForCircularDependency(
241  IdentifierInfo *PName,
242  SourceLocation &Ploc, SourceLocation PrevLoc,
243  const ObjCList<ObjCProtocolDecl> &PList) {
244  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
245       E = PList.end(); I != E; ++I) {
246
247    if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier())) {
248      if (PDecl->getIdentifier() == PName) {
249        Diag(Ploc, diag::err_protocol_has_circular_dependency);
250        Diag(PrevLoc, diag::note_previous_definition);
251      }
252      CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
253        PDecl->getLocation(), PDecl->getReferencedProtocols());
254    }
255  }
256}
257
258Sema::DeclPtrTy
259Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
260                                  IdentifierInfo *ProtocolName,
261                                  SourceLocation ProtocolLoc,
262                                  const DeclPtrTy *ProtoRefs,
263                                  unsigned NumProtoRefs,
264                                  const SourceLocation *ProtoLocs,
265                                  SourceLocation EndProtoLoc,
266                                  AttributeList *AttrList) {
267  // FIXME: Deal with AttrList.
268  assert(ProtocolName && "Missing protocol identifier");
269  ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName);
270  if (PDecl) {
271    // Protocol already seen. Better be a forward protocol declaration
272    if (!PDecl->isForwardDecl()) {
273      Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
274      Diag(PDecl->getLocation(), diag::note_previous_definition);
275      // Just return the protocol we already had.
276      // FIXME: don't leak the objects passed in!
277      return DeclPtrTy::make(PDecl);
278    }
279    ObjCList<ObjCProtocolDecl> PList;
280    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
281    CheckForwardProtocolDeclarationForCircularDependency(
282      ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
283    PList.Destroy(Context);
284
285    // Make sure the cached decl gets a valid start location.
286    PDecl->setLocation(AtProtoInterfaceLoc);
287    PDecl->setForwardDecl(false);
288  } else {
289    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
290                                     AtProtoInterfaceLoc,ProtocolName);
291    PushOnScopeChains(PDecl, TUScope);
292    PDecl->setForwardDecl(false);
293  }
294  if (AttrList)
295    ProcessDeclAttributeList(TUScope, PDecl, AttrList);
296  if (NumProtoRefs) {
297    /// Check then save referenced protocols.
298    PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
299                           ProtoLocs, Context);
300    PDecl->setLocEnd(EndProtoLoc);
301  }
302
303  CheckObjCDeclScope(PDecl);
304  return DeclPtrTy::make(PDecl);
305}
306
307/// FindProtocolDeclaration - This routine looks up protocols and
308/// issues an error if they are not declared. It returns list of
309/// protocol declarations in its 'Protocols' argument.
310void
311Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
312                              const IdentifierLocPair *ProtocolId,
313                              unsigned NumProtocols,
314                              llvm::SmallVectorImpl<DeclPtrTy> &Protocols) {
315  for (unsigned i = 0; i != NumProtocols; ++i) {
316    ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first);
317    if (!PDecl) {
318      LookupResult R(*this, ProtocolId[i].first, ProtocolId[i].second,
319                     LookupObjCProtocolName);
320      if (CorrectTypo(R, TUScope, 0) &&
321          (PDecl = R.getAsSingle<ObjCProtocolDecl>())) {
322        Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
323          << ProtocolId[i].first << R.getLookupName();
324        Diag(PDecl->getLocation(), diag::note_previous_decl)
325          << PDecl->getDeclName();
326      }
327    }
328
329    if (!PDecl) {
330      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
331        << ProtocolId[i].first;
332      continue;
333    }
334
335    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
336
337    // If this is a forward declaration and we are supposed to warn in this
338    // case, do it.
339    if (WarnOnDeclarations && PDecl->isForwardDecl())
340      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
341        << ProtocolId[i].first;
342    Protocols.push_back(DeclPtrTy::make(PDecl));
343  }
344}
345
346/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
347/// a class method in its extension.
348///
349void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
350                                            ObjCInterfaceDecl *ID) {
351  if (!ID)
352    return;  // Possibly due to previous error
353
354  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
355  for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
356       e =  ID->meth_end(); i != e; ++i) {
357    ObjCMethodDecl *MD = *i;
358    MethodMap[MD->getSelector()] = MD;
359  }
360
361  if (MethodMap.empty())
362    return;
363  for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
364       e =  CAT->meth_end(); i != e; ++i) {
365    ObjCMethodDecl *Method = *i;
366    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
367    if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
368      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
369            << Method->getDeclName();
370      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
371    }
372  }
373}
374
375/// ActOnForwardProtocolDeclaration - Handle @protocol foo;
376Action::DeclPtrTy
377Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
378                                      const IdentifierLocPair *IdentList,
379                                      unsigned NumElts,
380                                      AttributeList *attrList) {
381  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
382  llvm::SmallVector<SourceLocation, 8> ProtoLocs;
383
384  for (unsigned i = 0; i != NumElts; ++i) {
385    IdentifierInfo *Ident = IdentList[i].first;
386    ObjCProtocolDecl *PDecl = LookupProtocol(Ident);
387    if (PDecl == 0) { // Not already seen?
388      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
389                                       IdentList[i].second, Ident);
390      PushOnScopeChains(PDecl, TUScope);
391    }
392    if (attrList)
393      ProcessDeclAttributeList(TUScope, PDecl, attrList);
394    Protocols.push_back(PDecl);
395    ProtoLocs.push_back(IdentList[i].second);
396  }
397
398  ObjCForwardProtocolDecl *PDecl =
399    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
400                                    Protocols.data(), Protocols.size(),
401                                    ProtoLocs.data());
402  CurContext->addDecl(PDecl);
403  CheckObjCDeclScope(PDecl);
404  return DeclPtrTy::make(PDecl);
405}
406
407Sema::DeclPtrTy Sema::
408ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
409                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
410                            IdentifierInfo *CategoryName,
411                            SourceLocation CategoryLoc,
412                            const DeclPtrTy *ProtoRefs,
413                            unsigned NumProtoRefs,
414                            const SourceLocation *ProtoLocs,
415                            SourceLocation EndProtoLoc) {
416  ObjCCategoryDecl *CDecl = 0;
417  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc);
418
419  /// Check that class of this category is already completely declared.
420  if (!IDecl || IDecl->isForwardDecl()) {
421    // Create an invalid ObjCCategoryDecl to serve as context for
422    // the enclosing method declarations.  We mark the decl invalid
423    // to make it clear that this isn't a valid AST.
424    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
425                                     ClassLoc, CategoryLoc, CategoryName);
426    CDecl->setInvalidDecl();
427    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
428    return DeclPtrTy::make(CDecl);
429  }
430
431  if (!CategoryName) {
432    // Class extensions require a special treatment. Use an existing one.
433    // Note that 'getClassExtension()' can return NULL.
434    CDecl = IDecl->getClassExtension();
435    if (IDecl->getImplementation()) {
436      Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
437      Diag(IDecl->getImplementation()->getLocation(),
438           diag::note_implementation_declared);
439    }
440  }
441
442  if (!CDecl) {
443    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
444                                     ClassLoc, CategoryLoc, CategoryName);
445    // FIXME: PushOnScopeChains?
446    CurContext->addDecl(CDecl);
447
448    CDecl->setClassInterface(IDecl);
449    // Insert first use of class extension to the list of class's categories.
450    if (!CategoryName)
451      CDecl->insertNextClassCategory();
452  }
453
454  // If the interface is deprecated, warn about it.
455  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
456
457  if (CategoryName) {
458    /// Check for duplicate interface declaration for this category
459    ObjCCategoryDecl *CDeclChain;
460    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
461         CDeclChain = CDeclChain->getNextClassCategory()) {
462      if (CDeclChain->getIdentifier() == CategoryName) {
463        // Class extensions can be declared multiple times.
464        Diag(CategoryLoc, diag::warn_dup_category_def)
465          << ClassName << CategoryName;
466        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
467        break;
468      }
469    }
470    if (!CDeclChain)
471      CDecl->insertNextClassCategory();
472  }
473
474  if (NumProtoRefs) {
475    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
476                           ProtoLocs, Context);
477    // Protocols in the class extension belong to the class.
478    if (CDecl->IsClassExtension())
479     IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
480                                            NumProtoRefs, ProtoLocs,
481                                            Context);
482  }
483
484  CheckObjCDeclScope(CDecl);
485  return DeclPtrTy::make(CDecl);
486}
487
488/// ActOnStartCategoryImplementation - Perform semantic checks on the
489/// category implementation declaration and build an ObjCCategoryImplDecl
490/// object.
491Sema::DeclPtrTy Sema::ActOnStartCategoryImplementation(
492                      SourceLocation AtCatImplLoc,
493                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
494                      IdentifierInfo *CatName, SourceLocation CatLoc) {
495  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc);
496  ObjCCategoryDecl *CatIDecl = 0;
497  if (IDecl) {
498    CatIDecl = IDecl->FindCategoryDeclaration(CatName);
499    if (!CatIDecl) {
500      // Category @implementation with no corresponding @interface.
501      // Create and install one.
502      CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
503                                          SourceLocation(), SourceLocation(),
504                                          CatName);
505      CatIDecl->setClassInterface(IDecl);
506      CatIDecl->insertNextClassCategory();
507    }
508  }
509
510  ObjCCategoryImplDecl *CDecl =
511    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
512                                 IDecl);
513  /// Check that class of this category is already completely declared.
514  if (!IDecl || IDecl->isForwardDecl())
515    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
516
517  // FIXME: PushOnScopeChains?
518  CurContext->addDecl(CDecl);
519
520  /// Check that CatName, category name, is not used in another implementation.
521  if (CatIDecl) {
522    if (CatIDecl->getImplementation()) {
523      Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
524        << CatName;
525      Diag(CatIDecl->getImplementation()->getLocation(),
526           diag::note_previous_definition);
527    } else
528      CatIDecl->setImplementation(CDecl);
529  }
530
531  CheckObjCDeclScope(CDecl);
532  return DeclPtrTy::make(CDecl);
533}
534
535Sema::DeclPtrTy Sema::ActOnStartClassImplementation(
536                      SourceLocation AtClassImplLoc,
537                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
538                      IdentifierInfo *SuperClassname,
539                      SourceLocation SuperClassLoc) {
540  ObjCInterfaceDecl* IDecl = 0;
541  // Check for another declaration kind with the same name.
542  NamedDecl *PrevDecl
543    = LookupSingleName(TUScope, ClassName, LookupOrdinaryName);
544  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
545    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
546    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
547  } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
548    // If this is a forward declaration of an interface, warn.
549    if (IDecl->isForwardDecl()) {
550      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
551      IDecl = 0;
552    }
553  } else {
554    // We did not find anything with the name ClassName; try to correct for
555    // typos in the class name.
556    LookupResult R(*this, ClassName, ClassLoc, LookupOrdinaryName);
557    if (CorrectTypo(R, TUScope, 0) &&
558        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
559      // Suggest the (potentially) correct interface name. However, put the
560      // fix-it hint itself in a separate note, since changing the name in
561      // the warning would make the fix-it change semantics.However, don't
562      // provide a code-modification hint or use the typo name for recovery,
563      // because this is just a warning. The program may actually be correct.
564      Diag(ClassLoc, diag::warn_undef_interface_suggest)
565        << ClassName << R.getLookupName();
566      Diag(IDecl->getLocation(), diag::note_previous_decl)
567        << R.getLookupName()
568        << FixItHint::CreateReplacement(ClassLoc,
569                                        R.getLookupName().getAsString());
570      IDecl = 0;
571    } else {
572      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
573    }
574  }
575
576  // Check that super class name is valid class name
577  ObjCInterfaceDecl* SDecl = 0;
578  if (SuperClassname) {
579    // Check if a different kind of symbol declared in this scope.
580    PrevDecl = LookupSingleName(TUScope, SuperClassname, LookupOrdinaryName);
581    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
582      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
583        << SuperClassname;
584      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
585    } else {
586      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
587      if (!SDecl)
588        Diag(SuperClassLoc, diag::err_undef_superclass)
589          << SuperClassname << ClassName;
590      else if (IDecl && IDecl->getSuperClass() != SDecl) {
591        // This implementation and its interface do not have the same
592        // super class.
593        Diag(SuperClassLoc, diag::err_conflicting_super_class)
594          << SDecl->getDeclName();
595        Diag(SDecl->getLocation(), diag::note_previous_definition);
596      }
597    }
598  }
599
600  if (!IDecl) {
601    // Legacy case of @implementation with no corresponding @interface.
602    // Build, chain & install the interface decl into the identifier.
603
604    // FIXME: Do we support attributes on the @implementation? If so we should
605    // copy them over.
606    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
607                                      ClassName, ClassLoc, false, true);
608    IDecl->setSuperClass(SDecl);
609    IDecl->setLocEnd(ClassLoc);
610
611    PushOnScopeChains(IDecl, TUScope);
612  } else {
613    // Mark the interface as being completed, even if it was just as
614    //   @class ....;
615    // declaration; the user cannot reopen it.
616    IDecl->setForwardDecl(false);
617  }
618
619  ObjCImplementationDecl* IMPDecl =
620    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
621                                   IDecl, SDecl);
622
623  if (CheckObjCDeclScope(IMPDecl))
624    return DeclPtrTy::make(IMPDecl);
625
626  // Check that there is no duplicate implementation of this class.
627  if (IDecl->getImplementation()) {
628    // FIXME: Don't leak everything!
629    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
630    Diag(IDecl->getImplementation()->getLocation(),
631         diag::note_previous_definition);
632  } else { // add it to the list.
633    IDecl->setImplementation(IMPDecl);
634    PushOnScopeChains(IMPDecl, TUScope);
635  }
636  return DeclPtrTy::make(IMPDecl);
637}
638
639void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
640                                    ObjCIvarDecl **ivars, unsigned numIvars,
641                                    SourceLocation RBrace) {
642  assert(ImpDecl && "missing implementation decl");
643  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
644  if (!IDecl)
645    return;
646  /// Check case of non-existing @interface decl.
647  /// (legacy objective-c @implementation decl without an @interface decl).
648  /// Add implementations's ivar to the synthesize class's ivar list.
649  if (IDecl->isImplicitInterfaceDecl()) {
650    IDecl->setLocEnd(RBrace);
651    // Add ivar's to class's DeclContext.
652    for (unsigned i = 0, e = numIvars; i != e; ++i) {
653      ivars[i]->setLexicalDeclContext(ImpDecl);
654      IDecl->makeDeclVisibleInContext(ivars[i], false);
655      ImpDecl->addDecl(ivars[i]);
656    }
657
658    return;
659  }
660  // If implementation has empty ivar list, just return.
661  if (numIvars == 0)
662    return;
663
664  assert(ivars && "missing @implementation ivars");
665  if (LangOpts.ObjCNonFragileABI2) {
666    if (ImpDecl->getSuperClass())
667      Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
668    for (unsigned i = 0; i < numIvars; i++) {
669      ObjCIvarDecl* ImplIvar = ivars[i];
670      if (const ObjCIvarDecl *ClsIvar =
671            IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
672        Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
673        Diag(ClsIvar->getLocation(), diag::note_previous_definition);
674        continue;
675      }
676      // Instance ivar to Implementation's DeclContext.
677      ImplIvar->setLexicalDeclContext(ImpDecl);
678      IDecl->makeDeclVisibleInContext(ImplIvar, false);
679      ImpDecl->addDecl(ImplIvar);
680    }
681    return;
682  }
683  // Check interface's Ivar list against those in the implementation.
684  // names and types must match.
685  //
686  unsigned j = 0;
687  ObjCInterfaceDecl::ivar_iterator
688    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
689  for (; numIvars > 0 && IVI != IVE; ++IVI) {
690    ObjCIvarDecl* ImplIvar = ivars[j++];
691    ObjCIvarDecl* ClsIvar = *IVI;
692    assert (ImplIvar && "missing implementation ivar");
693    assert (ClsIvar && "missing class ivar");
694
695    // First, make sure the types match.
696    if (Context.getCanonicalType(ImplIvar->getType()) !=
697        Context.getCanonicalType(ClsIvar->getType())) {
698      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
699        << ImplIvar->getIdentifier()
700        << ImplIvar->getType() << ClsIvar->getType();
701      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
702    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
703      Expr *ImplBitWidth = ImplIvar->getBitWidth();
704      Expr *ClsBitWidth = ClsIvar->getBitWidth();
705      if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
706          ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
707        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
708          << ImplIvar->getIdentifier();
709        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
710      }
711    }
712    // Make sure the names are identical.
713    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
714      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
715        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
716      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
717    }
718    --numIvars;
719  }
720
721  if (numIvars > 0)
722    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
723  else if (IVI != IVE)
724    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
725}
726
727void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
728                               bool &IncompleteImpl, unsigned DiagID) {
729  if (!IncompleteImpl) {
730    Diag(ImpLoc, diag::warn_incomplete_impl);
731    IncompleteImpl = true;
732  }
733  Diag(method->getLocation(), DiagID)
734    << method->getDeclName();
735}
736
737void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
738                                       ObjCMethodDecl *IntfMethodDecl) {
739  if (!Context.typesAreCompatible(IntfMethodDecl->getResultType(),
740                                  ImpMethodDecl->getResultType()) &&
741      !Context.QualifiedIdConformsQualifiedId(IntfMethodDecl->getResultType(),
742                                              ImpMethodDecl->getResultType())) {
743    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_ret_types)
744      << ImpMethodDecl->getDeclName() << IntfMethodDecl->getResultType()
745      << ImpMethodDecl->getResultType();
746    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
747  }
748
749  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
750       IF = IntfMethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
751       IM != EM; ++IM, ++IF) {
752    QualType ParmDeclTy = (*IF)->getType().getUnqualifiedType();
753    QualType ParmImpTy = (*IM)->getType().getUnqualifiedType();
754    if (Context.typesAreCompatible(ParmDeclTy, ParmImpTy) ||
755        Context.QualifiedIdConformsQualifiedId(ParmDeclTy, ParmImpTy))
756      continue;
757
758    Diag((*IM)->getLocation(), diag::warn_conflicting_param_types)
759      << ImpMethodDecl->getDeclName() << (*IF)->getType()
760      << (*IM)->getType();
761    Diag((*IF)->getLocation(), diag::note_previous_definition);
762  }
763}
764
765/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
766/// improve the efficiency of selector lookups and type checking by associating
767/// with each protocol / interface / category the flattened instance tables. If
768/// we used an immutable set to keep the table then it wouldn't add significant
769/// memory cost and it would be handy for lookups.
770
771/// CheckProtocolMethodDefs - This routine checks unimplemented methods
772/// Declared in protocol, and those referenced by it.
773void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
774                                   ObjCProtocolDecl *PDecl,
775                                   bool& IncompleteImpl,
776                                   const llvm::DenseSet<Selector> &InsMap,
777                                   const llvm::DenseSet<Selector> &ClsMap,
778                                   ObjCContainerDecl *CDecl) {
779  ObjCInterfaceDecl *IDecl;
780  if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
781    IDecl = C->getClassInterface();
782  else
783    IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
784  assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
785
786  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
787  ObjCInterfaceDecl *NSIDecl = 0;
788  if (getLangOptions().NeXTRuntime) {
789    // check to see if class implements forwardInvocation method and objects
790    // of this class are derived from 'NSProxy' so that to forward requests
791    // from one object to another.
792    // Under such conditions, which means that every method possible is
793    // implemented in the class, we should not issue "Method definition not
794    // found" warnings.
795    // FIXME: Use a general GetUnarySelector method for this.
796    IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
797    Selector fISelector = Context.Selectors.getSelector(1, &II);
798    if (InsMap.count(fISelector))
799      // Is IDecl derived from 'NSProxy'? If so, no instance methods
800      // need be implemented in the implementation.
801      NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
802  }
803
804  // If a method lookup fails locally we still need to look and see if
805  // the method was implemented by a base class or an inherited
806  // protocol. This lookup is slow, but occurs rarely in correct code
807  // and otherwise would terminate in a warning.
808
809  // check unimplemented instance methods.
810  if (!NSIDecl)
811    for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
812         E = PDecl->instmeth_end(); I != E; ++I) {
813      ObjCMethodDecl *method = *I;
814      if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
815          !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
816          (!Super ||
817           !Super->lookupInstanceMethod(method->getSelector()))) {
818            // Ugly, but necessary. Method declared in protcol might have
819            // have been synthesized due to a property declared in the class which
820            // uses the protocol.
821            ObjCMethodDecl *MethodInClass =
822            IDecl->lookupInstanceMethod(method->getSelector());
823            if (!MethodInClass || !MethodInClass->isSynthesized()) {
824              unsigned DIAG = diag::warn_unimplemented_protocol_method;
825              if (Diags.getDiagnosticLevel(DIAG) != Diagnostic::Ignored) {
826                WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
827                Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
828                  << PDecl->getDeclName();
829              }
830            }
831          }
832    }
833  // check unimplemented class methods
834  for (ObjCProtocolDecl::classmeth_iterator
835         I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
836       I != E; ++I) {
837    ObjCMethodDecl *method = *I;
838    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
839        !ClsMap.count(method->getSelector()) &&
840        (!Super || !Super->lookupClassMethod(method->getSelector()))) {
841      unsigned DIAG = diag::warn_unimplemented_protocol_method;
842      if (Diags.getDiagnosticLevel(DIAG) != Diagnostic::Ignored) {
843        WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
844        Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
845          PDecl->getDeclName();
846      }
847    }
848  }
849  // Check on this protocols's referenced protocols, recursively.
850  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
851       E = PDecl->protocol_end(); PI != E; ++PI)
852    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
853}
854
855/// MatchAllMethodDeclarations - Check methods declaraed in interface or
856/// or protocol against those declared in their implementations.
857///
858void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
859                                      const llvm::DenseSet<Selector> &ClsMap,
860                                      llvm::DenseSet<Selector> &InsMapSeen,
861                                      llvm::DenseSet<Selector> &ClsMapSeen,
862                                      ObjCImplDecl* IMPDecl,
863                                      ObjCContainerDecl* CDecl,
864                                      bool &IncompleteImpl,
865                                      bool ImmediateClass) {
866  // Check and see if instance methods in class interface have been
867  // implemented in the implementation class. If so, their types match.
868  for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
869       E = CDecl->instmeth_end(); I != E; ++I) {
870    if (InsMapSeen.count((*I)->getSelector()))
871        continue;
872    InsMapSeen.insert((*I)->getSelector());
873    if (!(*I)->isSynthesized() &&
874        !InsMap.count((*I)->getSelector())) {
875      if (ImmediateClass)
876        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
877                            diag::note_undef_method_impl);
878      continue;
879    } else {
880      ObjCMethodDecl *ImpMethodDecl =
881      IMPDecl->getInstanceMethod((*I)->getSelector());
882      ObjCMethodDecl *IntfMethodDecl =
883      CDecl->getInstanceMethod((*I)->getSelector());
884      assert(IntfMethodDecl &&
885             "IntfMethodDecl is null in ImplMethodsVsClassMethods");
886      // ImpMethodDecl may be null as in a @dynamic property.
887      if (ImpMethodDecl)
888        WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
889    }
890  }
891
892  // Check and see if class methods in class interface have been
893  // implemented in the implementation class. If so, their types match.
894   for (ObjCInterfaceDecl::classmeth_iterator
895       I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
896     if (ClsMapSeen.count((*I)->getSelector()))
897       continue;
898     ClsMapSeen.insert((*I)->getSelector());
899    if (!ClsMap.count((*I)->getSelector())) {
900      if (ImmediateClass)
901        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
902                            diag::note_undef_method_impl);
903    } else {
904      ObjCMethodDecl *ImpMethodDecl =
905        IMPDecl->getClassMethod((*I)->getSelector());
906      ObjCMethodDecl *IntfMethodDecl =
907        CDecl->getClassMethod((*I)->getSelector());
908      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
909    }
910  }
911  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
912    // Check for any implementation of a methods declared in protocol.
913    for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
914         E = I->protocol_end(); PI != E; ++PI)
915      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
916                                 IMPDecl,
917                                 (*PI), IncompleteImpl, false);
918    if (I->getSuperClass())
919      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
920                                 IMPDecl,
921                                 I->getSuperClass(), IncompleteImpl, false);
922  }
923}
924
925void Sema::ImplMethodsVsClassMethods(ObjCImplDecl* IMPDecl,
926                                     ObjCContainerDecl* CDecl,
927                                     bool IncompleteImpl) {
928  llvm::DenseSet<Selector> InsMap;
929  // Check and see if instance methods in class interface have been
930  // implemented in the implementation class.
931  for (ObjCImplementationDecl::instmeth_iterator
932         I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
933    InsMap.insert((*I)->getSelector());
934
935  // Check and see if properties declared in the interface have either 1)
936  // an implementation or 2) there is a @synthesize/@dynamic implementation
937  // of the property in the @implementation.
938  if (isa<ObjCInterfaceDecl>(CDecl))
939    DiagnoseUnimplementedProperties(IMPDecl, CDecl, InsMap);
940
941  llvm::DenseSet<Selector> ClsMap;
942  for (ObjCImplementationDecl::classmeth_iterator
943       I = IMPDecl->classmeth_begin(),
944       E = IMPDecl->classmeth_end(); I != E; ++I)
945    ClsMap.insert((*I)->getSelector());
946
947  // Check for type conflict of methods declared in a class/protocol and
948  // its implementation; if any.
949  llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
950  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
951                             IMPDecl, CDecl,
952                             IncompleteImpl, true);
953
954  // Check the protocol list for unimplemented methods in the @implementation
955  // class.
956  // Check and see if class methods in class interface have been
957  // implemented in the implementation class.
958
959  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
960    for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
961         E = I->protocol_end(); PI != E; ++PI)
962      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
963                              InsMap, ClsMap, I);
964    // Check class extensions (unnamed categories)
965    for (ObjCCategoryDecl *Categories = I->getCategoryList();
966         Categories; Categories = Categories->getNextClassCategory()) {
967      if (Categories->IsClassExtension()) {
968        ImplMethodsVsClassMethods(IMPDecl, Categories, IncompleteImpl);
969        break;
970      }
971    }
972  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
973    // For extended class, unimplemented methods in its protocols will
974    // be reported in the primary class.
975    if (!C->IsClassExtension()) {
976      for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
977           E = C->protocol_end(); PI != E; ++PI)
978        CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
979                                InsMap, ClsMap, CDecl);
980      // Report unimplemented properties in the category as well.
981      // When reporting on missing setter/getters, do not report when
982      // setter/getter is implemented in category's primary class
983      // implementation.
984      if (ObjCInterfaceDecl *ID = C->getClassInterface())
985        if (ObjCImplDecl *IMP = ID->getImplementation()) {
986          for (ObjCImplementationDecl::instmeth_iterator
987               I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
988            InsMap.insert((*I)->getSelector());
989        }
990      DiagnoseUnimplementedProperties(IMPDecl, CDecl, InsMap);
991    }
992  } else
993    assert(false && "invalid ObjCContainerDecl type.");
994}
995
996/// ActOnForwardClassDeclaration -
997Action::DeclPtrTy
998Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
999                                   IdentifierInfo **IdentList,
1000                                   SourceLocation *IdentLocs,
1001                                   unsigned NumElts) {
1002  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1003
1004  for (unsigned i = 0; i != NumElts; ++i) {
1005    // Check for another declaration kind with the same name.
1006    NamedDecl *PrevDecl
1007      = LookupSingleName(TUScope, IdentList[i], LookupOrdinaryName);
1008    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1009      // Maybe we will complain about the shadowed template parameter.
1010      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1011      // Just pretend that we didn't see the previous declaration.
1012      PrevDecl = 0;
1013    }
1014
1015    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1016      // GCC apparently allows the following idiom:
1017      //
1018      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1019      // @class XCElementToggler;
1020      //
1021      // FIXME: Make an extension?
1022      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
1023      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
1024        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1025        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1026      } else if (TDD) {
1027        // a forward class declaration matching a typedef name of a class refers
1028        // to the underlying class.
1029        if (ObjCInterfaceType * OI =
1030              dyn_cast<ObjCInterfaceType>(TDD->getUnderlyingType()))
1031          PrevDecl = OI->getDecl();
1032      }
1033    }
1034    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1035    if (!IDecl) {  // Not already seen?  Make a forward decl.
1036      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1037                                        IdentList[i], IdentLocs[i], true);
1038
1039      // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1040      // the current DeclContext.  This prevents clients that walk DeclContext
1041      // from seeing the imaginary ObjCInterfaceDecl until it is actually
1042      // declared later (if at all).  We also take care to explicitly make
1043      // sure this declaration is visible for name lookup.
1044      PushOnScopeChains(IDecl, TUScope, false);
1045      CurContext->makeDeclVisibleInContext(IDecl, true);
1046    }
1047
1048    Interfaces.push_back(IDecl);
1049  }
1050
1051  assert(Interfaces.size() == NumElts);
1052  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1053                                               Interfaces.data(), IdentLocs,
1054                                               Interfaces.size());
1055  CurContext->addDecl(CDecl);
1056  CheckObjCDeclScope(CDecl);
1057  return DeclPtrTy::make(CDecl);
1058}
1059
1060
1061/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1062/// returns true, or false, accordingly.
1063/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1064bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1065                                      const ObjCMethodDecl *PrevMethod,
1066                                      bool matchBasedOnSizeAndAlignment) {
1067  QualType T1 = Context.getCanonicalType(Method->getResultType());
1068  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1069
1070  if (T1 != T2) {
1071    // The result types are different.
1072    if (!matchBasedOnSizeAndAlignment)
1073      return false;
1074    // Incomplete types don't have a size and alignment.
1075    if (T1->isIncompleteType() || T2->isIncompleteType())
1076      return false;
1077    // Check is based on size and alignment.
1078    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1079      return false;
1080  }
1081
1082  ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1083       E = Method->param_end();
1084  ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1085
1086  for (; ParamI != E; ++ParamI, ++PrevI) {
1087    assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1088    T1 = Context.getCanonicalType((*ParamI)->getType());
1089    T2 = Context.getCanonicalType((*PrevI)->getType());
1090    if (T1 != T2) {
1091      // The result types are different.
1092      if (!matchBasedOnSizeAndAlignment)
1093        return false;
1094      // Incomplete types don't have a size and alignment.
1095      if (T1->isIncompleteType() || T2->isIncompleteType())
1096        return false;
1097      // Check is based on size and alignment.
1098      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1099        return false;
1100    }
1101  }
1102  return true;
1103}
1104
1105/// \brief Read the contents of the instance and factory method pools
1106/// for a given selector from external storage.
1107///
1108/// This routine should only be called once, when neither the instance
1109/// nor the factory method pool has an entry for this selector.
1110Sema::MethodPool::iterator Sema::ReadMethodPool(Selector Sel,
1111                                                bool isInstance) {
1112  assert(ExternalSource && "We need an external AST source");
1113  assert(InstanceMethodPool.find(Sel) == InstanceMethodPool.end() &&
1114         "Selector data already loaded into the instance method pool");
1115  assert(FactoryMethodPool.find(Sel) == FactoryMethodPool.end() &&
1116         "Selector data already loaded into the factory method pool");
1117
1118  // Read the method list from the external source.
1119  std::pair<ObjCMethodList, ObjCMethodList> Methods
1120    = ExternalSource->ReadMethodPool(Sel);
1121
1122  if (isInstance) {
1123    if (Methods.second.Method)
1124      FactoryMethodPool[Sel] = Methods.second;
1125    return InstanceMethodPool.insert(std::make_pair(Sel, Methods.first)).first;
1126  }
1127
1128  if (Methods.first.Method)
1129    InstanceMethodPool[Sel] = Methods.first;
1130
1131  return FactoryMethodPool.insert(std::make_pair(Sel, Methods.second)).first;
1132}
1133
1134void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
1135  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1136    = InstanceMethodPool.find(Method->getSelector());
1137  if (Pos == InstanceMethodPool.end()) {
1138    if (ExternalSource && !FactoryMethodPool.count(Method->getSelector()))
1139      Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/true);
1140    else
1141      Pos = InstanceMethodPool.insert(std::make_pair(Method->getSelector(),
1142                                                     ObjCMethodList())).first;
1143  }
1144
1145  ObjCMethodList &Entry = Pos->second;
1146  if (Entry.Method == 0) {
1147    // Haven't seen a method with this selector name yet - add it.
1148    Entry.Method = Method;
1149    Entry.Next = 0;
1150    return;
1151  }
1152
1153  // We've seen a method with this name, see if we have already seen this type
1154  // signature.
1155  for (ObjCMethodList *List = &Entry; List; List = List->Next)
1156    if (MatchTwoMethodDeclarations(Method, List->Method))
1157      return;
1158
1159  // We have a new signature for an existing method - add it.
1160  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1161  ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1162  Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1163}
1164
1165// FIXME: Finish implementing -Wno-strict-selector-match.
1166ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
1167                                                       SourceRange R,
1168                                                       bool warn) {
1169  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1170    = InstanceMethodPool.find(Sel);
1171  if (Pos == InstanceMethodPool.end()) {
1172    if (ExternalSource && !FactoryMethodPool.count(Sel))
1173      Pos = ReadMethodPool(Sel, /*isInstance=*/true);
1174    else
1175      return 0;
1176  }
1177
1178  ObjCMethodList &MethList = Pos->second;
1179  bool issueWarning = false;
1180
1181  if (MethList.Method && MethList.Next) {
1182    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1183      // This checks if the methods differ by size & alignment.
1184      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1185        issueWarning = warn;
1186  }
1187  if (issueWarning && (MethList.Method && MethList.Next)) {
1188    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1189    Diag(MethList.Method->getLocStart(), diag::note_using)
1190      << MethList.Method->getSourceRange();
1191    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1192      Diag(Next->Method->getLocStart(), diag::note_also_found)
1193        << Next->Method->getSourceRange();
1194  }
1195  return MethList.Method;
1196}
1197
1198void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
1199  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1200    = FactoryMethodPool.find(Method->getSelector());
1201  if (Pos == FactoryMethodPool.end()) {
1202    if (ExternalSource && !InstanceMethodPool.count(Method->getSelector()))
1203      Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/false);
1204    else
1205      Pos = FactoryMethodPool.insert(std::make_pair(Method->getSelector(),
1206                                                    ObjCMethodList())).first;
1207  }
1208
1209  ObjCMethodList &FirstMethod = Pos->second;
1210  if (!FirstMethod.Method) {
1211    // Haven't seen a method with this selector name yet - add it.
1212    FirstMethod.Method = Method;
1213    FirstMethod.Next = 0;
1214  } else {
1215    // We've seen a method with this name, now check the type signature(s).
1216    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1217
1218    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1219         Next = Next->Next)
1220      match = MatchTwoMethodDeclarations(Method, Next->Method);
1221
1222    if (!match) {
1223      // We have a new signature for an existing method - add it.
1224      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1225      ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1226      ObjCMethodList *OMI = new (Mem) ObjCMethodList(Method, FirstMethod.Next);
1227      FirstMethod.Next = OMI;
1228    }
1229  }
1230}
1231
1232ObjCMethodDecl *Sema::LookupFactoryMethodInGlobalPool(Selector Sel,
1233                                                      SourceRange R) {
1234  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1235    = FactoryMethodPool.find(Sel);
1236  if (Pos == FactoryMethodPool.end()) {
1237    if (ExternalSource && !InstanceMethodPool.count(Sel))
1238      Pos = ReadMethodPool(Sel, /*isInstance=*/false);
1239    else
1240      return 0;
1241  }
1242
1243  ObjCMethodList &MethList = Pos->second;
1244  bool issueWarning = false;
1245
1246  if (MethList.Method && MethList.Next) {
1247    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1248      // This checks if the methods differ by size & alignment.
1249      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1250        issueWarning = true;
1251  }
1252  if (issueWarning && (MethList.Method && MethList.Next)) {
1253    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1254    Diag(MethList.Method->getLocStart(), diag::note_using)
1255      << MethList.Method->getSourceRange();
1256    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1257      Diag(Next->Method->getLocStart(), diag::note_also_found)
1258        << Next->Method->getSourceRange();
1259  }
1260  return MethList.Method;
1261}
1262
1263/// CompareMethodParamsInBaseAndSuper - This routine compares methods with
1264/// identical selector names in current and its super classes and issues
1265/// a warning if any of their argument types are incompatible.
1266void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
1267                                             ObjCMethodDecl *Method,
1268                                             bool IsInstance)  {
1269  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
1270  if (ID == 0) return;
1271
1272  while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
1273    ObjCMethodDecl *SuperMethodDecl =
1274        SD->lookupMethod(Method->getSelector(), IsInstance);
1275    if (SuperMethodDecl == 0) {
1276      ID = SD;
1277      continue;
1278    }
1279    ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1280      E = Method->param_end();
1281    ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
1282    for (; ParamI != E; ++ParamI, ++PrevI) {
1283      // Number of parameters are the same and is guaranteed by selector match.
1284      assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
1285      QualType T1 = Context.getCanonicalType((*ParamI)->getType());
1286      QualType T2 = Context.getCanonicalType((*PrevI)->getType());
1287      // If type of arguement of method in this class does not match its
1288      // respective argument type in the super class method, issue warning;
1289      if (!Context.typesAreCompatible(T1, T2)) {
1290        Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
1291          << T1 << T2;
1292        Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
1293        return;
1294      }
1295    }
1296    ID = SD;
1297  }
1298}
1299
1300/// DiagnoseDuplicateIvars -
1301/// Check for duplicate ivars in the entire class at the start of
1302/// @implementation. This becomes necesssary because class extension can
1303/// add ivars to a class in random order which will not be known until
1304/// class's @implementation is seen.
1305void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
1306                                  ObjCInterfaceDecl *SID) {
1307  for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
1308       IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
1309    ObjCIvarDecl* Ivar = (*IVI);
1310    if (Ivar->isInvalidDecl())
1311      continue;
1312    if (IdentifierInfo *II = Ivar->getIdentifier()) {
1313      ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
1314      if (prevIvar) {
1315        Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
1316        Diag(prevIvar->getLocation(), diag::note_previous_declaration);
1317        Ivar->setInvalidDecl();
1318      }
1319    }
1320  }
1321}
1322
1323// Note: For class/category implemenations, allMethods/allProperties is
1324// always null.
1325void Sema::ActOnAtEnd(SourceRange AtEnd,
1326                      DeclPtrTy classDecl,
1327                      DeclPtrTy *allMethods, unsigned allNum,
1328                      DeclPtrTy *allProperties, unsigned pNum,
1329                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1330  Decl *ClassDecl = classDecl.getAs<Decl>();
1331
1332  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1333  // always passing in a decl. If the decl has an error, isInvalidDecl()
1334  // should be true.
1335  if (!ClassDecl)
1336    return;
1337
1338  bool isInterfaceDeclKind =
1339        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1340         || isa<ObjCProtocolDecl>(ClassDecl);
1341  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1342
1343  if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
1344    // FIXME: This is wrong.  We shouldn't be pretending that there is
1345    //  an '@end' in the declaration.
1346    SourceLocation L = ClassDecl->getLocation();
1347    AtEnd.setBegin(L);
1348    AtEnd.setEnd(L);
1349    Diag(L, diag::warn_missing_atend);
1350  }
1351
1352  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1353
1354  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1355  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1356  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1357
1358  for (unsigned i = 0; i < allNum; i++ ) {
1359    ObjCMethodDecl *Method =
1360      cast_or_null<ObjCMethodDecl>(allMethods[i].getAs<Decl>());
1361
1362    if (!Method) continue;  // Already issued a diagnostic.
1363    if (Method->isInstanceMethod()) {
1364      /// Check for instance method of the same name with incompatible types
1365      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1366      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1367                              : false;
1368      if ((isInterfaceDeclKind && PrevMethod && !match)
1369          || (checkIdenticalMethods && match)) {
1370          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1371            << Method->getDeclName();
1372          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1373      } else {
1374        DC->addDecl(Method);
1375        InsMap[Method->getSelector()] = Method;
1376        /// The following allows us to typecheck messages to "id".
1377        AddInstanceMethodToGlobalPool(Method);
1378        // verify that the instance method conforms to the same definition of
1379        // parent methods if it shadows one.
1380        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
1381      }
1382    } else {
1383      /// Check for class method of the same name with incompatible types
1384      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1385      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1386                              : false;
1387      if ((isInterfaceDeclKind && PrevMethod && !match)
1388          || (checkIdenticalMethods && match)) {
1389        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1390          << Method->getDeclName();
1391        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1392      } else {
1393        DC->addDecl(Method);
1394        ClsMap[Method->getSelector()] = Method;
1395        /// The following allows us to typecheck messages to "Class".
1396        AddFactoryMethodToGlobalPool(Method);
1397        // verify that the class method conforms to the same definition of
1398        // parent methods if it shadows one.
1399        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
1400      }
1401    }
1402  }
1403  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1404    // Compares properties declared in this class to those of its
1405    // super class.
1406    ComparePropertiesInBaseAndSuper(I);
1407    CompareProperties(I, DeclPtrTy::make(I));
1408  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1409    // Categories are used to extend the class by declaring new methods.
1410    // By the same token, they are also used to add new properties. No
1411    // need to compare the added property to those in the class.
1412
1413    // Compare protocol properties with those in category
1414    CompareProperties(C, DeclPtrTy::make(C));
1415    if (C->IsClassExtension())
1416      DiagnoseClassExtensionDupMethods(C, C->getClassInterface());
1417  }
1418  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1419    if (CDecl->getIdentifier())
1420      // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1421      // user-defined setter/getter. It also synthesizes setter/getter methods
1422      // and adds them to the DeclContext and global method pools.
1423      for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1424                                            E = CDecl->prop_end();
1425           I != E; ++I)
1426        ProcessPropertyDecl(*I, CDecl);
1427    CDecl->setAtEndRange(AtEnd);
1428  }
1429  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1430    IC->setAtEndRange(AtEnd);
1431    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
1432      ImplMethodsVsClassMethods(IC, IDecl);
1433      AtomicPropertySetterGetterRules(IC, IDecl);
1434      if (LangOpts.ObjCNonFragileABI2)
1435        while (IDecl->getSuperClass()) {
1436          DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
1437          IDecl = IDecl->getSuperClass();
1438        }
1439    }
1440  } else if (ObjCCategoryImplDecl* CatImplClass =
1441                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1442    CatImplClass->setAtEndRange(AtEnd);
1443
1444    // Find category interface decl and then check that all methods declared
1445    // in this interface are implemented in the category @implementation.
1446    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1447      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1448           Categories; Categories = Categories->getNextClassCategory()) {
1449        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1450          ImplMethodsVsClassMethods(CatImplClass, Categories);
1451          break;
1452        }
1453      }
1454    }
1455  }
1456  if (isInterfaceDeclKind) {
1457    // Reject invalid vardecls.
1458    for (unsigned i = 0; i != tuvNum; i++) {
1459      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1460      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1461        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1462          if (!VDecl->hasExternalStorage())
1463            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1464        }
1465    }
1466  }
1467}
1468
1469
1470/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1471/// objective-c's type qualifier from the parser version of the same info.
1472static Decl::ObjCDeclQualifier
1473CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1474  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1475  if (PQTVal & ObjCDeclSpec::DQ_In)
1476    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1477  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1478    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1479  if (PQTVal & ObjCDeclSpec::DQ_Out)
1480    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1481  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1482    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1483  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1484    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1485  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1486    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1487
1488  return ret;
1489}
1490
1491Sema::DeclPtrTy Sema::ActOnMethodDeclaration(
1492    SourceLocation MethodLoc, SourceLocation EndLoc,
1493    tok::TokenKind MethodType, DeclPtrTy classDecl,
1494    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1495    Selector Sel,
1496    // optional arguments. The number of types/arguments is obtained
1497    // from the Sel.getNumArgs().
1498    ObjCArgInfo *ArgInfo,
1499    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
1500    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1501    bool isVariadic) {
1502  Decl *ClassDecl = classDecl.getAs<Decl>();
1503
1504  // Make sure we can establish a context for the method.
1505  if (!ClassDecl) {
1506    Diag(MethodLoc, diag::error_missing_method_context);
1507    getLabelMap().clear();
1508    return DeclPtrTy();
1509  }
1510  QualType resultDeclType;
1511
1512  TypeSourceInfo *ResultTInfo = 0;
1513  if (ReturnType) {
1514    resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
1515
1516    // Methods cannot return interface types. All ObjC objects are
1517    // passed by reference.
1518    if (resultDeclType->isObjCInterfaceType()) {
1519      Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1520        << 0 << resultDeclType;
1521      return DeclPtrTy();
1522    }
1523  } else // get the type for "id".
1524    resultDeclType = Context.getObjCIdType();
1525
1526  ObjCMethodDecl* ObjCMethod =
1527    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1528                           ResultTInfo,
1529                           cast<DeclContext>(ClassDecl),
1530                           MethodType == tok::minus, isVariadic,
1531                           false,
1532                           MethodDeclKind == tok::objc_optional ?
1533                           ObjCMethodDecl::Optional :
1534                           ObjCMethodDecl::Required);
1535
1536  llvm::SmallVector<ParmVarDecl*, 16> Params;
1537
1538  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1539    QualType ArgType;
1540    TypeSourceInfo *DI;
1541
1542    if (ArgInfo[i].Type == 0) {
1543      ArgType = Context.getObjCIdType();
1544      DI = 0;
1545    } else {
1546      ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
1547      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1548      ArgType = adjustParameterType(ArgType);
1549    }
1550
1551    ParmVarDecl* Param
1552      = ParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc,
1553                            ArgInfo[i].Name, ArgType, DI,
1554                            VarDecl::None, 0);
1555
1556    if (ArgType->isObjCInterfaceType()) {
1557      Diag(ArgInfo[i].NameLoc,
1558           diag::err_object_cannot_be_passed_returned_by_value)
1559        << 1 << ArgType;
1560      Param->setInvalidDecl();
1561    }
1562
1563    Param->setObjCDeclQualifier(
1564      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
1565
1566    // Apply the attributes to the parameter.
1567    ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
1568
1569    Params.push_back(Param);
1570  }
1571
1572  for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
1573    ParmVarDecl *Param = CParamInfo[i].Param.getAs<ParmVarDecl>();
1574    QualType ArgType = Param->getType();
1575    if (ArgType.isNull())
1576      ArgType = Context.getObjCIdType();
1577    else
1578      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1579      ArgType = adjustParameterType(ArgType);
1580    if (ArgType->isObjCInterfaceType()) {
1581      Diag(Param->getLocation(),
1582           diag::err_object_cannot_be_passed_returned_by_value)
1583      << 1 << ArgType;
1584      Param->setInvalidDecl();
1585    }
1586    Param->setDeclContext(ObjCMethod);
1587    IdResolver.RemoveDecl(Param);
1588    Params.push_back(Param);
1589  }
1590
1591  ObjCMethod->setMethodParams(Context, Params.data(), Params.size(),
1592                              Sel.getNumArgs());
1593  ObjCMethod->setObjCDeclQualifier(
1594    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1595  const ObjCMethodDecl *PrevMethod = 0;
1596
1597  if (AttrList)
1598    ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
1599
1600  const ObjCMethodDecl *InterfaceMD = 0;
1601
1602  // For implementations (which can be very "coarse grain"), we add the
1603  // method now. This allows the AST to implement lookup methods that work
1604  // incrementally (without waiting until we parse the @end). It also allows
1605  // us to flag multiple declaration errors as they occur.
1606  if (ObjCImplementationDecl *ImpDecl =
1607        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1608    if (MethodType == tok::minus) {
1609      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1610      ImpDecl->addInstanceMethod(ObjCMethod);
1611    } else {
1612      PrevMethod = ImpDecl->getClassMethod(Sel);
1613      ImpDecl->addClassMethod(ObjCMethod);
1614    }
1615    InterfaceMD = ImpDecl->getClassInterface()->getMethod(Sel,
1616                                                   MethodType == tok::minus);
1617    if (AttrList)
1618      Diag(EndLoc, diag::warn_attribute_method_def);
1619  } else if (ObjCCategoryImplDecl *CatImpDecl =
1620             dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1621    if (MethodType == tok::minus) {
1622      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1623      CatImpDecl->addInstanceMethod(ObjCMethod);
1624    } else {
1625      PrevMethod = CatImpDecl->getClassMethod(Sel);
1626      CatImpDecl->addClassMethod(ObjCMethod);
1627    }
1628    if (AttrList)
1629      Diag(EndLoc, diag::warn_attribute_method_def);
1630  }
1631  if (PrevMethod) {
1632    // You can never have two method definitions with the same name.
1633    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1634      << ObjCMethod->getDeclName();
1635    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1636  }
1637
1638  // If the interface declared this method, and it was deprecated there,
1639  // mark it deprecated here.
1640  if (InterfaceMD && InterfaceMD->hasAttr<DeprecatedAttr>())
1641    ObjCMethod->addAttr(::new (Context) DeprecatedAttr());
1642
1643  return DeclPtrTy::make(ObjCMethod);
1644}
1645
1646bool Sema::CheckObjCDeclScope(Decl *D) {
1647  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1648    return false;
1649
1650  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1651  D->setInvalidDecl();
1652
1653  return true;
1654}
1655
1656/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1657/// instance variables of ClassName into Decls.
1658void Sema::ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart,
1659                     IdentifierInfo *ClassName,
1660                     llvm::SmallVectorImpl<DeclPtrTy> &Decls) {
1661  // Check that ClassName is a valid class
1662  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1663  if (!Class) {
1664    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1665    return;
1666  }
1667  if (LangOpts.ObjCNonFragileABI) {
1668    Diag(DeclStart, diag::err_atdef_nonfragile_interface);
1669    return;
1670  }
1671
1672  // Collect the instance variables
1673  llvm::SmallVector<FieldDecl*, 32> RecFields;
1674  Context.CollectObjCIvars(Class, RecFields);
1675  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1676  for (unsigned i = 0; i < RecFields.size(); i++) {
1677    FieldDecl* ID = RecFields[i];
1678    RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>());
1679    Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, ID->getLocation(),
1680                                           ID->getIdentifier(), ID->getType(),
1681                                           ID->getBitWidth());
1682    Decls.push_back(Sema::DeclPtrTy::make(FD));
1683  }
1684
1685  // Introduce all of these fields into the appropriate scope.
1686  for (llvm::SmallVectorImpl<DeclPtrTy>::iterator D = Decls.begin();
1687       D != Decls.end(); ++D) {
1688    FieldDecl *FD = cast<FieldDecl>(D->getAs<Decl>());
1689    if (getLangOptions().CPlusPlus)
1690      PushOnScopeChains(cast<FieldDecl>(FD), S);
1691    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>()))
1692      Record->addDecl(FD);
1693  }
1694}
1695
1696