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