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