SemaDeclObjC.cpp revision 89951a86b594513c2a013532ed45d197413b1087
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 "clang/AST/ASTContext.h"
16#include "clang/AST/DeclObjC.h"
17#include "clang/Parse/DeclSpec.h"
18using namespace clang;
19
20/// ObjCActOnStartOfMethodDef - This routine sets up parameters; invisible
21/// and user declared, in the method definition's AST.
22void Sema::ObjCActOnStartOfMethodDef(Scope *FnBodyScope, DeclTy *D) {
23  assert(getCurMethodDecl() == 0 && "Method parsing confused");
24  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>((Decl *)D);
25
26  // If we don't have a valid method decl, simply return.
27  if (!MDecl)
28    return;
29
30  // Allow the rest of sema to find private method decl implementations.
31  if (MDecl->isInstanceMethod())
32    AddInstanceMethodToGlobalPool(MDecl);
33  else
34    AddFactoryMethodToGlobalPool(MDecl);
35
36  // Allow all of Sema to see that we are entering a method definition.
37  PushDeclContext(FnBodyScope, MDecl);
38
39  // Create Decl objects for each parameter, entrring them in the scope for
40  // binding to their use.
41
42  // Insert the invisible arguments, self and _cmd!
43  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
44
45  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
46  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
47
48  // Introduce all of the other parameters into this scope.
49  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
50       E = MDecl->param_end(); PI != E; ++PI)
51    if ((*PI)->getIdentifier())
52      PushOnScopeChains(*PI, FnBodyScope);
53}
54
55Sema::DeclTy *Sema::
56ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
57                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
58                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
59                         DeclTy * const *ProtoRefs, unsigned NumProtoRefs,
60                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
61  assert(ClassName && "Missing class identifier");
62
63  // Check for another declaration kind with the same name.
64  NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
65  if (PrevDecl && PrevDecl->isTemplateParameter()) {
66    // Maybe we will complain about the shadowed template parameter.
67    DiagnoseTemplateParameterShadow(ClassLoc, PrevDecl);
68    // Just pretend that we didn't see the previous declaration.
69    PrevDecl = 0;
70  }
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      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
82      Diag(IDecl->getLocation(), diag::note_previous_definition);
83
84      // Return the previous class interface.
85      // FIXME: don't leak the objects passed in!
86      return IDecl;
87    } else {
88      IDecl->setLocation(AtInterfaceLoc);
89      IDecl->setForwardDecl(false);
90    }
91  } else {
92    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
93                                      ClassName, ClassLoc);
94    if (AttrList)
95      ProcessDeclAttributeList(IDecl, AttrList);
96
97    ObjCInterfaceDecls[ClassName] = IDecl;
98    // FIXME: PushOnScopeChains
99    CurContext->addDecl(IDecl);
100    // Remember that this needs to be removed when the scope is popped.
101    TUScope->AddDecl(IDecl);
102  }
103
104  if (SuperName) {
105    // Check if a different kind of symbol declared in this scope.
106    PrevDecl = LookupName(TUScope, SuperName, LookupOrdinaryName);
107
108    ObjCInterfaceDecl *SuperClassDecl =
109                                  dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
110
111    // Diagnose classes that inherit from deprecated classes.
112    if (SuperClassDecl)
113      (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
114
115    if (PrevDecl && SuperClassDecl == 0) {
116      // The previous declaration was not a class decl. Check if we have a
117      // typedef. If we do, get the underlying class type.
118      if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
119        QualType T = TDecl->getUnderlyingType();
120        if (T->isObjCInterfaceType()) {
121          if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl())
122            SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
123        }
124      }
125
126      // This handles the following case:
127      //
128      // typedef int SuperClass;
129      // @interface MyClass : SuperClass {} @end
130      //
131      if (!SuperClassDecl) {
132        Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
133        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
134      }
135    }
136
137    if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
138      if (!SuperClassDecl)
139        Diag(SuperLoc, diag::err_undef_superclass)
140          << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
141      else if (SuperClassDecl->isForwardDecl())
142        Diag(SuperLoc, diag::err_undef_superclass)
143          << SuperClassDecl->getDeclName() << ClassName
144          << SourceRange(AtInterfaceLoc, ClassLoc);
145    }
146    IDecl->setSuperClass(SuperClassDecl);
147    IDecl->setSuperClassLoc(SuperLoc);
148    IDecl->setLocEnd(SuperLoc);
149  } else { // we have a root class.
150    IDecl->setLocEnd(ClassLoc);
151  }
152
153  /// Check then save referenced protocols.
154  if (NumProtoRefs) {
155    IDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
156    IDecl->setLocEnd(EndProtoLoc);
157  }
158
159  CheckObjCDeclScope(IDecl);
160  return IDecl;
161}
162
163/// ActOnCompatiblityAlias - this action is called after complete parsing of
164/// @compatibility_alias declaration. It sets up the alias relationships.
165Sema::DeclTy *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
166                                           IdentifierInfo *AliasName,
167                                           SourceLocation AliasLocation,
168                                           IdentifierInfo *ClassName,
169                                           SourceLocation ClassLocation) {
170  // Look for previous declaration of alias name
171  NamedDecl *ADecl = LookupName(TUScope, AliasName, LookupOrdinaryName);
172  if (ADecl) {
173    if (isa<ObjCCompatibleAliasDecl>(ADecl))
174      Diag(AliasLocation, diag::warn_previous_alias_decl);
175    else
176      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
177    Diag(ADecl->getLocation(), diag::note_previous_declaration);
178    return 0;
179  }
180  // Check for class declaration
181  NamedDecl *CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName);
182  if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
183    QualType T = TDecl->getUnderlyingType();
184    if (T->isObjCInterfaceType()) {
185      if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl()) {
186        ClassName = IDecl->getIdentifier();
187        CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName);
188      }
189    }
190  }
191  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
192  if (CDecl == 0) {
193    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
194    if (CDeclU)
195      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
196    return 0;
197  }
198
199  // Everything checked out, instantiate a new alias declaration AST.
200  ObjCCompatibleAliasDecl *AliasDecl =
201    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
202
203  ObjCAliasDecls[AliasName] = AliasDecl;
204
205  // FIXME: PushOnScopeChains?
206  CurContext->addDecl(AliasDecl);
207  if (!CheckObjCDeclScope(AliasDecl))
208    TUScope->AddDecl(AliasDecl);
209
210  return AliasDecl;
211}
212
213Sema::DeclTy *
214Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
215                                  IdentifierInfo *ProtocolName,
216                                  SourceLocation ProtocolLoc,
217                                  DeclTy * const *ProtoRefs,
218                                  unsigned NumProtoRefs,
219                                  SourceLocation EndProtoLoc,
220                                  AttributeList *AttrList) {
221  // FIXME: Deal with AttrList.
222  assert(ProtocolName && "Missing protocol identifier");
223  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
224  if (PDecl) {
225    // Protocol already seen. Better be a forward protocol declaration
226    if (!PDecl->isForwardDecl()) {
227      Diag(ProtocolLoc, diag::err_duplicate_protocol_def) << ProtocolName;
228      Diag(PDecl->getLocation(), diag::note_previous_definition);
229      // Just return the protocol we already had.
230      // FIXME: don't leak the objects passed in!
231      return PDecl;
232    }
233    // Make sure the cached decl gets a valid start location.
234    PDecl->setLocation(AtProtoInterfaceLoc);
235    PDecl->setForwardDecl(false);
236  } else {
237    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
238                                     AtProtoInterfaceLoc,ProtocolName);
239    // FIXME: PushOnScopeChains?
240    CurContext->addDecl(PDecl);
241    PDecl->setForwardDecl(false);
242    ObjCProtocols[ProtocolName] = PDecl;
243  }
244  if (AttrList)
245    ProcessDeclAttributeList(PDecl, AttrList);
246  if (NumProtoRefs) {
247    /// Check then save referenced protocols.
248    PDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
249    PDecl->setLocEnd(EndProtoLoc);
250  }
251
252  CheckObjCDeclScope(PDecl);
253  return PDecl;
254}
255
256/// FindProtocolDeclaration - This routine looks up protocols and
257/// issues an error if they are not declared. It returns list of
258/// protocol declarations in its 'Protocols' argument.
259void
260Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
261                              const IdentifierLocPair *ProtocolId,
262                              unsigned NumProtocols,
263                              llvm::SmallVectorImpl<DeclTy*> &Protocols) {
264  for (unsigned i = 0; i != NumProtocols; ++i) {
265    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i].first];
266    if (!PDecl) {
267      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
268        << ProtocolId[i].first;
269      continue;
270    }
271
272    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
273
274    // If this is a forward declaration and we are supposed to warn in this
275    // case, do it.
276    if (WarnOnDeclarations && PDecl->isForwardDecl())
277      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
278        << ProtocolId[i].first;
279    Protocols.push_back(PDecl);
280  }
281}
282
283/// DiagnosePropertyMismatch - Compares two properties for their
284/// attributes and types and warns on a variety of inconsistencies.
285///
286void
287Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
288                               ObjCPropertyDecl *SuperProperty,
289                               const IdentifierInfo *inheritedName) {
290  ObjCPropertyDecl::PropertyAttributeKind CAttr =
291  Property->getPropertyAttributes();
292  ObjCPropertyDecl::PropertyAttributeKind SAttr =
293  SuperProperty->getPropertyAttributes();
294  if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
295      && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
296    Diag(Property->getLocation(), diag::warn_readonly_property)
297      << Property->getDeclName() << inheritedName;
298  if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
299      != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
300    Diag(Property->getLocation(), diag::warn_property_attribute)
301      << Property->getDeclName() << "copy" << inheritedName;
302  else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain)
303           != (SAttr & ObjCPropertyDecl::OBJC_PR_retain))
304    Diag(Property->getLocation(), diag::warn_property_attribute)
305      << Property->getDeclName() << "retain" << inheritedName;
306
307  if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
308      != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
309    Diag(Property->getLocation(), diag::warn_property_attribute)
310      << Property->getDeclName() << "atomic" << inheritedName;
311  if (Property->getSetterName() != SuperProperty->getSetterName())
312    Diag(Property->getLocation(), diag::warn_property_attribute)
313      << Property->getDeclName() << "setter" << inheritedName;
314  if (Property->getGetterName() != SuperProperty->getGetterName())
315    Diag(Property->getLocation(), diag::warn_property_attribute)
316      << Property->getDeclName() << "getter" << inheritedName;
317
318  if (Context.getCanonicalType(Property->getType()) !=
319          Context.getCanonicalType(SuperProperty->getType()))
320    Diag(Property->getLocation(), diag::warn_property_type)
321      << Property->getType() << inheritedName;
322
323}
324
325/// ComparePropertiesInBaseAndSuper - This routine compares property
326/// declarations in base and its super class, if any, and issues
327/// diagnostics in a variety of inconsistant situations.
328///
329void Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
330  ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
331  if (!SDecl)
332    return;
333  // FIXME: O(N^2)
334  for (ObjCInterfaceDecl::prop_iterator S = SDecl->prop_begin(),
335       E = SDecl->prop_end(); S != E; ++S) {
336    ObjCPropertyDecl *SuperPDecl = (*S);
337    // Does property in super class has declaration in current class?
338    for (ObjCInterfaceDecl::prop_iterator I = IDecl->prop_begin(),
339         E = IDecl->prop_end(); I != E; ++I) {
340      ObjCPropertyDecl *PDecl = (*I);
341      if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
342          DiagnosePropertyMismatch(PDecl, SuperPDecl,
343                                   SDecl->getIdentifier());
344    }
345  }
346}
347
348/// MergeOneProtocolPropertiesIntoClass - This routine goes thru the list
349/// of properties declared in a protocol and adds them to the list
350/// of properties for current class/category if it is not there already.
351void
352Sema::MergeOneProtocolPropertiesIntoClass(Decl *CDecl,
353                                          ObjCProtocolDecl *PDecl) {
354  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
355  if (!IDecl) {
356    // Category
357    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
358    assert (CatDecl && "MergeOneProtocolPropertiesIntoClass");
359    for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
360         E = PDecl->prop_end(); P != E; ++P) {
361      ObjCPropertyDecl *Pr = (*P);
362      ObjCCategoryDecl::prop_iterator CP, CE;
363      // Is this property already in  category's list of properties?
364      for (CP = CatDecl->prop_begin(), CE = CatDecl->prop_end();
365           CP != CE; ++CP)
366        if ((*CP)->getIdentifier() == Pr->getIdentifier())
367          break;
368      if (CP != CE)
369        // Property protocol already exist in class. Diagnose any mismatch.
370        DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
371    }
372    return;
373  }
374  for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(),
375       E = PDecl->prop_end(); P != E; ++P) {
376    ObjCPropertyDecl *Pr = (*P);
377    ObjCInterfaceDecl::prop_iterator CP, CE;
378    // Is this property already in  class's list of properties?
379    for (CP = IDecl->prop_begin(), CE = IDecl->prop_end();
380         CP != CE; ++CP)
381      if ((*CP)->getIdentifier() == Pr->getIdentifier())
382        break;
383    if (CP != CE)
384      // Property protocol already exist in class. Diagnose any mismatch.
385      DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
386    }
387}
388
389/// MergeProtocolPropertiesIntoClass - This routine merges properties
390/// declared in 'MergeItsProtocols' objects (which can be a class or an
391/// inherited protocol into the list of properties for class/category 'CDecl'
392///
393void Sema::MergeProtocolPropertiesIntoClass(Decl *CDecl,
394                                            DeclTy *MergeItsProtocols) {
395  Decl *ClassDecl = static_cast<Decl *>(MergeItsProtocols);
396  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
397
398  if (!IDecl) {
399    // Category
400    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
401    assert (CatDecl && "MergeProtocolPropertiesIntoClass");
402    if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
403      for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(),
404           E = MDecl->protocol_end(); P != E; ++P)
405      // Merge properties of category (*P) into IDECL's
406      MergeOneProtocolPropertiesIntoClass(CatDecl, *P);
407
408      // Go thru the list of protocols for this category and recursively merge
409      // their properties into this class as well.
410      for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(),
411           E = CatDecl->protocol_end(); P != E; ++P)
412        MergeProtocolPropertiesIntoClass(CatDecl, *P);
413    } else {
414      ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
415      for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
416           E = MD->protocol_end(); P != E; ++P)
417        MergeOneProtocolPropertiesIntoClass(CatDecl, (*P));
418    }
419    return;
420  }
421
422  if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
423    for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(),
424         E = MDecl->protocol_end(); P != E; ++P)
425      // Merge properties of class (*P) into IDECL's
426      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
427
428    // Go thru the list of protocols for this class and recursively merge
429    // their properties into this class as well.
430    for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(),
431         E = IDecl->protocol_end(); P != E; ++P)
432      MergeProtocolPropertiesIntoClass(IDecl, *P);
433  } else {
434    ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
435    for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
436         E = MD->protocol_end(); P != E; ++P)
437      MergeOneProtocolPropertiesIntoClass(IDecl, (*P));
438  }
439}
440
441/// ActOnForwardProtocolDeclaration -
442Action::DeclTy *
443Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
444                                      const IdentifierLocPair *IdentList,
445                                      unsigned NumElts,
446                                      AttributeList *attrList) {
447  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
448
449  for (unsigned i = 0; i != NumElts; ++i) {
450    IdentifierInfo *Ident = IdentList[i].first;
451    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
452    if (PDecl == 0) { // Not already seen?
453      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
454                                       IdentList[i].second, Ident);
455      // FIXME: PushOnScopeChains?
456      CurContext->addDecl(PDecl);
457    }
458    if (attrList)
459      ProcessDeclAttributeList(PDecl, attrList);
460    Protocols.push_back(PDecl);
461  }
462
463  ObjCForwardProtocolDecl *PDecl =
464    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
465                                    &Protocols[0], Protocols.size());
466  CurContext->addDecl(PDecl);
467  CheckObjCDeclScope(PDecl);
468  return PDecl;
469}
470
471Sema::DeclTy *Sema::
472ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
473                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
474                            IdentifierInfo *CategoryName,
475                            SourceLocation CategoryLoc,
476                            DeclTy * const *ProtoRefs,
477                            unsigned NumProtoRefs,
478                            SourceLocation EndProtoLoc) {
479  ObjCCategoryDecl *CDecl =
480    ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, CategoryName);
481  // FIXME: PushOnScopeChains?
482  CurContext->addDecl(CDecl);
483
484  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
485  /// Check that class of this category is already completely declared.
486  if (!IDecl || IDecl->isForwardDecl()) {
487    CDecl->setInvalidDecl();
488    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
489    return CDecl;
490  }
491
492  CDecl->setClassInterface(IDecl);
493
494  // If the interface is deprecated, warn about it.
495  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
496
497  /// Check for duplicate interface declaration for this category
498  ObjCCategoryDecl *CDeclChain;
499  for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
500       CDeclChain = CDeclChain->getNextClassCategory()) {
501    if (CategoryName && CDeclChain->getIdentifier() == CategoryName) {
502      Diag(CategoryLoc, diag::warn_dup_category_def)
503      << ClassName << CategoryName;
504      Diag(CDeclChain->getLocation(), diag::note_previous_definition);
505      break;
506    }
507  }
508  if (!CDeclChain)
509    CDecl->insertNextClassCategory();
510
511  if (NumProtoRefs) {
512    CDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
513    CDecl->setLocEnd(EndProtoLoc);
514  }
515
516  CheckObjCDeclScope(CDecl);
517  return CDecl;
518}
519
520/// ActOnStartCategoryImplementation - Perform semantic checks on the
521/// category implementation declaration and build an ObjCCategoryImplDecl
522/// object.
523Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
524                      SourceLocation AtCatImplLoc,
525                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
526                      IdentifierInfo *CatName, SourceLocation CatLoc) {
527  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
528  ObjCCategoryImplDecl *CDecl =
529    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
530                                 IDecl);
531  /// Check that class of this category is already completely declared.
532  if (!IDecl || IDecl->isForwardDecl())
533    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
534
535  // FIXME: PushOnScopeChains?
536  CurContext->addDecl(CDecl);
537
538  /// TODO: Check that CatName, category name, is not used in another
539  // implementation.
540  ObjCCategoryImpls.push_back(CDecl);
541
542  CheckObjCDeclScope(CDecl);
543  return CDecl;
544}
545
546Sema::DeclTy *Sema::ActOnStartClassImplementation(
547                      SourceLocation AtClassImplLoc,
548                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
549                      IdentifierInfo *SuperClassname,
550                      SourceLocation SuperClassLoc) {
551  ObjCInterfaceDecl* IDecl = 0;
552  // Check for another declaration kind with the same name.
553  NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
554  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
555    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
556    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
557  }
558  else {
559    // Is there an interface declaration of this class; if not, warn!
560    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
561    if (!IDecl)
562      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
563  }
564
565  // Check that super class name is valid class name
566  ObjCInterfaceDecl* SDecl = 0;
567  if (SuperClassname) {
568    // Check if a different kind of symbol declared in this scope.
569    PrevDecl = LookupName(TUScope, SuperClassname, LookupOrdinaryName);
570    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
571      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
572        << SuperClassname;
573      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
574    } else {
575      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
576      if (!SDecl)
577        Diag(SuperClassLoc, diag::err_undef_superclass)
578          << SuperClassname << ClassName;
579      else if (IDecl && IDecl->getSuperClass() != SDecl) {
580        // This implementation and its interface do not have the same
581        // super class.
582        Diag(SuperClassLoc, diag::err_conflicting_super_class)
583          << SDecl->getDeclName();
584        Diag(SDecl->getLocation(), diag::note_previous_definition);
585      }
586    }
587  }
588
589  if (!IDecl) {
590    // Legacy case of @implementation with no corresponding @interface.
591    // Build, chain & install the interface decl into the identifier.
592
593    // FIXME: Do we support attributes on the @implementation? If so
594    // we should copy them over.
595    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
596                                      ClassName, ClassLoc, false, true);
597    ObjCInterfaceDecls[ClassName] = IDecl;
598    IDecl->setSuperClass(SDecl);
599    IDecl->setLocEnd(ClassLoc);
600
601    // FIXME: PushOnScopeChains?
602    CurContext->addDecl(IDecl);
603    // Remember that this needs to be removed when the scope is popped.
604    TUScope->AddDecl(IDecl);
605  }
606
607  ObjCImplementationDecl* IMPDecl =
608    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
609                                   IDecl, SDecl);
610
611  // FIXME: PushOnScopeChains?
612  CurContext->addDecl(IMPDecl);
613
614  if (CheckObjCDeclScope(IMPDecl))
615    return IMPDecl;
616
617  // Check that there is no duplicate implementation of this class.
618  if (ObjCImplementations[ClassName])
619    // FIXME: Don't leak everything!
620    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
621  else // add it to the list.
622    ObjCImplementations[ClassName] = IMPDecl;
623  return IMPDecl;
624}
625
626void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
627                                    ObjCIvarDecl **ivars, unsigned numIvars,
628                                    SourceLocation RBrace) {
629  assert(ImpDecl && "missing implementation decl");
630  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
631  if (!IDecl)
632    return;
633  /// Check case of non-existing @interface decl.
634  /// (legacy objective-c @implementation decl without an @interface decl).
635  /// Add implementations's ivar to the synthesize class's ivar list.
636  if (IDecl->ImplicitInterfaceDecl()) {
637    IDecl->addInstanceVariablesToClass(ivars, numIvars, RBrace);
638    return;
639  }
640  // If implementation has empty ivar list, just return.
641  if (numIvars == 0)
642    return;
643
644  assert(ivars && "missing @implementation ivars");
645
646  // Check interface's Ivar list against those in the implementation.
647  // names and types must match.
648  //
649  unsigned j = 0;
650  ObjCInterfaceDecl::ivar_iterator
651    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
652  for (; numIvars > 0 && IVI != IVE; ++IVI) {
653    ObjCIvarDecl* ImplIvar = ivars[j++];
654    ObjCIvarDecl* ClsIvar = *IVI;
655    assert (ImplIvar && "missing implementation ivar");
656    assert (ClsIvar && "missing class ivar");
657    if (Context.getCanonicalType(ImplIvar->getType()) !=
658        Context.getCanonicalType(ClsIvar->getType())) {
659      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
660        << ImplIvar->getIdentifier()
661        << ImplIvar->getType() << ClsIvar->getType();
662      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
663    }
664    // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
665    // as error.
666    else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
667      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
668        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
669      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
670      return;
671    }
672    --numIvars;
673  }
674
675  if (numIvars > 0)
676    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
677  else if (IVI != IVE)
678    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
679}
680
681void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
682                               bool &IncompleteImpl) {
683  if (!IncompleteImpl) {
684    Diag(ImpLoc, diag::warn_incomplete_impl);
685    IncompleteImpl = true;
686  }
687  Diag(ImpLoc, diag::warn_undef_method_impl) << method->getDeclName();
688}
689
690void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
691                                       ObjCMethodDecl *IntfMethodDecl) {
692  bool err = false;
693  QualType ImpMethodQType =
694    Context.getCanonicalType(ImpMethodDecl->getResultType());
695  QualType IntfMethodQType =
696    Context.getCanonicalType(IntfMethodDecl->getResultType());
697  if (!Context.typesAreCompatible(IntfMethodQType, ImpMethodQType))
698    err = true;
699  else for (ObjCMethodDecl::param_iterator IM=ImpMethodDecl->param_begin(),
700            IF=IntfMethodDecl->param_begin(),
701            EM=ImpMethodDecl->param_end(); IM!=EM; ++IM, IF++) {
702    ImpMethodQType = Context.getCanonicalType((*IM)->getType());
703    IntfMethodQType = Context.getCanonicalType((*IF)->getType());
704    if (!Context.typesAreCompatible(IntfMethodQType, ImpMethodQType)) {
705      err = true;
706      break;
707    }
708  }
709  if (err) {
710    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_types)
711    << ImpMethodDecl->getDeclName();
712    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
713  }
714}
715
716/// isPropertyReadonly - Return true if property is readonly, by searching
717/// for the property in the class and in its categories and implementations
718///
719bool Sema::isPropertyReadonly(ObjCPropertyDecl *PDecl,
720                              ObjCInterfaceDecl *IDecl) const {
721  // by far the most common case.
722  if (!PDecl->isReadOnly())
723    return false;
724  // Even if property is ready only, if interface has a user defined setter,
725  // it is not considered read only.
726  if (IDecl->getInstanceMethod(PDecl->getSetterName()))
727    return false;
728
729  // Main class has the property as 'readonly'. Must search
730  // through the category list to see if the property's
731  // attribute has been over-ridden to 'readwrite'.
732  for (ObjCCategoryDecl *Category = IDecl->getCategoryList();
733       Category; Category = Category->getNextClassCategory()) {
734    // Even if property is ready only, if a category has a user defined setter,
735    // it is not considered read only.
736    if (Category->getInstanceMethod(PDecl->getSetterName()))
737      return false;
738    ObjCPropertyDecl *P =
739    Category->FindPropertyDeclaration(PDecl->getIdentifier());
740    if (P && !P->isReadOnly())
741      return false;
742  }
743
744  // Also, check for definition of a setter method in the implementation if
745  // all else failed.
746  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurContext)) {
747    if (ObjCImplementationDecl *IMD =
748        dyn_cast<ObjCImplementationDecl>(OMD->getDeclContext())) {
749      if (IMD->getInstanceMethod(PDecl->getSetterName()))
750        return false;
751    }
752    else if (ObjCCategoryImplDecl *CIMD =
753             dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
754      if (CIMD->getInstanceMethod(PDecl->getSetterName()))
755        return false;
756    }
757  }
758  return true;
759}
760
761/// FIXME: Type hierarchies in Objective-C can be deep. We could most
762/// likely improve the efficiency of selector lookups and type
763/// checking by associating with each protocol / interface / category
764/// the flattened instance tables. If we used an immutable set to keep
765/// the table then it wouldn't add significant memory cost and it
766/// would be handy for lookups.
767
768/// CheckProtocolMethodDefs - This routine checks unimplemented methods
769/// Declared in protocol, and those referenced by it.
770void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
771                                   ObjCProtocolDecl *PDecl,
772                                   bool& IncompleteImpl,
773                                   const llvm::DenseSet<Selector> &InsMap,
774                                   const llvm::DenseSet<Selector> &ClsMap,
775                                   ObjCInterfaceDecl *IDecl) {
776  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
777
778  // If a method lookup fails locally we still need to look and see if
779  // the method was implemented by a base class or an inherited
780  // protocol. This lookup is slow, but occurs rarely in correct code
781  // and otherwise would terminate in a warning.
782
783  // check unimplemented instance methods.
784  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
785       E = PDecl->instmeth_end(); I != E; ++I) {
786    ObjCMethodDecl *method = *I;
787    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
788        !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
789        (!Super || !Super->lookupInstanceMethod(method->getSelector())))
790      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
791  }
792  // check unimplemented class methods
793  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
794       E = PDecl->classmeth_end(); I != E; ++I) {
795    ObjCMethodDecl *method = *I;
796    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
797        !ClsMap.count(method->getSelector()) &&
798        (!Super || !Super->lookupClassMethod(method->getSelector())))
799      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
800  }
801  // Check on this protocols's referenced protocols, recursively.
802  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
803       E = PDecl->protocol_end(); PI != E; ++PI)
804    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
805}
806
807void Sema::ImplMethodsVsClassMethods(ObjCImplementationDecl* IMPDecl,
808                                     ObjCInterfaceDecl* IDecl) {
809  llvm::DenseSet<Selector> InsMap;
810  // Check and see if instance methods in class interface have been
811  // implemented in the implementation class.
812  for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(),
813       E = IMPDecl->instmeth_end(); I != E; ++I)
814    InsMap.insert((*I)->getSelector());
815
816  bool IncompleteImpl = false;
817  for (ObjCInterfaceDecl::instmeth_iterator I = IDecl->instmeth_begin(),
818       E = IDecl->instmeth_end(); I != E; ++I) {
819    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector())) {
820      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
821      continue;
822    }
823
824    ObjCMethodDecl *ImpMethodDecl =
825      IMPDecl->getInstanceMethod((*I)->getSelector());
826    ObjCMethodDecl *IntfMethodDecl =
827      IDecl->getInstanceMethod((*I)->getSelector());
828    assert(IntfMethodDecl &&
829           "IntfMethodDecl is null in ImplMethodsVsClassMethods");
830    // ImpMethodDecl may be null as in a @dynamic property.
831    if (ImpMethodDecl)
832      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
833  }
834
835  llvm::DenseSet<Selector> ClsMap;
836  // Check and see if class methods in class interface have been
837  // implemented in the implementation class.
838  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
839       E = IMPDecl->classmeth_end(); I != E; ++I)
840    ClsMap.insert((*I)->getSelector());
841
842  for (ObjCInterfaceDecl::classmeth_iterator I = IDecl->classmeth_begin(),
843       E = IDecl->classmeth_end(); I != E; ++I)
844    if (!ClsMap.count((*I)->getSelector()))
845      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
846    else {
847      ObjCMethodDecl *ImpMethodDecl =
848        IMPDecl->getClassMethod((*I)->getSelector());
849      ObjCMethodDecl *IntfMethodDecl =
850        IDecl->getClassMethod((*I)->getSelector());
851      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
852    }
853
854
855  // Check the protocol list for unimplemented methods in the @implementation
856  // class.
857  const ObjCList<ObjCProtocolDecl> &Protocols =
858    IDecl->getReferencedProtocols();
859  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
860       E = Protocols.end(); I != E; ++I)
861    CheckProtocolMethodDefs(IMPDecl->getLocation(), *I,
862                            IncompleteImpl, InsMap, ClsMap, IDecl);
863}
864
865/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
866/// category interface are implemented in the category @implementation.
867void Sema::ImplCategoryMethodsVsIntfMethods(ObjCCategoryImplDecl *CatImplDecl,
868                                            ObjCCategoryDecl *CatClassDecl) {
869  llvm::DenseSet<Selector> InsMap;
870  // Check and see if instance methods in category interface have been
871  // implemented in its implementation class.
872  for (ObjCCategoryImplDecl::instmeth_iterator I =CatImplDecl->instmeth_begin(),
873       E = CatImplDecl->instmeth_end(); I != E; ++I)
874    InsMap.insert((*I)->getSelector());
875
876  bool IncompleteImpl = false;
877  for (ObjCCategoryDecl::instmeth_iterator I = CatClassDecl->instmeth_begin(),
878       E = CatClassDecl->instmeth_end(); I != E; ++I)
879    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector()))
880      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
881    else {
882      ObjCMethodDecl *ImpMethodDecl =
883        CatImplDecl->getInstanceMethod((*I)->getSelector());
884      ObjCMethodDecl *IntfMethodDecl =
885        CatClassDecl->getInstanceMethod((*I)->getSelector());
886      assert(IntfMethodDecl &&
887             "IntfMethodDecl is null in ImplCategoryMethodsVsIntfMethods");
888      // ImpMethodDecl may be null as in a @dynamic property.
889      if (ImpMethodDecl)
890        WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
891    }
892
893  llvm::DenseSet<Selector> ClsMap;
894  // Check and see if class methods in category interface have been
895  // implemented in its implementation class.
896  for (ObjCCategoryImplDecl::classmeth_iterator
897       I = CatImplDecl->classmeth_begin(), E = CatImplDecl->classmeth_end();
898       I != E; ++I)
899    ClsMap.insert((*I)->getSelector());
900
901  for (ObjCCategoryDecl::classmeth_iterator I = CatClassDecl->classmeth_begin(),
902       E = CatClassDecl->classmeth_end(); I != E; ++I)
903    if (!ClsMap.count((*I)->getSelector()))
904      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
905    else {
906      ObjCMethodDecl *ImpMethodDecl =
907        CatImplDecl->getClassMethod((*I)->getSelector());
908      ObjCMethodDecl *IntfMethodDecl =
909        CatClassDecl->getClassMethod((*I)->getSelector());
910      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
911    }
912  // Check the protocol list for unimplemented methods in the @implementation
913  // class.
914  for (ObjCCategoryDecl::protocol_iterator PI = CatClassDecl->protocol_begin(),
915       E = CatClassDecl->protocol_end(); PI != E; ++PI)
916    CheckProtocolMethodDefs(CatImplDecl->getLocation(), *PI, IncompleteImpl,
917                            InsMap, ClsMap, CatClassDecl->getClassInterface());
918}
919
920/// ActOnForwardClassDeclaration -
921Action::DeclTy *
922Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
923                                   IdentifierInfo **IdentList,
924                                   unsigned NumElts) {
925  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
926
927  for (unsigned i = 0; i != NumElts; ++i) {
928    // Check for another declaration kind with the same name.
929    NamedDecl *PrevDecl = LookupName(TUScope, IdentList[i], LookupOrdinaryName);
930    if (PrevDecl && PrevDecl->isTemplateParameter()) {
931      // Maybe we will complain about the shadowed template parameter.
932      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
933      // Just pretend that we didn't see the previous declaration.
934      PrevDecl = 0;
935    }
936
937    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
938      // GCC apparently allows the following idiom:
939      //
940      // typedef NSObject < XCElementTogglerP > XCElementToggler;
941      // @class XCElementToggler;
942      //
943      // FIXME: Make an extension?
944      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
945      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
946        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
947        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
948      }
949    }
950    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
951    if (!IDecl) {  // Not already seen?  Make a forward decl.
952      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
953                                        IdentList[i], SourceLocation(), true);
954      ObjCInterfaceDecls[IdentList[i]] = IDecl;
955
956      // FIXME: PushOnScopeChains?
957      CurContext->addDecl(IDecl);
958      // Remember that this needs to be removed when the scope is popped.
959      TUScope->AddDecl(IDecl);
960    }
961
962    Interfaces.push_back(IDecl);
963  }
964
965  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
966                                               &Interfaces[0],
967                                               Interfaces.size());
968  CurContext->addDecl(CDecl);
969  CheckObjCDeclScope(CDecl);
970  return CDecl;
971}
972
973
974/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
975/// returns true, or false, accordingly.
976/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
977bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
978                                      const ObjCMethodDecl *PrevMethod,
979                                      bool matchBasedOnSizeAndAlignment) {
980  QualType T1 = Context.getCanonicalType(Method->getResultType());
981  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
982
983  if (T1 != T2) {
984    // The result types are different.
985    if (!matchBasedOnSizeAndAlignment)
986      return false;
987    // Incomplete types don't have a size and alignment.
988    if (T1->isIncompleteType() || T2->isIncompleteType())
989      return false;
990    // Check is based on size and alignment.
991    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
992      return false;
993  }
994
995  ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
996       E = Method->param_end();
997  ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
998
999  for (; ParamI != E; ++ParamI, ++PrevI) {
1000    assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1001    T1 = Context.getCanonicalType((*ParamI)->getType());
1002    T2 = Context.getCanonicalType((*PrevI)->getType());
1003    if (T1 != T2) {
1004      // The result types are different.
1005      if (!matchBasedOnSizeAndAlignment)
1006        return false;
1007      // Incomplete types don't have a size and alignment.
1008      if (T1->isIncompleteType() || T2->isIncompleteType())
1009        return false;
1010      // Check is based on size and alignment.
1011      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1012        return false;
1013    }
1014  }
1015  return true;
1016}
1017
1018void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
1019  ObjCMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
1020  if (!FirstMethod.Method) {
1021    // Haven't seen a method with this selector name yet - add it.
1022    FirstMethod.Method = Method;
1023    FirstMethod.Next = 0;
1024  } else {
1025    // We've seen a method with this name, now check the type signature(s).
1026    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1027
1028    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1029         Next = Next->Next)
1030      match = MatchTwoMethodDeclarations(Method, Next->Method);
1031
1032    if (!match) {
1033      // We have a new signature for an existing method - add it.
1034      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1035      FirstMethod.Next = new ObjCMethodList(Method, FirstMethod.Next);;
1036    }
1037  }
1038}
1039
1040// FIXME: Finish implementing -Wno-strict-selector-match.
1041ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
1042                                                       SourceRange R) {
1043  ObjCMethodList &MethList = InstanceMethodPool[Sel];
1044  bool issueWarning = false;
1045
1046  if (MethList.Method && MethList.Next) {
1047    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1048      // This checks if the methods differ by size & alignment.
1049      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1050        issueWarning = true;
1051  }
1052  if (issueWarning && (MethList.Method && MethList.Next)) {
1053    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1054    Diag(MethList.Method->getLocStart(), diag::note_using_decl)
1055      << MethList.Method->getSourceRange();
1056    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1057      Diag(Next->Method->getLocStart(), diag::note_also_found_decl)
1058        << Next->Method->getSourceRange();
1059  }
1060  return MethList.Method;
1061}
1062
1063void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
1064  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
1065  if (!FirstMethod.Method) {
1066    // Haven't seen a method with this selector name yet - add it.
1067    FirstMethod.Method = Method;
1068    FirstMethod.Next = 0;
1069  } else {
1070    // We've seen a method with this name, now check the type signature(s).
1071    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1072
1073    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1074         Next = Next->Next)
1075      match = MatchTwoMethodDeclarations(Method, Next->Method);
1076
1077    if (!match) {
1078      // We have a new signature for an existing method - add it.
1079      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1080      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
1081      FirstMethod.Next = OMI;
1082    }
1083  }
1084}
1085
1086/// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
1087/// have the property type and issue diagnostics if they don't.
1088/// Also synthesize a getter/setter method if none exist (and update the
1089/// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
1090/// methods is the "right" thing to do.
1091void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
1092                               ObjCContainerDecl *CD) {
1093  ObjCMethodDecl *GetterMethod, *SetterMethod;
1094
1095  GetterMethod = CD->getInstanceMethod(property->getGetterName());
1096  SetterMethod = CD->getInstanceMethod(property->getSetterName());
1097
1098  if (GetterMethod &&
1099      GetterMethod->getResultType() != property->getType()) {
1100    Diag(property->getLocation(),
1101         diag::err_accessor_property_type_mismatch)
1102      << property->getDeclName()
1103      << GetterMethod->getSelector().getAsIdentifierInfo();
1104    Diag(GetterMethod->getLocation(), diag::note_declared_at);
1105  }
1106
1107  if (SetterMethod) {
1108    if (Context.getCanonicalType(SetterMethod->getResultType())
1109        != Context.VoidTy)
1110      Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1111    if (SetterMethod->param_size() != 1 ||
1112        ((*SetterMethod->param_begin())->getType() != property->getType())) {
1113      Diag(property->getLocation(),
1114           diag::err_accessor_property_type_mismatch)
1115        << property->getDeclName()
1116        << SetterMethod->getSelector().getAsIdentifierInfo();
1117      Diag(SetterMethod->getLocation(), diag::note_declared_at);
1118    }
1119  }
1120
1121  // Synthesize getter/setter methods if none exist.
1122  // Find the default getter and if one not found, add one.
1123  // FIXME: The synthesized property we set here is misleading. We
1124  // almost always synthesize these methods unless the user explicitly
1125  // provided prototypes (which is odd, but allowed). Sema should be
1126  // typechecking that the declarations jive in that situation (which
1127  // it is not currently).
1128  if (!GetterMethod) {
1129    // No instance method of same name as property getter name was found.
1130    // Declare a getter method and add it to the list of methods
1131    // for this class.
1132    GetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(),
1133                             property->getLocation(), property->getGetterName(),
1134                             property->getType(), CD, true, false, true,
1135                             (property->getPropertyImplementation() ==
1136                              ObjCPropertyDecl::Optional) ?
1137                             ObjCMethodDecl::Optional :
1138                             ObjCMethodDecl::Required);
1139    CD->addDecl(GetterMethod);
1140  } else
1141    // A user declared getter will be synthesize when @synthesize of
1142    // the property with the same name is seen in the @implementation
1143    GetterMethod->setIsSynthesized();
1144  property->setGetterMethodDecl(GetterMethod);
1145
1146  // Skip setter if property is read-only.
1147  if (!property->isReadOnly()) {
1148    // Find the default setter and if one not found, add one.
1149    if (!SetterMethod) {
1150      // No instance method of same name as property setter name was found.
1151      // Declare a setter method and add it to the list of methods
1152      // for this class.
1153      SetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(),
1154                               property->getLocation(),
1155                               property->getSetterName(),
1156                               Context.VoidTy, CD, true, false, true,
1157                               (property->getPropertyImplementation() ==
1158                                ObjCPropertyDecl::Optional) ?
1159                               ObjCMethodDecl::Optional :
1160                               ObjCMethodDecl::Required);
1161      // Invent the arguments for the setter. We don't bother making a
1162      // nice name for the argument.
1163      ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
1164                                                  SourceLocation(),
1165                                                  property->getIdentifier(),
1166                                                  property->getType(),
1167                                                  VarDecl::None,
1168                                                  0);
1169      SetterMethod->setMethodParams(&Argument, 1);
1170      CD->addDecl(SetterMethod);
1171    } else
1172      // A user declared setter will be synthesize when @synthesize of
1173      // the property with the same name is seen in the @implementation
1174      SetterMethod->setIsSynthesized();
1175    property->setSetterMethodDecl(SetterMethod);
1176  }
1177  // Add any synthesized methods to the global pool. This allows us to
1178  // handle the following, which is supported by GCC (and part of the design).
1179  //
1180  // @interface Foo
1181  // @property double bar;
1182  // @end
1183  //
1184  // void thisIsUnfortunate() {
1185  //   id foo;
1186  //   double bar = [foo bar];
1187  // }
1188  //
1189  if (GetterMethod)
1190    AddInstanceMethodToGlobalPool(GetterMethod);
1191  if (SetterMethod)
1192    AddInstanceMethodToGlobalPool(SetterMethod);
1193}
1194
1195// Note: For class/category implemenations, allMethods/allProperties is
1196// always null.
1197void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
1198                      DeclTy **allMethods, unsigned allNum,
1199                      DeclTy **allProperties, unsigned pNum) {
1200  Decl *ClassDecl = static_cast<Decl *>(classDecl);
1201
1202  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1203  // always passing in a decl. If the decl has an error, isInvalidDecl()
1204  // should be true.
1205  if (!ClassDecl)
1206    return;
1207
1208  bool isInterfaceDeclKind =
1209        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1210         || isa<ObjCProtocolDecl>(ClassDecl);
1211  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1212
1213  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1214
1215  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1216  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1217  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1218
1219  for (unsigned i = 0; i < allNum; i++ ) {
1220    ObjCMethodDecl *Method =
1221      cast_or_null<ObjCMethodDecl>(static_cast<Decl*>(allMethods[i]));
1222
1223    if (!Method) continue;  // Already issued a diagnostic.
1224    if (Method->isInstanceMethod()) {
1225      /// Check for instance method of the same name with incompatible types
1226      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1227      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1228                              : false;
1229      if ((isInterfaceDeclKind && PrevMethod && !match)
1230          || (checkIdenticalMethods && match)) {
1231          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1232            << Method->getDeclName();
1233          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1234      } else {
1235        DC->addDecl(Method);
1236        InsMap[Method->getSelector()] = Method;
1237        /// The following allows us to typecheck messages to "id".
1238        AddInstanceMethodToGlobalPool(Method);
1239      }
1240    }
1241    else {
1242      /// Check for class method of the same name with incompatible types
1243      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1244      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1245                              : false;
1246      if ((isInterfaceDeclKind && PrevMethod && !match)
1247          || (checkIdenticalMethods && match)) {
1248        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1249          << Method->getDeclName();
1250        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1251      } else {
1252        DC->addDecl(Method);
1253        ClsMap[Method->getSelector()] = Method;
1254        /// The following allows us to typecheck messages to "Class".
1255        AddFactoryMethodToGlobalPool(Method);
1256      }
1257    }
1258  }
1259  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1260    // Compares properties declared in this class to those of its
1261    // super class.
1262    ComparePropertiesInBaseAndSuper(I);
1263    MergeProtocolPropertiesIntoClass(I, I);
1264  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1265    // Categories are used to extend the class by declaring new methods.
1266    // By the same token, they are also used to add new properties. No
1267    // need to compare the added property to those in the class.
1268
1269    // Merge protocol properties into category
1270    MergeProtocolPropertiesIntoClass(C, C);
1271  }
1272  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1273    // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1274    // user-defined setter/getter. It also synthesizes setter/getter methods
1275    // and adds them to the DeclContext and global method pools.
1276    for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1277                                          E = CDecl->prop_end(); I != E; ++I)
1278      ProcessPropertyDecl(*I, CDecl);
1279    CDecl->setAtEndLoc(AtEndLoc);
1280  }
1281  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1282    IC->setLocEnd(AtEndLoc);
1283    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
1284      ImplMethodsVsClassMethods(IC, IDecl);
1285  } else if (ObjCCategoryImplDecl* CatImplClass =
1286                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1287    CatImplClass->setLocEnd(AtEndLoc);
1288
1289    // Find category interface decl and then check that all methods declared
1290    // in this interface are implemented in the category @implementation.
1291    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1292      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1293           Categories; Categories = Categories->getNextClassCategory()) {
1294        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1295          ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
1296          break;
1297        }
1298      }
1299    }
1300  }
1301}
1302
1303
1304/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1305/// objective-c's type qualifier from the parser version of the same info.
1306static Decl::ObjCDeclQualifier
1307CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1308  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1309  if (PQTVal & ObjCDeclSpec::DQ_In)
1310    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1311  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1312    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1313  if (PQTVal & ObjCDeclSpec::DQ_Out)
1314    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1315  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1316    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1317  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1318    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1319  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1320    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1321
1322  return ret;
1323}
1324
1325Sema::DeclTy *Sema::ActOnMethodDeclaration(
1326    SourceLocation MethodLoc, SourceLocation EndLoc,
1327    tok::TokenKind MethodType, DeclTy *classDecl,
1328    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1329    Selector Sel,
1330    // optional arguments. The number of types/arguments is obtained
1331    // from the Sel.getNumArgs().
1332    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
1333    llvm::SmallVectorImpl<Declarator> &Cdecls,
1334    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1335    bool isVariadic) {
1336  Decl *ClassDecl = static_cast<Decl*>(classDecl);
1337
1338  // Make sure we can establish a context for the method.
1339  if (!ClassDecl) {
1340    Diag(MethodLoc, diag::error_missing_method_context);
1341    return 0;
1342  }
1343  QualType resultDeclType;
1344
1345  if (ReturnType)
1346    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1347  else // get the type for "id".
1348    resultDeclType = Context.getObjCIdType();
1349
1350  ObjCMethodDecl* ObjCMethod =
1351    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1352                           dyn_cast<DeclContext>(ClassDecl),
1353                           MethodType == tok::minus, isVariadic,
1354                           false,
1355                           MethodDeclKind == tok::objc_optional ?
1356                           ObjCMethodDecl::Optional :
1357                           ObjCMethodDecl::Required);
1358
1359  llvm::SmallVector<ParmVarDecl*, 16> Params;
1360
1361  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
1362    // FIXME: arg->AttrList must be stored too!
1363    QualType argType, originalArgType;
1364
1365    if (ArgTypes[i]) {
1366      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
1367      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1368      if (argType->isArrayType())  { // (char *[]) -> (char **)
1369        originalArgType = argType;
1370        argType = Context.getArrayDecayedType(argType);
1371      }
1372      else if (argType->isFunctionType())
1373        argType = Context.getPointerType(argType);
1374      else if (argType->isObjCInterfaceType()) {
1375        // FIXME! provide more precise location for the parameter
1376        Diag(MethodLoc, diag::err_object_as_method_param);
1377        return 0;
1378      }
1379    } else
1380      argType = Context.getObjCIdType();
1381    ParmVarDecl* Param;
1382    if (originalArgType.isNull())
1383      Param = ParmVarDecl::Create(Context, ObjCMethod,
1384                                  SourceLocation(/*FIXME*/),
1385                                  ArgNames[i], argType,
1386                                  VarDecl::None, 0);
1387    else
1388      Param = OriginalParmVarDecl::Create(Context, ObjCMethod,
1389                                          SourceLocation(/*FIXME*/),
1390                                          ArgNames[i], argType, originalArgType,
1391                                          VarDecl::None, 0);
1392
1393    Param->setObjCDeclQualifier(
1394      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
1395    Params.push_back(Param);
1396  }
1397
1398  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs());
1399  ObjCMethod->setObjCDeclQualifier(
1400    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1401  const ObjCMethodDecl *PrevMethod = 0;
1402
1403  if (AttrList)
1404    ProcessDeclAttributeList(ObjCMethod, AttrList);
1405
1406  // For implementations (which can be very "coarse grain"), we add the
1407  // method now. This allows the AST to implement lookup methods that work
1408  // incrementally (without waiting until we parse the @end). It also allows
1409  // us to flag multiple declaration errors as they occur.
1410  if (ObjCImplementationDecl *ImpDecl =
1411        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1412    if (MethodType == tok::minus) {
1413      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1414      ImpDecl->addInstanceMethod(ObjCMethod);
1415    } else {
1416      PrevMethod = ImpDecl->getClassMethod(Sel);
1417      ImpDecl->addClassMethod(ObjCMethod);
1418    }
1419  }
1420  else if (ObjCCategoryImplDecl *CatImpDecl =
1421            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1422    if (MethodType == tok::minus) {
1423      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1424      CatImpDecl->addInstanceMethod(ObjCMethod);
1425    } else {
1426      PrevMethod = CatImpDecl->getClassMethod(Sel);
1427      CatImpDecl->addClassMethod(ObjCMethod);
1428    }
1429  }
1430  if (PrevMethod) {
1431    // You can never have two method definitions with the same name.
1432    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1433      << ObjCMethod->getDeclName();
1434    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1435  }
1436  return ObjCMethod;
1437}
1438
1439void Sema::CheckObjCPropertyAttributes(QualType PropertyTy,
1440                                       SourceLocation Loc,
1441                                       unsigned &Attributes) {
1442  // FIXME: Improve the reported location.
1443
1444  // readonly and readwrite/assign/retain/copy conflict.
1445  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1446      (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1447                     ObjCDeclSpec::DQ_PR_assign |
1448                     ObjCDeclSpec::DQ_PR_copy |
1449                     ObjCDeclSpec::DQ_PR_retain))) {
1450    const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ?
1451                          "readwrite" :
1452                         (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
1453                          "assign" :
1454                         (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
1455                          "copy" : "retain";
1456
1457    Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ?
1458                 diag::err_objc_property_attr_mutually_exclusive :
1459                 diag::warn_objc_property_attr_mutually_exclusive)
1460      << "readonly" << which;
1461  }
1462
1463  // Check for copy or retain on non-object types.
1464  if ((Attributes & (ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain)) &&
1465      !Context.isObjCObjectPointerType(PropertyTy)) {
1466    Diag(Loc, diag::err_objc_property_requires_object)
1467      << (Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain");
1468    Attributes &= ~(ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain);
1469  }
1470
1471  // Check for more than one of { assign, copy, retain }.
1472  if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
1473    if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1474      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1475        << "assign" << "copy";
1476      Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
1477    }
1478    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1479      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1480        << "assign" << "retain";
1481      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1482    }
1483  } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1484    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1485      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1486        << "copy" << "retain";
1487      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1488    }
1489  }
1490
1491  // Warn if user supplied no assignment attribute, property is
1492  // readwrite, and this is an object type.
1493  if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
1494                      ObjCDeclSpec::DQ_PR_retain)) &&
1495      !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1496      Context.isObjCObjectPointerType(PropertyTy)) {
1497    // Skip this warning in gc-only mode.
1498    if (getLangOptions().getGCMode() != LangOptions::GCOnly)
1499      Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
1500
1501    // If non-gc code warn that this is likely inappropriate.
1502    if (getLangOptions().getGCMode() == LangOptions::NonGC)
1503      Diag(Loc, diag::warn_objc_property_default_assign_on_object);
1504
1505    // FIXME: Implement warning dependent on NSCopying being
1506    // implemented. See also:
1507    // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
1508    // (please trim this list while you are at it).
1509  }
1510}
1511
1512Sema::DeclTy *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
1513                                  FieldDeclarator &FD,
1514                                  ObjCDeclSpec &ODS,
1515                                  Selector GetterSel,
1516                                  Selector SetterSel,
1517                                  DeclTy *ClassCategory,
1518                                  bool *isOverridingProperty,
1519                                  tok::ObjCKeywordKind MethodImplKind) {
1520  unsigned Attributes = ODS.getPropertyAttributes();
1521  bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
1522                      // default is readwrite!
1523                      !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
1524  // property is defaulted to 'assign' if it is readwrite and is
1525  // not retain or copy
1526  bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
1527                   (isReadWrite &&
1528                    !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
1529                    !(Attributes & ObjCDeclSpec::DQ_PR_copy)));
1530  QualType T = GetTypeForDeclarator(FD.D, S);
1531  Decl *ClassDecl = static_cast<Decl *>(ClassCategory);
1532
1533  // May modify Attributes.
1534  CheckObjCPropertyAttributes(T, AtLoc, Attributes);
1535
1536  if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
1537    if (!CDecl->getIdentifier()) {
1538      // This is an anonymous category. property requires special
1539      // handling.
1540      if (ObjCInterfaceDecl *ICDecl = CDecl->getClassInterface()) {
1541        if (ObjCPropertyDecl *PIDecl =
1542            ICDecl->FindPropertyDeclaration(FD.D.getIdentifier())) {
1543          // property 'PIDecl's readonly attribute will be over-ridden
1544          // with anonymous category's readwrite property attribute!
1545          unsigned PIkind = PIDecl->getPropertyAttributes();
1546          if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
1547            if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) !=
1548                (PIkind & ObjCPropertyDecl::OBJC_PR_nonatomic))
1549              Diag(AtLoc, diag::warn_property_attr_mismatch);
1550            PIDecl->makeitReadWriteAttribute();
1551            if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1552              PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1553            if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1554              PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1555            PIDecl->setSetterName(SetterSel);
1556            // FIXME: use a common routine with addPropertyMethods.
1557            ObjCMethodDecl *SetterDecl =
1558              ObjCMethodDecl::Create(Context, AtLoc, AtLoc, SetterSel,
1559                                     Context.VoidTy,
1560                                     ICDecl,
1561                                     true, false, true,
1562                                     ObjCMethodDecl::Required);
1563            ParmVarDecl *Argument = ParmVarDecl::Create(Context,
1564                                                        SetterDecl,
1565                                                        SourceLocation(),
1566                                                        FD.D.getIdentifier(),
1567                                                        T,
1568                                                        VarDecl::None,
1569                                                        0);
1570            SetterDecl->setMethodParams(&Argument, 1);
1571            PIDecl->setSetterMethodDecl(SetterDecl);
1572          }
1573          else
1574            Diag(AtLoc, diag::err_use_continuation_class) << ICDecl->getDeclName();
1575          *isOverridingProperty = true;
1576          return 0;
1577        }
1578        // No matching property found in the main class. Just fall thru
1579        // and add property to the anonymous category. It looks like
1580        // it works as is. This category becomes just like a category
1581        // for its primary class.
1582      } else {
1583          Diag(CDecl->getLocation(), diag::err_continuation_class);
1584          *isOverridingProperty = true;
1585          return 0;
1586      }
1587    }
1588
1589  Type *t = T.getTypePtr();
1590  if (t->isArrayType() || t->isFunctionType())
1591    Diag(AtLoc, diag::err_property_type) << T;
1592
1593  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1594  assert(DC && "ClassDecl is not a DeclContext");
1595  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC, AtLoc,
1596                                                     FD.D.getIdentifier(), T);
1597  DC->addDecl(PDecl);
1598
1599  ProcessDeclAttributes(PDecl, FD.D);
1600
1601  // Regardless of setter/getter attribute, we save the default getter/setter
1602  // selector names in anticipation of declaration of setter/getter methods.
1603  PDecl->setGetterName(GetterSel);
1604  PDecl->setSetterName(SetterSel);
1605
1606  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
1607    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
1608
1609  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
1610    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
1611
1612  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
1613    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
1614
1615  if (isReadWrite)
1616    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
1617
1618  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1619    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1620
1621  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1622    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1623
1624  if (isAssign)
1625    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
1626
1627  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
1628    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
1629
1630  if (MethodImplKind == tok::objc_required)
1631    PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
1632  else if (MethodImplKind == tok::objc_optional)
1633    PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
1634
1635  return PDecl;
1636}
1637
1638/// ActOnPropertyImplDecl - This routine performs semantic checks and
1639/// builds the AST node for a property implementation declaration; declared
1640/// as @synthesize or @dynamic.
1641///
1642Sema::DeclTy *Sema::ActOnPropertyImplDecl(SourceLocation AtLoc,
1643                                          SourceLocation PropertyLoc,
1644                                          bool Synthesize,
1645                                          DeclTy *ClassCatImpDecl,
1646                                          IdentifierInfo *PropertyId,
1647                                          IdentifierInfo *PropertyIvar) {
1648  Decl *ClassImpDecl = static_cast<Decl*>(ClassCatImpDecl);
1649  // Make sure we have a context for the property implementation declaration.
1650  if (!ClassImpDecl) {
1651    Diag(AtLoc, diag::error_missing_property_context);
1652    return 0;
1653  }
1654  ObjCPropertyDecl *property = 0;
1655  ObjCInterfaceDecl* IDecl = 0;
1656  // Find the class or category class where this property must have
1657  // a declaration.
1658  ObjCImplementationDecl *IC = 0;
1659  ObjCCategoryImplDecl* CatImplClass = 0;
1660  if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
1661    IDecl = IC->getClassInterface();
1662    // We always synthesize an interface for an implementation
1663    // without an interface decl. So, IDecl is always non-zero.
1664    assert(IDecl &&
1665           "ActOnPropertyImplDecl - @implementation without @interface");
1666
1667    // Look for this property declaration in the @implementation's @interface
1668    property = IDecl->FindPropertyDeclaration(PropertyId);
1669    if (!property) {
1670      Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
1671      return 0;
1672    }
1673  }
1674  else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
1675    if (Synthesize) {
1676      Diag(AtLoc, diag::error_synthesize_category_decl);
1677      return 0;
1678    }
1679    IDecl = CatImplClass->getClassInterface();
1680    if (!IDecl) {
1681      Diag(AtLoc, diag::error_missing_property_interface);
1682      return 0;
1683    }
1684    ObjCCategoryDecl *Category =
1685      IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
1686
1687    // If category for this implementation not found, it is an error which
1688    // has already been reported eralier.
1689    if (!Category)
1690      return 0;
1691    // Look for this property declaration in @implementation's category
1692    property = Category->FindPropertyDeclaration(PropertyId);
1693    if (!property) {
1694      Diag(PropertyLoc, diag::error_bad_category_property_decl)
1695        << Category->getDeclName();
1696      return 0;
1697    }
1698  }
1699  else {
1700    Diag(AtLoc, diag::error_bad_property_context);
1701    return 0;
1702  }
1703  ObjCIvarDecl *Ivar = 0;
1704  // Check that we have a valid, previously declared ivar for @synthesize
1705  if (Synthesize) {
1706    // @synthesize
1707    if (!PropertyIvar)
1708      PropertyIvar = PropertyId;
1709    // Check that this is a previously declared 'ivar' in 'IDecl' interface
1710    Ivar = IDecl->lookupInstanceVariable(PropertyIvar);
1711    if (!Ivar) {
1712      Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << PropertyId;
1713      return 0;
1714    }
1715    QualType PropType = Context.getCanonicalType(property->getType());
1716    QualType IvarType = Context.getCanonicalType(Ivar->getType());
1717
1718    // Check that type of property and its ivar are type compatible.
1719    if (PropType != IvarType) {
1720      if (CheckAssignmentConstraints(PropType, IvarType) != Compatible) {
1721        Diag(PropertyLoc, diag::error_property_ivar_type)
1722          << property->getDeclName() << Ivar->getDeclName();
1723        return 0;
1724      }
1725      else {
1726        // FIXME! Rules for properties are somewhat different that those
1727        // for assignments. Use a new routine to consolidate all cases;
1728        // specifically for property redeclarations as well as for ivars.
1729        QualType lhsType =
1730                    Context.getCanonicalType(PropType).getUnqualifiedType();
1731        QualType rhsType =
1732                    Context.getCanonicalType(IvarType).getUnqualifiedType();
1733        if (lhsType != rhsType &&
1734            lhsType->isArithmeticType()) {
1735          Diag(PropertyLoc, diag::error_property_ivar_type)
1736          << property->getDeclName() << Ivar->getDeclName();
1737          return 0;
1738        }
1739      }
1740    }
1741  } else if (PropertyIvar) {
1742    // @dynamic
1743    Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
1744    return 0;
1745  }
1746  assert (property && "ActOnPropertyImplDecl - property declaration missing");
1747  ObjCPropertyImplDecl *PIDecl =
1748    ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc,
1749                                 property,
1750                                 (Synthesize ?
1751                                  ObjCPropertyImplDecl::Synthesize
1752                                  : ObjCPropertyImplDecl::Dynamic),
1753                                 Ivar);
1754  CurContext->addDecl(PIDecl);
1755  if (IC) {
1756    if (Synthesize)
1757      if (ObjCPropertyImplDecl *PPIDecl =
1758          IC->FindPropertyImplIvarDecl(PropertyIvar)) {
1759        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1760          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1761          << PropertyIvar;
1762        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1763      }
1764
1765    if (ObjCPropertyImplDecl *PPIDecl = IC->FindPropertyImplDecl(PropertyId)) {
1766      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1767      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1768      return 0;
1769    }
1770    IC->addPropertyImplementation(PIDecl);
1771  }
1772  else {
1773    if (Synthesize)
1774      if (ObjCPropertyImplDecl *PPIDecl =
1775          CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
1776        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1777          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1778          << PropertyIvar;
1779        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1780      }
1781
1782    if (ObjCPropertyImplDecl *PPIDecl =
1783          CatImplClass->FindPropertyImplDecl(PropertyId)) {
1784      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1785      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1786      return 0;
1787    }
1788    CatImplClass->addPropertyImplementation(PIDecl);
1789  }
1790
1791  return PIDecl;
1792}
1793
1794bool Sema::CheckObjCDeclScope(Decl *D) {
1795  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1796    return false;
1797
1798  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1799  D->setInvalidDecl();
1800
1801  return true;
1802}
1803
1804/// Collect the instance variables declared in an Objective-C object.  Used in
1805/// the creation of structures from objects using the @defs directive.
1806/// FIXME: This should be consolidated with CollectObjCIvars as it is also
1807/// part of the AST generation logic of @defs.
1808static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
1809                         ASTContext& Ctx,
1810                         llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
1811  if (Class->getSuperClass())
1812    CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
1813
1814  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1815  for (ObjCInterfaceDecl::ivar_iterator
1816       I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1817
1818    ObjCIvarDecl* ID = *I;
1819    ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, Record,
1820                                                ID->getLocation(),
1821                                                ID->getIdentifier(),
1822                                                ID->getType(),
1823                                                ID->getBitWidth()));
1824  }
1825}
1826
1827/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1828/// instance variables of ClassName into Decls.
1829void Sema::ActOnDefs(Scope *S, DeclTy *TagD, SourceLocation DeclStart,
1830                     IdentifierInfo *ClassName,
1831                     llvm::SmallVectorImpl<DeclTy*> &Decls) {
1832  // Check that ClassName is a valid class
1833  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1834  if (!Class) {
1835    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1836    return;
1837  }
1838  // Collect the instance variables
1839  CollectIvars(Class, dyn_cast<RecordDecl>((Decl*)TagD), Context, Decls);
1840
1841  // Introduce all of these fields into the appropriate scope.
1842  for (llvm::SmallVectorImpl<DeclTy*>::iterator D = Decls.begin();
1843       D != Decls.end(); ++D) {
1844    FieldDecl *FD = cast<FieldDecl>((Decl*)*D);
1845    if (getLangOptions().CPlusPlus)
1846      PushOnScopeChains(cast<FieldDecl>(FD), S);
1847    else if (RecordDecl *Record = dyn_cast<RecordDecl>((Decl*)TagD))
1848      Record->addDecl(FD);
1849  }
1850}
1851
1852