SemaDeclObjC.cpp revision 210299
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->isObjCObjectType()) {
146            if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
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->isObjCObjectType()) {
214      if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
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;
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 && IDecl->getImplementation()) {
433    Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
434    Diag(IDecl->getImplementation()->getLocation(),
435          diag::note_implementation_declared);
436  }
437
438  CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
439                                   ClassLoc, CategoryLoc, CategoryName);
440  // FIXME: PushOnScopeChains?
441  CurContext->addDecl(CDecl);
442
443  CDecl->setClassInterface(IDecl);
444  // Insert class extension to the list of class's categories.
445  if (!CategoryName)
446    CDecl->insertNextClassCategory();
447
448  // If the interface is deprecated, warn about it.
449  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
450
451  if (CategoryName) {
452    /// Check for duplicate interface declaration for this category
453    ObjCCategoryDecl *CDeclChain;
454    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
455         CDeclChain = CDeclChain->getNextClassCategory()) {
456      if (CDeclChain->getIdentifier() == CategoryName) {
457        // Class extensions can be declared multiple times.
458        Diag(CategoryLoc, diag::warn_dup_category_def)
459          << ClassName << CategoryName;
460        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
461        break;
462      }
463    }
464    if (!CDeclChain)
465      CDecl->insertNextClassCategory();
466  }
467
468  if (NumProtoRefs) {
469    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
470                           ProtoLocs, Context);
471    // Protocols in the class extension belong to the class.
472    if (CDecl->IsClassExtension())
473     IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
474                                            NumProtoRefs, ProtoLocs,
475                                            Context);
476  }
477
478  CheckObjCDeclScope(CDecl);
479  return DeclPtrTy::make(CDecl);
480}
481
482/// ActOnStartCategoryImplementation - Perform semantic checks on the
483/// category implementation declaration and build an ObjCCategoryImplDecl
484/// object.
485Sema::DeclPtrTy Sema::ActOnStartCategoryImplementation(
486                      SourceLocation AtCatImplLoc,
487                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
488                      IdentifierInfo *CatName, SourceLocation CatLoc) {
489  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
490  ObjCCategoryDecl *CatIDecl = 0;
491  if (IDecl) {
492    CatIDecl = IDecl->FindCategoryDeclaration(CatName);
493    if (!CatIDecl) {
494      // Category @implementation with no corresponding @interface.
495      // Create and install one.
496      CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
497                                          SourceLocation(), SourceLocation(),
498                                          CatName);
499      CatIDecl->setClassInterface(IDecl);
500      CatIDecl->insertNextClassCategory();
501    }
502  }
503
504  ObjCCategoryImplDecl *CDecl =
505    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
506                                 IDecl);
507  /// Check that class of this category is already completely declared.
508  if (!IDecl || IDecl->isForwardDecl())
509    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
510
511  // FIXME: PushOnScopeChains?
512  CurContext->addDecl(CDecl);
513
514  /// Check that CatName, category name, is not used in another implementation.
515  if (CatIDecl) {
516    if (CatIDecl->getImplementation()) {
517      Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
518        << CatName;
519      Diag(CatIDecl->getImplementation()->getLocation(),
520           diag::note_previous_definition);
521    } else
522      CatIDecl->setImplementation(CDecl);
523  }
524
525  CheckObjCDeclScope(CDecl);
526  return DeclPtrTy::make(CDecl);
527}
528
529Sema::DeclPtrTy Sema::ActOnStartClassImplementation(
530                      SourceLocation AtClassImplLoc,
531                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
532                      IdentifierInfo *SuperClassname,
533                      SourceLocation SuperClassLoc) {
534  ObjCInterfaceDecl* IDecl = 0;
535  // Check for another declaration kind with the same name.
536  NamedDecl *PrevDecl
537    = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
538                       ForRedeclaration);
539  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
540    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
541    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
542  } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
543    // If this is a forward declaration of an interface, warn.
544    if (IDecl->isForwardDecl()) {
545      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
546      IDecl = 0;
547    }
548  } else {
549    // We did not find anything with the name ClassName; try to correct for
550    // typos in the class name.
551    LookupResult R(*this, ClassName, ClassLoc, LookupOrdinaryName);
552    if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
553        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
554      // Suggest the (potentially) correct interface name. However, put the
555      // fix-it hint itself in a separate note, since changing the name in
556      // the warning would make the fix-it change semantics.However, don't
557      // provide a code-modification hint or use the typo name for recovery,
558      // because this is just a warning. The program may actually be correct.
559      Diag(ClassLoc, diag::warn_undef_interface_suggest)
560        << ClassName << R.getLookupName();
561      Diag(IDecl->getLocation(), diag::note_previous_decl)
562        << R.getLookupName()
563        << FixItHint::CreateReplacement(ClassLoc,
564                                        R.getLookupName().getAsString());
565      IDecl = 0;
566    } else {
567      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
568    }
569  }
570
571  // Check that super class name is valid class name
572  ObjCInterfaceDecl* SDecl = 0;
573  if (SuperClassname) {
574    // Check if a different kind of symbol declared in this scope.
575    PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
576                                LookupOrdinaryName);
577    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
578      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
579        << SuperClassname;
580      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
581    } else {
582      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
583      if (!SDecl)
584        Diag(SuperClassLoc, diag::err_undef_superclass)
585          << SuperClassname << ClassName;
586      else if (IDecl && IDecl->getSuperClass() != SDecl) {
587        // This implementation and its interface do not have the same
588        // super class.
589        Diag(SuperClassLoc, diag::err_conflicting_super_class)
590          << SDecl->getDeclName();
591        Diag(SDecl->getLocation(), diag::note_previous_definition);
592      }
593    }
594  }
595
596  if (!IDecl) {
597    // Legacy case of @implementation with no corresponding @interface.
598    // Build, chain & install the interface decl into the identifier.
599
600    // FIXME: Do we support attributes on the @implementation? If so we should
601    // copy them over.
602    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
603                                      ClassName, ClassLoc, false, true);
604    IDecl->setSuperClass(SDecl);
605    IDecl->setLocEnd(ClassLoc);
606
607    PushOnScopeChains(IDecl, TUScope);
608  } else {
609    // Mark the interface as being completed, even if it was just as
610    //   @class ....;
611    // declaration; the user cannot reopen it.
612    IDecl->setForwardDecl(false);
613  }
614
615  ObjCImplementationDecl* IMPDecl =
616    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
617                                   IDecl, SDecl);
618
619  if (CheckObjCDeclScope(IMPDecl))
620    return DeclPtrTy::make(IMPDecl);
621
622  // Check that there is no duplicate implementation of this class.
623  if (IDecl->getImplementation()) {
624    // FIXME: Don't leak everything!
625    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
626    Diag(IDecl->getImplementation()->getLocation(),
627         diag::note_previous_definition);
628  } else { // add it to the list.
629    IDecl->setImplementation(IMPDecl);
630    PushOnScopeChains(IMPDecl, TUScope);
631  }
632  return DeclPtrTy::make(IMPDecl);
633}
634
635void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
636                                    ObjCIvarDecl **ivars, unsigned numIvars,
637                                    SourceLocation RBrace) {
638  assert(ImpDecl && "missing implementation decl");
639  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
640  if (!IDecl)
641    return;
642  /// Check case of non-existing @interface decl.
643  /// (legacy objective-c @implementation decl without an @interface decl).
644  /// Add implementations's ivar to the synthesize class's ivar list.
645  if (IDecl->isImplicitInterfaceDecl()) {
646    IDecl->setLocEnd(RBrace);
647    // Add ivar's to class's DeclContext.
648    for (unsigned i = 0, e = numIvars; i != e; ++i) {
649      ivars[i]->setLexicalDeclContext(ImpDecl);
650      IDecl->makeDeclVisibleInContext(ivars[i], false);
651      ImpDecl->addDecl(ivars[i]);
652    }
653
654    return;
655  }
656  // If implementation has empty ivar list, just return.
657  if (numIvars == 0)
658    return;
659
660  assert(ivars && "missing @implementation ivars");
661  if (LangOpts.ObjCNonFragileABI2) {
662    if (ImpDecl->getSuperClass())
663      Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
664    for (unsigned i = 0; i < numIvars; i++) {
665      ObjCIvarDecl* ImplIvar = ivars[i];
666      if (const ObjCIvarDecl *ClsIvar =
667            IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
668        Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
669        Diag(ClsIvar->getLocation(), diag::note_previous_definition);
670        continue;
671      }
672      // Instance ivar to Implementation's DeclContext.
673      ImplIvar->setLexicalDeclContext(ImpDecl);
674      IDecl->makeDeclVisibleInContext(ImplIvar, false);
675      ImpDecl->addDecl(ImplIvar);
676    }
677    return;
678  }
679  // Check interface's Ivar list against those in the implementation.
680  // names and types must match.
681  //
682  unsigned j = 0;
683  ObjCInterfaceDecl::ivar_iterator
684    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
685  for (; numIvars > 0 && IVI != IVE; ++IVI) {
686    ObjCIvarDecl* ImplIvar = ivars[j++];
687    ObjCIvarDecl* ClsIvar = *IVI;
688    assert (ImplIvar && "missing implementation ivar");
689    assert (ClsIvar && "missing class ivar");
690
691    // First, make sure the types match.
692    if (Context.getCanonicalType(ImplIvar->getType()) !=
693        Context.getCanonicalType(ClsIvar->getType())) {
694      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
695        << ImplIvar->getIdentifier()
696        << ImplIvar->getType() << ClsIvar->getType();
697      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
698    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
699      Expr *ImplBitWidth = ImplIvar->getBitWidth();
700      Expr *ClsBitWidth = ClsIvar->getBitWidth();
701      if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
702          ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
703        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
704          << ImplIvar->getIdentifier();
705        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
706      }
707    }
708    // Make sure the names are identical.
709    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
710      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
711        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
712      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
713    }
714    --numIvars;
715  }
716
717  if (numIvars > 0)
718    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
719  else if (IVI != IVE)
720    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
721}
722
723void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
724                               bool &IncompleteImpl, unsigned DiagID) {
725  if (!IncompleteImpl) {
726    Diag(ImpLoc, diag::warn_incomplete_impl);
727    IncompleteImpl = true;
728  }
729  Diag(method->getLocation(), DiagID)
730    << method->getDeclName();
731}
732
733void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
734                                       ObjCMethodDecl *IntfMethodDecl) {
735  if (!Context.typesAreCompatible(IntfMethodDecl->getResultType(),
736                                  ImpMethodDecl->getResultType()) &&
737      !Context.QualifiedIdConformsQualifiedId(IntfMethodDecl->getResultType(),
738                                              ImpMethodDecl->getResultType())) {
739    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_ret_types)
740      << ImpMethodDecl->getDeclName() << IntfMethodDecl->getResultType()
741      << ImpMethodDecl->getResultType();
742    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
743  }
744
745  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
746       IF = IntfMethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
747       IM != EM; ++IM, ++IF) {
748    QualType ParmDeclTy = (*IF)->getType().getUnqualifiedType();
749    QualType ParmImpTy = (*IM)->getType().getUnqualifiedType();
750    if (Context.typesAreCompatible(ParmDeclTy, ParmImpTy) ||
751        Context.QualifiedIdConformsQualifiedId(ParmDeclTy, ParmImpTy))
752      continue;
753
754    Diag((*IM)->getLocation(), diag::warn_conflicting_param_types)
755      << ImpMethodDecl->getDeclName() << (*IF)->getType()
756      << (*IM)->getType();
757    Diag((*IF)->getLocation(), diag::note_previous_definition);
758  }
759  if (ImpMethodDecl->isVariadic() != IntfMethodDecl->isVariadic()) {
760    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic);
761    Diag(IntfMethodDecl->getLocation(), diag::note_previous_declaration);
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(Scope *S, 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) && !LangOpts.ObjCNonFragileABI2)
939    DiagnoseUnimplementedProperties(S, 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 (const ObjCCategoryDecl *Categories = I->getFirstClassExtension();
966         Categories; Categories = Categories->getNextClassExtension())
967      ImplMethodsVsClassMethods(S, IMPDecl,
968                                const_cast<ObjCCategoryDecl*>(Categories),
969                                IncompleteImpl);
970  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
971    // For extended class, unimplemented methods in its protocols will
972    // be reported in the primary class.
973    if (!C->IsClassExtension()) {
974      for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
975           E = C->protocol_end(); PI != E; ++PI)
976        CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
977                                InsMap, ClsMap, CDecl);
978      // Report unimplemented properties in the category as well.
979      // When reporting on missing setter/getters, do not report when
980      // setter/getter is implemented in category's primary class
981      // implementation.
982      if (ObjCInterfaceDecl *ID = C->getClassInterface())
983        if (ObjCImplDecl *IMP = ID->getImplementation()) {
984          for (ObjCImplementationDecl::instmeth_iterator
985               I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
986            InsMap.insert((*I)->getSelector());
987        }
988      DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
989    }
990  } else
991    assert(false && "invalid ObjCContainerDecl type.");
992}
993
994/// ActOnForwardClassDeclaration -
995Action::DeclPtrTy
996Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
997                                   IdentifierInfo **IdentList,
998                                   SourceLocation *IdentLocs,
999                                   unsigned NumElts) {
1000  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1001
1002  for (unsigned i = 0; i != NumElts; ++i) {
1003    // Check for another declaration kind with the same name.
1004    NamedDecl *PrevDecl
1005      = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1006                         LookupOrdinaryName, ForRedeclaration);
1007    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1008      // Maybe we will complain about the shadowed template parameter.
1009      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1010      // Just pretend that we didn't see the previous declaration.
1011      PrevDecl = 0;
1012    }
1013
1014    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1015      // GCC apparently allows the following idiom:
1016      //
1017      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1018      // @class XCElementToggler;
1019      //
1020      // FIXME: Make an extension?
1021      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
1022      if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1023        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1024        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1025      } else {
1026        // a forward class declaration matching a typedef name of a class refers
1027        // to the underlying class.
1028        if (const ObjCObjectType *OI =
1029              TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1030          PrevDecl = OI->getInterface();
1031      }
1032    }
1033    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1034    if (!IDecl) {  // Not already seen?  Make a forward decl.
1035      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1036                                        IdentList[i], IdentLocs[i], true);
1037
1038      // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1039      // the current DeclContext.  This prevents clients that walk DeclContext
1040      // from seeing the imaginary ObjCInterfaceDecl until it is actually
1041      // declared later (if at all).  We also take care to explicitly make
1042      // sure this declaration is visible for name lookup.
1043      PushOnScopeChains(IDecl, TUScope, false);
1044      CurContext->makeDeclVisibleInContext(IDecl, true);
1045    }
1046
1047    Interfaces.push_back(IDecl);
1048  }
1049
1050  assert(Interfaces.size() == NumElts);
1051  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1052                                               Interfaces.data(), IdentLocs,
1053                                               Interfaces.size());
1054  CurContext->addDecl(CDecl);
1055  CheckObjCDeclScope(CDecl);
1056  return DeclPtrTy::make(CDecl);
1057}
1058
1059
1060/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1061/// returns true, or false, accordingly.
1062/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1063bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1064                                      const ObjCMethodDecl *PrevMethod,
1065                                      bool matchBasedOnSizeAndAlignment) {
1066  QualType T1 = Context.getCanonicalType(Method->getResultType());
1067  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1068
1069  if (T1 != T2) {
1070    // The result types are different.
1071    if (!matchBasedOnSizeAndAlignment)
1072      return false;
1073    // Incomplete types don't have a size and alignment.
1074    if (T1->isIncompleteType() || T2->isIncompleteType())
1075      return false;
1076    // Check is based on size and alignment.
1077    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1078      return false;
1079  }
1080
1081  ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1082       E = Method->param_end();
1083  ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1084
1085  for (; ParamI != E; ++ParamI, ++PrevI) {
1086    assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1087    T1 = Context.getCanonicalType((*ParamI)->getType());
1088    T2 = Context.getCanonicalType((*PrevI)->getType());
1089    if (T1 != T2) {
1090      // The result types are different.
1091      if (!matchBasedOnSizeAndAlignment)
1092        return false;
1093      // Incomplete types don't have a size and alignment.
1094      if (T1->isIncompleteType() || T2->isIncompleteType())
1095        return false;
1096      // Check is based on size and alignment.
1097      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1098        return false;
1099    }
1100  }
1101  return true;
1102}
1103
1104/// \brief Read the contents of the instance and factory method pools
1105/// for a given selector from external storage.
1106///
1107/// This routine should only be called once, when neither the instance
1108/// nor the factory method pool has an entry for this selector.
1109Sema::MethodPool::iterator Sema::ReadMethodPool(Selector Sel,
1110                                                bool isInstance) {
1111  assert(ExternalSource && "We need an external AST source");
1112  assert(InstanceMethodPool.find(Sel) == InstanceMethodPool.end() &&
1113         "Selector data already loaded into the instance method pool");
1114  assert(FactoryMethodPool.find(Sel) == FactoryMethodPool.end() &&
1115         "Selector data already loaded into the factory method pool");
1116
1117  // Read the method list from the external source.
1118  std::pair<ObjCMethodList, ObjCMethodList> Methods
1119    = ExternalSource->ReadMethodPool(Sel);
1120
1121  if (isInstance) {
1122    if (Methods.second.Method)
1123      FactoryMethodPool[Sel] = Methods.second;
1124    return InstanceMethodPool.insert(std::make_pair(Sel, Methods.first)).first;
1125  }
1126
1127  if (Methods.first.Method)
1128    InstanceMethodPool[Sel] = Methods.first;
1129
1130  return FactoryMethodPool.insert(std::make_pair(Sel, Methods.second)).first;
1131}
1132
1133void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
1134  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1135    = InstanceMethodPool.find(Method->getSelector());
1136  if (Pos == InstanceMethodPool.end()) {
1137    if (ExternalSource && !FactoryMethodPool.count(Method->getSelector()))
1138      Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/true);
1139    else
1140      Pos = InstanceMethodPool.insert(std::make_pair(Method->getSelector(),
1141                                                     ObjCMethodList())).first;
1142  }
1143
1144  ObjCMethodList &Entry = Pos->second;
1145  if (Entry.Method == 0) {
1146    // Haven't seen a method with this selector name yet - add it.
1147    Entry.Method = Method;
1148    Entry.Next = 0;
1149    return;
1150  }
1151
1152  // We've seen a method with this name, see if we have already seen this type
1153  // signature.
1154  for (ObjCMethodList *List = &Entry; List; List = List->Next)
1155    if (MatchTwoMethodDeclarations(Method, List->Method))
1156      return;
1157
1158  // We have a new signature for an existing method - add it.
1159  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1160  ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1161  Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1162}
1163
1164// FIXME: Finish implementing -Wno-strict-selector-match.
1165ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
1166                                                       SourceRange R,
1167                                                       bool warn) {
1168  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1169    = InstanceMethodPool.find(Sel);
1170  if (Pos == InstanceMethodPool.end()) {
1171    if (ExternalSource && !FactoryMethodPool.count(Sel))
1172      Pos = ReadMethodPool(Sel, /*isInstance=*/true);
1173    else
1174      return 0;
1175  }
1176
1177  ObjCMethodList &MethList = Pos->second;
1178  bool issueWarning = false;
1179
1180  if (MethList.Method && MethList.Next) {
1181    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1182      // This checks if the methods differ by size & alignment.
1183      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1184        issueWarning = warn;
1185  }
1186  if (issueWarning && (MethList.Method && MethList.Next)) {
1187    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1188    Diag(MethList.Method->getLocStart(), diag::note_using)
1189      << MethList.Method->getSourceRange();
1190    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1191      Diag(Next->Method->getLocStart(), diag::note_also_found)
1192        << Next->Method->getSourceRange();
1193  }
1194  return MethList.Method;
1195}
1196
1197void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
1198  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1199    = FactoryMethodPool.find(Method->getSelector());
1200  if (Pos == FactoryMethodPool.end()) {
1201    if (ExternalSource && !InstanceMethodPool.count(Method->getSelector()))
1202      Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/false);
1203    else
1204      Pos = FactoryMethodPool.insert(std::make_pair(Method->getSelector(),
1205                                                    ObjCMethodList())).first;
1206  }
1207
1208  ObjCMethodList &FirstMethod = Pos->second;
1209  if (!FirstMethod.Method) {
1210    // Haven't seen a method with this selector name yet - add it.
1211    FirstMethod.Method = Method;
1212    FirstMethod.Next = 0;
1213  } else {
1214    // We've seen a method with this name, now check the type signature(s).
1215    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1216
1217    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1218         Next = Next->Next)
1219      match = MatchTwoMethodDeclarations(Method, Next->Method);
1220
1221    if (!match) {
1222      // We have a new signature for an existing method - add it.
1223      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1224      ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1225      ObjCMethodList *OMI = new (Mem) ObjCMethodList(Method, FirstMethod.Next);
1226      FirstMethod.Next = OMI;
1227    }
1228  }
1229}
1230
1231ObjCMethodDecl *Sema::LookupFactoryMethodInGlobalPool(Selector Sel,
1232                                                      SourceRange R) {
1233  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1234    = FactoryMethodPool.find(Sel);
1235  if (Pos == FactoryMethodPool.end()) {
1236    if (ExternalSource && !InstanceMethodPool.count(Sel))
1237      Pos = ReadMethodPool(Sel, /*isInstance=*/false);
1238    else
1239      return 0;
1240  }
1241
1242  ObjCMethodList &MethList = Pos->second;
1243  bool issueWarning = false;
1244
1245  if (MethList.Method && MethList.Next) {
1246    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1247      // This checks if the methods differ by size & alignment.
1248      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1249        issueWarning = true;
1250  }
1251  if (issueWarning && (MethList.Method && MethList.Next)) {
1252    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1253    Diag(MethList.Method->getLocStart(), diag::note_using)
1254      << MethList.Method->getSourceRange();
1255    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1256      Diag(Next->Method->getLocStart(), diag::note_also_found)
1257        << Next->Method->getSourceRange();
1258  }
1259  return MethList.Method;
1260}
1261
1262/// CompareMethodParamsInBaseAndSuper - This routine compares methods with
1263/// identical selector names in current and its super classes and issues
1264/// a warning if any of their argument types are incompatible.
1265void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
1266                                             ObjCMethodDecl *Method,
1267                                             bool IsInstance)  {
1268  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
1269  if (ID == 0) return;
1270
1271  while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
1272    ObjCMethodDecl *SuperMethodDecl =
1273        SD->lookupMethod(Method->getSelector(), IsInstance);
1274    if (SuperMethodDecl == 0) {
1275      ID = SD;
1276      continue;
1277    }
1278    ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1279      E = Method->param_end();
1280    ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
1281    for (; ParamI != E; ++ParamI, ++PrevI) {
1282      // Number of parameters are the same and is guaranteed by selector match.
1283      assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
1284      QualType T1 = Context.getCanonicalType((*ParamI)->getType());
1285      QualType T2 = Context.getCanonicalType((*PrevI)->getType());
1286      // If type of arguement of method in this class does not match its
1287      // respective argument type in the super class method, issue warning;
1288      if (!Context.typesAreCompatible(T1, T2)) {
1289        Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
1290          << T1 << T2;
1291        Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
1292        return;
1293      }
1294    }
1295    ID = SD;
1296  }
1297}
1298
1299/// DiagnoseDuplicateIvars -
1300/// Check for duplicate ivars in the entire class at the start of
1301/// @implementation. This becomes necesssary because class extension can
1302/// add ivars to a class in random order which will not be known until
1303/// class's @implementation is seen.
1304void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
1305                                  ObjCInterfaceDecl *SID) {
1306  for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
1307       IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
1308    ObjCIvarDecl* Ivar = (*IVI);
1309    if (Ivar->isInvalidDecl())
1310      continue;
1311    if (IdentifierInfo *II = Ivar->getIdentifier()) {
1312      ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
1313      if (prevIvar) {
1314        Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
1315        Diag(prevIvar->getLocation(), diag::note_previous_declaration);
1316        Ivar->setInvalidDecl();
1317      }
1318    }
1319  }
1320}
1321
1322// Note: For class/category implemenations, allMethods/allProperties is
1323// always null.
1324void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
1325                      DeclPtrTy classDecl,
1326                      DeclPtrTy *allMethods, unsigned allNum,
1327                      DeclPtrTy *allProperties, unsigned pNum,
1328                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1329  Decl *ClassDecl = classDecl.getAs<Decl>();
1330
1331  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1332  // always passing in a decl. If the decl has an error, isInvalidDecl()
1333  // should be true.
1334  if (!ClassDecl)
1335    return;
1336
1337  bool isInterfaceDeclKind =
1338        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1339         || isa<ObjCProtocolDecl>(ClassDecl);
1340  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1341
1342  if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
1343    // FIXME: This is wrong.  We shouldn't be pretending that there is
1344    //  an '@end' in the declaration.
1345    SourceLocation L = ClassDecl->getLocation();
1346    AtEnd.setBegin(L);
1347    AtEnd.setEnd(L);
1348    Diag(L, diag::warn_missing_atend);
1349  }
1350
1351  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1352
1353  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1354  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1355  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1356
1357  for (unsigned i = 0; i < allNum; i++ ) {
1358    ObjCMethodDecl *Method =
1359      cast_or_null<ObjCMethodDecl>(allMethods[i].getAs<Decl>());
1360
1361    if (!Method) continue;  // Already issued a diagnostic.
1362    if (Method->isInstanceMethod()) {
1363      /// Check for instance method of the same name with incompatible types
1364      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1365      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1366                              : false;
1367      if ((isInterfaceDeclKind && PrevMethod && !match)
1368          || (checkIdenticalMethods && match)) {
1369          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1370            << Method->getDeclName();
1371          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1372      } else {
1373        DC->addDecl(Method);
1374        InsMap[Method->getSelector()] = Method;
1375        /// The following allows us to typecheck messages to "id".
1376        AddInstanceMethodToGlobalPool(Method);
1377        // verify that the instance method conforms to the same definition of
1378        // parent methods if it shadows one.
1379        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
1380      }
1381    } else {
1382      /// Check for class method of the same name with incompatible types
1383      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1384      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1385                              : false;
1386      if ((isInterfaceDeclKind && PrevMethod && !match)
1387          || (checkIdenticalMethods && match)) {
1388        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1389          << Method->getDeclName();
1390        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1391      } else {
1392        DC->addDecl(Method);
1393        ClsMap[Method->getSelector()] = Method;
1394        /// The following allows us to typecheck messages to "Class".
1395        AddFactoryMethodToGlobalPool(Method);
1396        // verify that the class method conforms to the same definition of
1397        // parent methods if it shadows one.
1398        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
1399      }
1400    }
1401  }
1402  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1403    // Compares properties declared in this class to those of its
1404    // super class.
1405    ComparePropertiesInBaseAndSuper(I);
1406    CompareProperties(I, DeclPtrTy::make(I));
1407  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1408    // Categories are used to extend the class by declaring new methods.
1409    // By the same token, they are also used to add new properties. No
1410    // need to compare the added property to those in the class.
1411
1412    // Compare protocol properties with those in category
1413    CompareProperties(C, DeclPtrTy::make(C));
1414    if (C->IsClassExtension())
1415      DiagnoseClassExtensionDupMethods(C, C->getClassInterface());
1416  }
1417  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1418    if (CDecl->getIdentifier())
1419      // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1420      // user-defined setter/getter. It also synthesizes setter/getter methods
1421      // and adds them to the DeclContext and global method pools.
1422      for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1423                                            E = CDecl->prop_end();
1424           I != E; ++I)
1425        ProcessPropertyDecl(*I, CDecl);
1426    CDecl->setAtEndRange(AtEnd);
1427  }
1428  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1429    IC->setAtEndRange(AtEnd);
1430    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
1431      if (LangOpts.ObjCNonFragileABI2)
1432        DefaultSynthesizeProperties(S, IC, IDecl);
1433      ImplMethodsVsClassMethods(S, IC, IDecl);
1434      AtomicPropertySetterGetterRules(IC, IDecl);
1435      if (LangOpts.ObjCNonFragileABI2)
1436        while (IDecl->getSuperClass()) {
1437          DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
1438          IDecl = IDecl->getSuperClass();
1439        }
1440    }
1441    SetIvarInitializers(IC);
1442  } else if (ObjCCategoryImplDecl* CatImplClass =
1443                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1444    CatImplClass->setAtEndRange(AtEnd);
1445
1446    // Find category interface decl and then check that all methods declared
1447    // in this interface are implemented in the category @implementation.
1448    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1449      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1450           Categories; Categories = Categories->getNextClassCategory()) {
1451        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1452          ImplMethodsVsClassMethods(S, CatImplClass, Categories);
1453          break;
1454        }
1455      }
1456    }
1457  }
1458  if (isInterfaceDeclKind) {
1459    // Reject invalid vardecls.
1460    for (unsigned i = 0; i != tuvNum; i++) {
1461      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1462      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1463        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1464          if (!VDecl->hasExternalStorage())
1465            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1466        }
1467    }
1468  }
1469}
1470
1471
1472/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1473/// objective-c's type qualifier from the parser version of the same info.
1474static Decl::ObjCDeclQualifier
1475CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1476  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1477  if (PQTVal & ObjCDeclSpec::DQ_In)
1478    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1479  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1480    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1481  if (PQTVal & ObjCDeclSpec::DQ_Out)
1482    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1483  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1484    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1485  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1486    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1487  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1488    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1489
1490  return ret;
1491}
1492
1493static inline
1494bool containsInvalidMethodImplAttribute(const AttributeList *A) {
1495  // The 'ibaction' attribute is allowed on method definitions because of
1496  // how the IBAction macro is used on both method declarations and definitions.
1497  // If the method definitions contains any other attributes, return true.
1498  while (A && A->getKind() == AttributeList::AT_IBAction)
1499    A = A->getNext();
1500  return A != NULL;
1501}
1502
1503Sema::DeclPtrTy Sema::ActOnMethodDeclaration(
1504    SourceLocation MethodLoc, SourceLocation EndLoc,
1505    tok::TokenKind MethodType, DeclPtrTy classDecl,
1506    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1507    Selector Sel,
1508    // optional arguments. The number of types/arguments is obtained
1509    // from the Sel.getNumArgs().
1510    ObjCArgInfo *ArgInfo,
1511    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
1512    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1513    bool isVariadic) {
1514  Decl *ClassDecl = classDecl.getAs<Decl>();
1515
1516  // Make sure we can establish a context for the method.
1517  if (!ClassDecl) {
1518    Diag(MethodLoc, diag::error_missing_method_context);
1519    getLabelMap().clear();
1520    return DeclPtrTy();
1521  }
1522  QualType resultDeclType;
1523
1524  TypeSourceInfo *ResultTInfo = 0;
1525  if (ReturnType) {
1526    resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
1527
1528    // Methods cannot return interface types. All ObjC objects are
1529    // passed by reference.
1530    if (resultDeclType->isObjCObjectType()) {
1531      Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1532        << 0 << resultDeclType;
1533      return DeclPtrTy();
1534    }
1535  } else // get the type for "id".
1536    resultDeclType = Context.getObjCIdType();
1537
1538  ObjCMethodDecl* ObjCMethod =
1539    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1540                           ResultTInfo,
1541                           cast<DeclContext>(ClassDecl),
1542                           MethodType == tok::minus, isVariadic,
1543                           false,
1544                           MethodDeclKind == tok::objc_optional ?
1545                           ObjCMethodDecl::Optional :
1546                           ObjCMethodDecl::Required);
1547
1548  llvm::SmallVector<ParmVarDecl*, 16> Params;
1549
1550  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1551    QualType ArgType;
1552    TypeSourceInfo *DI;
1553
1554    if (ArgInfo[i].Type == 0) {
1555      ArgType = Context.getObjCIdType();
1556      DI = 0;
1557    } else {
1558      ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
1559      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1560      ArgType = adjustParameterType(ArgType);
1561    }
1562
1563    ParmVarDecl* Param
1564      = ParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc,
1565                            ArgInfo[i].Name, ArgType, DI,
1566                            VarDecl::None, VarDecl::None, 0);
1567
1568    if (ArgType->isObjCObjectType()) {
1569      Diag(ArgInfo[i].NameLoc,
1570           diag::err_object_cannot_be_passed_returned_by_value)
1571        << 1 << ArgType;
1572      Param->setInvalidDecl();
1573    }
1574
1575    Param->setObjCDeclQualifier(
1576      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
1577
1578    // Apply the attributes to the parameter.
1579    ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
1580
1581    Params.push_back(Param);
1582  }
1583
1584  for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
1585    ParmVarDecl *Param = CParamInfo[i].Param.getAs<ParmVarDecl>();
1586    QualType ArgType = Param->getType();
1587    if (ArgType.isNull())
1588      ArgType = Context.getObjCIdType();
1589    else
1590      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1591      ArgType = adjustParameterType(ArgType);
1592    if (ArgType->isObjCObjectType()) {
1593      Diag(Param->getLocation(),
1594           diag::err_object_cannot_be_passed_returned_by_value)
1595      << 1 << ArgType;
1596      Param->setInvalidDecl();
1597    }
1598    Param->setDeclContext(ObjCMethod);
1599    IdResolver.RemoveDecl(Param);
1600    Params.push_back(Param);
1601  }
1602
1603  ObjCMethod->setMethodParams(Context, Params.data(), Params.size(),
1604                              Sel.getNumArgs());
1605  ObjCMethod->setObjCDeclQualifier(
1606    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1607  const ObjCMethodDecl *PrevMethod = 0;
1608
1609  if (AttrList)
1610    ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
1611
1612  const ObjCMethodDecl *InterfaceMD = 0;
1613
1614  // For implementations (which can be very "coarse grain"), we add the
1615  // method now. This allows the AST to implement lookup methods that work
1616  // incrementally (without waiting until we parse the @end). It also allows
1617  // us to flag multiple declaration errors as they occur.
1618  if (ObjCImplementationDecl *ImpDecl =
1619        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1620    if (MethodType == tok::minus) {
1621      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1622      ImpDecl->addInstanceMethod(ObjCMethod);
1623    } else {
1624      PrevMethod = ImpDecl->getClassMethod(Sel);
1625      ImpDecl->addClassMethod(ObjCMethod);
1626    }
1627    InterfaceMD = ImpDecl->getClassInterface()->getMethod(Sel,
1628                                                   MethodType == tok::minus);
1629    if (containsInvalidMethodImplAttribute(AttrList))
1630      Diag(EndLoc, diag::warn_attribute_method_def);
1631  } else if (ObjCCategoryImplDecl *CatImpDecl =
1632             dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1633    if (MethodType == tok::minus) {
1634      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1635      CatImpDecl->addInstanceMethod(ObjCMethod);
1636    } else {
1637      PrevMethod = CatImpDecl->getClassMethod(Sel);
1638      CatImpDecl->addClassMethod(ObjCMethod);
1639    }
1640    if (containsInvalidMethodImplAttribute(AttrList))
1641      Diag(EndLoc, diag::warn_attribute_method_def);
1642  }
1643  if (PrevMethod) {
1644    // You can never have two method definitions with the same name.
1645    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1646      << ObjCMethod->getDeclName();
1647    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1648  }
1649
1650  // If the interface declared this method, and it was deprecated there,
1651  // mark it deprecated here.
1652  if (InterfaceMD && InterfaceMD->hasAttr<DeprecatedAttr>())
1653    ObjCMethod->addAttr(::new (Context) DeprecatedAttr());
1654
1655  return DeclPtrTy::make(ObjCMethod);
1656}
1657
1658bool Sema::CheckObjCDeclScope(Decl *D) {
1659  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1660    return false;
1661
1662  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1663  D->setInvalidDecl();
1664
1665  return true;
1666}
1667
1668/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1669/// instance variables of ClassName into Decls.
1670void Sema::ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart,
1671                     IdentifierInfo *ClassName,
1672                     llvm::SmallVectorImpl<DeclPtrTy> &Decls) {
1673  // Check that ClassName is a valid class
1674  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
1675  if (!Class) {
1676    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1677    return;
1678  }
1679  if (LangOpts.ObjCNonFragileABI) {
1680    Diag(DeclStart, diag::err_atdef_nonfragile_interface);
1681    return;
1682  }
1683
1684  // Collect the instance variables
1685  llvm::SmallVector<FieldDecl*, 32> RecFields;
1686  Context.CollectObjCIvars(Class, RecFields);
1687  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1688  for (unsigned i = 0; i < RecFields.size(); i++) {
1689    FieldDecl* ID = RecFields[i];
1690    RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>());
1691    Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, ID->getLocation(),
1692                                           ID->getIdentifier(), ID->getType(),
1693                                           ID->getBitWidth());
1694    Decls.push_back(Sema::DeclPtrTy::make(FD));
1695  }
1696
1697  // Introduce all of these fields into the appropriate scope.
1698  for (llvm::SmallVectorImpl<DeclPtrTy>::iterator D = Decls.begin();
1699       D != Decls.end(); ++D) {
1700    FieldDecl *FD = cast<FieldDecl>(D->getAs<Decl>());
1701    if (getLangOptions().CPlusPlus)
1702      PushOnScopeChains(cast<FieldDecl>(FD), S);
1703    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>()))
1704      Record->addDecl(FD);
1705  }
1706}
1707
1708/// \brief Build a type-check a new Objective-C exception variable declaration.
1709VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo,
1710                                      QualType T,
1711                                      IdentifierInfo *Name,
1712                                      SourceLocation NameLoc,
1713                                      bool Invalid) {
1714  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
1715  // duration shall not be qualified by an address-space qualifier."
1716  // Since all parameters have automatic store duration, they can not have
1717  // an address space.
1718  if (T.getAddressSpace() != 0) {
1719    Diag(NameLoc, diag::err_arg_with_address_space);
1720    Invalid = true;
1721  }
1722
1723  // An @catch parameter must be an unqualified object pointer type;
1724  // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
1725  if (Invalid) {
1726    // Don't do any further checking.
1727  } else if (T->isDependentType()) {
1728    // Okay: we don't know what this type will instantiate to.
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  New->setExceptionVariable(true);
1740
1741  if (Invalid)
1742    New->setInvalidDecl();
1743  return New;
1744}
1745
1746Sema::DeclPtrTy Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
1747  const DeclSpec &DS = D.getDeclSpec();
1748
1749  // We allow the "register" storage class on exception variables because
1750  // GCC did, but we drop it completely. Any other storage class is an error.
1751  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1752    Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
1753      << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
1754  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
1755    Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
1756      << DS.getStorageClassSpec();
1757  }
1758  if (D.getDeclSpec().isThreadSpecified())
1759    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
1760  D.getMutableDeclSpec().ClearStorageClassSpecs();
1761
1762  DiagnoseFunctionSpecifiers(D);
1763
1764  // Check that there are no default arguments inside the type of this
1765  // exception object (C++ only).
1766  if (getLangOptions().CPlusPlus)
1767    CheckExtraCXXDefaultArguments(D);
1768
1769  TagDecl *OwnedDecl = 0;
1770  TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S, &OwnedDecl);
1771  QualType ExceptionType = TInfo->getType();
1772
1773  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
1774    // Objective-C++: Types shall not be defined in exception types.
1775    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
1776      << Context.getTypeDeclType(OwnedDecl);
1777  }
1778
1779  VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, D.getIdentifier(),
1780                                        D.getIdentifierLoc(),
1781                                        D.isInvalidType());
1782
1783  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
1784  if (D.getCXXScopeSpec().isSet()) {
1785    Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
1786      << D.getCXXScopeSpec().getRange();
1787    New->setInvalidDecl();
1788  }
1789
1790  // Add the parameter declaration into this scope.
1791  S->AddDecl(DeclPtrTy::make(New));
1792  if (D.getIdentifier())
1793    IdResolver.AddDecl(New);
1794
1795  ProcessDeclAttributes(S, New, D);
1796
1797  if (New->hasAttr<BlocksAttr>())
1798    Diag(New->getLocation(), diag::err_block_on_nonlocal);
1799  return DeclPtrTy::make(New);
1800}
1801
1802/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
1803/// initialization.
1804void Sema::CollectIvarsToConstructOrDestruct(const ObjCInterfaceDecl *OI,
1805                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
1806  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1807       E = OI->ivar_end(); I != E; ++I) {
1808    ObjCIvarDecl *Iv = (*I);
1809    QualType QT = Context.getBaseElementType(Iv->getType());
1810    if (QT->isRecordType())
1811      Ivars.push_back(*I);
1812  }
1813
1814  // Find ivars to construct/destruct in class extension.
1815  for (const ObjCCategoryDecl *CDecl = OI->getFirstClassExtension(); CDecl;
1816      CDecl = CDecl->getNextClassExtension()) {
1817    for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
1818         E = CDecl->ivar_end(); I != E; ++I) {
1819      ObjCIvarDecl *Iv = (*I);
1820      QualType QT = Context.getBaseElementType(Iv->getType());
1821      if (QT->isRecordType())
1822        Ivars.push_back(*I);
1823    }
1824  }
1825
1826  // Also add any ivar defined in this class's implementation.  This
1827  // includes synthesized ivars.
1828  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
1829    for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
1830         E = ImplDecl->ivar_end(); I != E; ++I) {
1831      ObjCIvarDecl *Iv = (*I);
1832      QualType QT = Context.getBaseElementType(Iv->getType());
1833      if (QT->isRecordType())
1834        Ivars.push_back(*I);
1835    }
1836  }
1837}
1838
1839void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
1840                                    CXXBaseOrMemberInitializer ** initializers,
1841                                                 unsigned numInitializers) {
1842  if (numInitializers > 0) {
1843    NumIvarInitializers = numInitializers;
1844    CXXBaseOrMemberInitializer **ivarInitializers =
1845    new (C) CXXBaseOrMemberInitializer*[NumIvarInitializers];
1846    memcpy(ivarInitializers, initializers,
1847           numInitializers * sizeof(CXXBaseOrMemberInitializer*));
1848    IvarInitializers = ivarInitializers;
1849  }
1850}
1851
1852