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