SemaDeclObjC.cpp revision e13b9595dc1e2f4288bec34f3412359f648e84a5
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/Scope.h"
18
19using namespace clang;
20
21/// ObjCActOnStartOfMethodDef - This routine sets up parameters; invisible
22/// and user declared, in the method definition's AST.
23void Sema::ObjCActOnStartOfMethodDef(Scope *FnBodyScope, DeclTy *D) {
24  assert(getCurMethodDecl() == 0 && "Method parsing confused");
25  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>((Decl *)D);
26
27  // If we don't have a valid method decl, simply return.
28  if (!MDecl)
29    return;
30
31  // Allow the rest of sema to find private method decl implementations.
32  if (MDecl->isInstance())
33    AddInstanceMethodToGlobalPool(MDecl);
34  else
35    AddFactoryMethodToGlobalPool(MDecl);
36
37  // Allow all of Sema to see that we are entering a method definition.
38  PushDeclContext(MDecl);
39
40  // Create Decl objects for each parameter, entrring them in the scope for
41  // binding to their use.
42  struct DeclaratorChunk::ParamInfo PI;
43
44  // Insert the invisible arguments, self and _cmd!
45  PI.Ident = &Context.Idents.get("self");
46  PI.IdentLoc = SourceLocation(); // synthesized vars have a null location.
47  QualType selfTy;
48  if (MDecl->isInstance()) {
49    selfTy = Context.getObjCIdType();
50    if (ObjCInterfaceDecl *OID = MDecl->getClassInterface()) {
51      // There may be no interface context due to error in declaration of the
52      // interface (which has been reported). Recover gracefully
53      selfTy = Context.getObjCInterfaceType(OID);
54      selfTy = Context.getPointerType(selfTy);
55    }
56  } else // we have a factory method.
57    selfTy = Context.getObjCClassType();
58  getCurMethodDecl()->setSelfDecl(CreateImplicitParameter(FnBodyScope,
59        PI.Ident, PI.IdentLoc, selfTy));
60
61  PI.Ident = &Context.Idents.get("_cmd");
62  getCurMethodDecl()->setCmdDecl(CreateImplicitParameter(FnBodyScope,
63        PI.Ident, PI.IdentLoc, Context.getObjCSelType()));
64
65  // Introduce all of the other parameters into this scope.
66  for (unsigned i = 0, e = MDecl->getNumParams(); i != e; ++i) {
67    ParmVarDecl *PDecl = MDecl->getParamDecl(i);
68    IdentifierInfo *II = PDecl->getIdentifier();
69    if (II)
70      PushOnScopeChains(PDecl, FnBodyScope);
71  }
72}
73
74Sema::DeclTy *Sema::
75ActOnStartClassInterface(SourceLocation AtInterfaceLoc,
76                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
77                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
78                         const IdentifierLocPair *ProtocolNames,
79                         unsigned NumProtocols,
80                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
81  assert(ClassName && "Missing class identifier");
82
83  // Check for another declaration kind with the same name.
84  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
85  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
86    Diag(ClassLoc, diag::err_redefinition_different_kind,
87         ClassName->getName());
88    Diag(PrevDecl->getLocation(), diag::err_previous_definition);
89  }
90
91  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
92  if (IDecl) {
93    // Class already seen. Is it a forward declaration?
94    if (!IDecl->isForwardDecl())
95      Diag(AtInterfaceLoc, diag::err_duplicate_class_def, IDecl->getName());
96    else {
97      IDecl->setLocation(AtInterfaceLoc);
98      IDecl->setForwardDecl(false);
99    }
100  } else {
101    IDecl = ObjCInterfaceDecl::Create(Context, AtInterfaceLoc,
102                                      ClassName, ClassLoc);
103
104    ObjCInterfaceDecls[ClassName] = IDecl;
105    // Remember that this needs to be removed when the scope is popped.
106    TUScope->AddDecl(IDecl);
107  }
108
109  if (SuperName) {
110    ObjCInterfaceDecl* SuperClassEntry = 0;
111    // Check if a different kind of symbol declared in this scope.
112    PrevDecl = LookupDecl(SuperName, Decl::IDNS_Ordinary, TUScope);
113    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
114      Diag(SuperLoc, diag::err_redefinition_different_kind,
115           SuperName->getName());
116      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
117    }
118    else {
119      // Check that super class is previously defined
120      SuperClassEntry = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
121
122      if (!SuperClassEntry || SuperClassEntry->isForwardDecl()) {
123        Diag(SuperLoc, diag::err_undef_superclass,
124             SuperClassEntry ? SuperClassEntry->getName()
125                             : SuperName->getName(),
126             ClassName->getName(), SourceRange(AtInterfaceLoc, ClassLoc));
127      }
128    }
129    IDecl->setSuperClass(SuperClassEntry);
130    IDecl->setSuperClassLoc(SuperLoc);
131    IDecl->setLocEnd(SuperLoc);
132  } else { // we have a root class.
133    IDecl->setLocEnd(ClassLoc);
134  }
135
136  /// Check then save referenced protocols
137  if (NumProtocols) {
138    llvm::SmallVector<ObjCProtocolDecl*, 8> RefProtos;
139    for (unsigned int i = 0; i != NumProtocols; i++) {
140      ObjCProtocolDecl* RefPDecl = ObjCProtocols[ProtocolNames[i].first];
141      if (!RefPDecl)
142        Diag(ProtocolNames[i].second, diag::err_undeclared_protocol,
143             ProtocolNames[i].first->getName());
144      else {
145        if (RefPDecl->isForwardDecl())
146          Diag(ProtocolNames[i].second, diag::warn_undef_protocolref,
147               ProtocolNames[i].first->getName());
148        RefProtos.push_back(RefPDecl);
149      }
150    }
151    if (!RefProtos.empty())
152      IDecl->addReferencedProtocols(&RefProtos[0], RefProtos.size());
153    IDecl->setLocEnd(EndProtoLoc);
154  }
155  return IDecl;
156}
157
158/// ActOnCompatiblityAlias - this action is called after complete parsing of
159/// @compaatibility_alias declaration. It sets up the alias relationships.
160Sema::DeclTy *Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
161                                           IdentifierInfo *AliasName,
162                                           SourceLocation AliasLocation,
163                                           IdentifierInfo *ClassName,
164                                           SourceLocation ClassLocation) {
165  // Look for previous declaration of alias name
166  Decl *ADecl = LookupDecl(AliasName, Decl::IDNS_Ordinary, TUScope);
167  if (ADecl) {
168    if (isa<ObjCCompatibleAliasDecl>(ADecl)) {
169      Diag(AliasLocation, diag::warn_previous_alias_decl);
170      Diag(ADecl->getLocation(), diag::warn_previous_declaration);
171    }
172    else {
173      Diag(AliasLocation, diag::err_conflicting_aliasing_type,
174           AliasName->getName());
175      Diag(ADecl->getLocation(), diag::err_previous_declaration);
176    }
177    return 0;
178  }
179  // Check for class declaration
180  Decl *CDeclU = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
181  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
182  if (CDecl == 0) {
183    Diag(ClassLocation, diag::warn_undef_interface, ClassName->getName());
184    if (CDeclU)
185      Diag(CDeclU->getLocation(), diag::warn_previous_declaration);
186    return 0;
187  }
188
189  // Everything checked out, instantiate a new alias declaration AST.
190  ObjCCompatibleAliasDecl *AliasDecl =
191    ObjCCompatibleAliasDecl::Create(Context, AtLoc, AliasName, CDecl);
192
193  ObjCAliasDecls[AliasName] = AliasDecl;
194  TUScope->AddDecl(AliasDecl);
195  return AliasDecl;
196}
197
198Sema::DeclTy *
199Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
200                                  IdentifierInfo *ProtocolName,
201                                  SourceLocation ProtocolLoc,
202                                  DeclTy * const *ProtoRefs,
203                                  unsigned NumProtoRefs,
204                                  SourceLocation EndProtoLoc) {
205  assert(ProtocolName && "Missing protocol identifier");
206  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
207  if (PDecl) {
208    // Protocol already seen. Better be a forward protocol declaration
209    if (!PDecl->isForwardDecl()) {
210      Diag(ProtocolLoc, diag::err_duplicate_protocol_def,
211           ProtocolName->getName());
212      // Just return the protocol we already had.
213      // FIXME: don't leak the objects passed in!
214      return PDecl;
215    }
216
217    PDecl->setForwardDecl(false);
218  } else {
219    PDecl = ObjCProtocolDecl::Create(Context, AtProtoInterfaceLoc,ProtocolName);
220    PDecl->setForwardDecl(false);
221    ObjCProtocols[ProtocolName] = PDecl;
222  }
223
224  if (NumProtoRefs) {
225    /// Check then save referenced protocols.
226    PDecl->addReferencedProtocols((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs);
227    PDecl->setLocEnd(EndProtoLoc);
228  }
229  return PDecl;
230}
231
232/// FindProtocolDeclaration - This routine looks up protocols and
233/// issuer error if they are not declared. It returns list of protocol
234/// declarations in its 'Protocols' argument.
235void
236Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
237                              const IdentifierLocPair *ProtocolId,
238                              unsigned NumProtocols,
239                              llvm::SmallVectorImpl<DeclTy*> &Protocols) {
240  for (unsigned i = 0; i != NumProtocols; ++i) {
241    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i].first];
242    if (!PDecl) {
243      Diag(ProtocolId[i].second, diag::err_undeclared_protocol,
244           ProtocolId[i].first->getName());
245      continue;
246    }
247
248    // If this is a forward declaration and we are supposed to warn in this
249    // case, do it.
250    if (WarnOnDeclarations && PDecl->isForwardDecl())
251      Diag(ProtocolId[i].second, diag::warn_undef_protocolref,
252           ProtocolId[i].first->getName());
253    Protocols.push_back(PDecl);
254  }
255}
256
257/// DiagnosePropertyMismatch - Compares two properties for their
258/// attributes and types and warns on a variety of inconsistancies.
259///
260void
261Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
262                               ObjCPropertyDecl *SuperProperty,
263                               const char *inheritedName) {
264  ObjCPropertyDecl::PropertyAttributeKind CAttr =
265  Property->getPropertyAttributes();
266  ObjCPropertyDecl::PropertyAttributeKind SAttr =
267  SuperProperty->getPropertyAttributes();
268  if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
269      && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
270    Diag(Property->getLocation(), diag::warn_readonly_property,
271               Property->getName(), inheritedName);
272  if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
273      != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
274    Diag(Property->getLocation(), diag::warn_property_attribute,
275         Property->getName(), "copy", inheritedName,
276         SourceRange());
277  else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain)
278           != (SAttr & ObjCPropertyDecl::OBJC_PR_retain))
279    Diag(Property->getLocation(), diag::warn_property_attribute,
280         Property->getName(), "retain", inheritedName,
281         SourceRange());
282
283  if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
284      != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
285    Diag(Property->getLocation(), diag::warn_property_attribute,
286         Property->getName(), "atomic", inheritedName,
287         SourceRange());
288  if (Property->getSetterName() != SuperProperty->getSetterName())
289    Diag(Property->getLocation(), diag::warn_property_attribute,
290         Property->getName(), "setter", inheritedName,
291         SourceRange());
292  if (Property->getGetterName() != SuperProperty->getGetterName())
293    Diag(Property->getLocation(), diag::warn_property_attribute,
294         Property->getName(), "getter", inheritedName,
295         SourceRange());
296
297  if (Property->getCanonicalType() != SuperProperty->getCanonicalType())
298    Diag(Property->getLocation(), diag::warn_property_type,
299         Property->getType().getAsString(),
300         inheritedName);
301
302}
303
304/// ComparePropertiesInBaseAndSuper - This routine compares property
305/// declarations in base and its super class, if any, and issues
306/// diagnostics in a variety of inconsistant situations.
307///
308void
309Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
310  ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
311  if (!SDecl)
312    return;
313  for (ObjCInterfaceDecl::classprop_iterator S = SDecl->classprop_begin(),
314       E = SDecl->classprop_end(); S != E; ++S) {
315    ObjCPropertyDecl *SuperPDecl = (*S);
316    // Does property in super class has declaration in current class?
317    for (ObjCInterfaceDecl::classprop_iterator I = IDecl->classprop_begin(),
318         E = IDecl->classprop_end(); I != E; ++I) {
319      ObjCPropertyDecl *PDecl = (*I);
320      if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
321          DiagnosePropertyMismatch(PDecl, SuperPDecl, SDecl->getName());
322    }
323  }
324}
325
326/// MergeOneProtocolPropertiesIntoClass - This routine goes thru the list
327/// of properties declared in a protocol and adds them to the list
328/// of properties for current class if it is not there already.
329void
330Sema::MergeOneProtocolPropertiesIntoClass(ObjCInterfaceDecl *IDecl,
331                                          ObjCProtocolDecl *PDecl)
332{
333  llvm::SmallVector<ObjCPropertyDecl*, 16> mergeProperties;
334  for (ObjCProtocolDecl::classprop_iterator P = PDecl->classprop_begin(),
335       E = PDecl->classprop_end(); P != E; ++P) {
336    ObjCPropertyDecl *Pr = (*P);
337    ObjCInterfaceDecl::classprop_iterator CP, CE;
338    // Is this property already in  class's list of properties?
339    for (CP = IDecl->classprop_begin(), CE = IDecl->classprop_end();
340         CP != CE; ++CP)
341      if ((*CP)->getIdentifier() == Pr->getIdentifier())
342        break;
343    if (CP == CE)
344      // Add this property to list of properties for thie class.
345      mergeProperties.push_back(Pr);
346    else
347      // Property protocol already exist in class. Diagnose any mismatch.
348      DiagnosePropertyMismatch((*CP), Pr, PDecl->getName());
349    }
350  IDecl->mergeProperties(&mergeProperties[0], mergeProperties.size());
351}
352
353/// MergeProtocolPropertiesIntoClass - This routine merges properties
354/// declared in 'MergeItsProtocols' objects (which can be a class or an
355/// inherited protocol into the list of properties for class 'IDecl'
356///
357
358void
359Sema::MergeProtocolPropertiesIntoClass(ObjCInterfaceDecl *IDecl,
360                                       DeclTy *MergeItsProtocols) {
361  Decl *ClassDecl = static_cast<Decl *>(MergeItsProtocols);
362  if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
363    for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(),
364         E = MDecl->protocol_end(); P != E; ++P)
365      // Merge properties of class (*P) into IDECL's
366      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
367
368    // Go thru the list of protocols for this class and recursively merge
369    // their properties into this class as well.
370    for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(),
371         E = IDecl->protocol_end(); P != E; ++P)
372      MergeProtocolPropertiesIntoClass(IDecl, *P);
373  } else {
374    ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
375    for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
376         E = MD->protocol_end(); P != E; ++P)
377      MergeOneProtocolPropertiesIntoClass(IDecl, (*P));
378  }
379}
380
381/// ActOnForwardProtocolDeclaration -
382Action::DeclTy *
383Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
384                                      const IdentifierLocPair *IdentList,
385                                      unsigned NumElts) {
386  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
387
388  for (unsigned i = 0; i != NumElts; ++i) {
389    IdentifierInfo *Ident = IdentList[i].first;
390    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
391    if (PDecl == 0) // Not already seen?
392      PDecl = ObjCProtocolDecl::Create(Context, IdentList[i].second, Ident);
393
394    Protocols.push_back(PDecl);
395  }
396  return ObjCForwardProtocolDecl::Create(Context, AtProtocolLoc,
397                                         &Protocols[0], Protocols.size());
398}
399
400Sema::DeclTy *Sema::
401ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
402                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
403                            IdentifierInfo *CategoryName,
404                            SourceLocation CategoryLoc,
405                            const IdentifierLocPair *ProtoRefNames,
406                            unsigned NumProtoRefs,
407                            SourceLocation EndProtoLoc) {
408  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
409
410  ObjCCategoryDecl *CDecl =
411    ObjCCategoryDecl::Create(Context, AtInterfaceLoc, CategoryName);
412  CDecl->setClassInterface(IDecl);
413
414  /// Check that class of this category is already completely declared.
415  if (!IDecl || IDecl->isForwardDecl())
416    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
417  else {
418    /// Check for duplicate interface declaration for this category
419    ObjCCategoryDecl *CDeclChain;
420    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
421         CDeclChain = CDeclChain->getNextClassCategory()) {
422      if (CategoryName && CDeclChain->getIdentifier() == CategoryName) {
423        Diag(CategoryLoc, diag::warn_dup_category_def, ClassName->getName(),
424             CategoryName->getName());
425        break;
426      }
427    }
428    if (!CDeclChain)
429      CDecl->insertNextClassCategory();
430  }
431
432  if (NumProtoRefs) {
433    llvm::SmallVector<ObjCProtocolDecl*, 32> RefProtocols;
434    /// Check and then save the referenced protocols.
435    for (unsigned int i = 0; i != NumProtoRefs; i++) {
436      ObjCProtocolDecl* RefPDecl = ObjCProtocols[ProtoRefNames[i].first];
437      if (!RefPDecl)
438        Diag(ProtoRefNames[i].second, diag::err_undeclared_protocol,
439             ProtoRefNames[i].first->getName());
440      else {
441        if (RefPDecl->isForwardDecl())
442          Diag(ProtoRefNames[i].second, diag::warn_undef_protocolref,
443               ProtoRefNames[i].first->getName());
444        RefProtocols.push_back(RefPDecl);
445      }
446    }
447    if (!RefProtocols.empty())
448      CDecl->addReferencedProtocols(&RefProtocols[0], RefProtocols.size());
449  }
450  CDecl->setLocEnd(EndProtoLoc);
451  return CDecl;
452}
453
454/// ActOnStartCategoryImplementation - Perform semantic checks on the
455/// category implementation declaration and build an ObjCCategoryImplDecl
456/// object.
457Sema::DeclTy *Sema::ActOnStartCategoryImplementation(
458                      SourceLocation AtCatImplLoc,
459                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
460                      IdentifierInfo *CatName, SourceLocation CatLoc) {
461  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
462  ObjCCategoryImplDecl *CDecl =
463    ObjCCategoryImplDecl::Create(Context, AtCatImplLoc, CatName, IDecl);
464  /// Check that class of this category is already completely declared.
465  if (!IDecl || IDecl->isForwardDecl())
466    Diag(ClassLoc, diag::err_undef_interface, ClassName->getName());
467
468  /// TODO: Check that CatName, category name, is not used in another
469  // implementation.
470  return CDecl;
471}
472
473Sema::DeclTy *Sema::ActOnStartClassImplementation(
474                      SourceLocation AtClassImplLoc,
475                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
476                      IdentifierInfo *SuperClassname,
477                      SourceLocation SuperClassLoc) {
478  ObjCInterfaceDecl* IDecl = 0;
479  // Check for another declaration kind with the same name.
480  Decl *PrevDecl = LookupDecl(ClassName, Decl::IDNS_Ordinary, TUScope);
481  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
482    Diag(ClassLoc, diag::err_redefinition_different_kind,
483         ClassName->getName());
484    Diag(PrevDecl->getLocation(), diag::err_previous_definition);
485  }
486  else {
487    // Is there an interface declaration of this class; if not, warn!
488    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
489    if (!IDecl)
490      Diag(ClassLoc, diag::warn_undef_interface, ClassName->getName());
491  }
492
493  // Check that super class name is valid class name
494  ObjCInterfaceDecl* SDecl = 0;
495  if (SuperClassname) {
496    // Check if a different kind of symbol declared in this scope.
497    PrevDecl = LookupDecl(SuperClassname, Decl::IDNS_Ordinary, TUScope);
498    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
499      Diag(SuperClassLoc, diag::err_redefinition_different_kind,
500           SuperClassname->getName());
501      Diag(PrevDecl->getLocation(), diag::err_previous_definition);
502    }
503    else {
504      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
505      if (!SDecl)
506        Diag(SuperClassLoc, diag::err_undef_superclass,
507             SuperClassname->getName(), ClassName->getName());
508      else if (IDecl && IDecl->getSuperClass() != SDecl) {
509        // This implementation and its interface do not have the same
510        // super class.
511        Diag(SuperClassLoc, diag::err_conflicting_super_class,
512             SDecl->getName());
513        Diag(SDecl->getLocation(), diag::err_previous_definition);
514      }
515    }
516  }
517
518  if (!IDecl) {
519    // Legacy case of @implementation with no corresponding @interface.
520    // Build, chain & install the interface decl into the identifier.
521    IDecl = ObjCInterfaceDecl::Create(Context, AtClassImplLoc, ClassName,
522                                      ClassLoc, false, true);
523    ObjCInterfaceDecls[ClassName] = IDecl;
524    IDecl->setSuperClass(SDecl);
525    IDecl->setLocEnd(ClassLoc);
526
527    // Remember that this needs to be removed when the scope is popped.
528    TUScope->AddDecl(IDecl);
529  }
530
531  ObjCImplementationDecl* IMPDecl =
532    ObjCImplementationDecl::Create(Context, AtClassImplLoc, ClassName,
533                                   IDecl, SDecl);
534
535  // Check that there is no duplicate implementation of this class.
536  if (ObjCImplementations[ClassName])
537    // FIXME: Don't leak everything!
538    Diag(ClassLoc, diag::err_dup_implementation_class, ClassName->getName());
539  else // add it to the list.
540    ObjCImplementations[ClassName] = IMPDecl;
541  return IMPDecl;
542}
543
544void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
545                                    ObjCIvarDecl **ivars, unsigned numIvars,
546                                    SourceLocation RBrace) {
547  assert(ImpDecl && "missing implementation decl");
548  ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(ImpDecl->getIdentifier());
549  if (!IDecl)
550    return;
551  /// Check case of non-existing @interface decl.
552  /// (legacy objective-c @implementation decl without an @interface decl).
553  /// Add implementations's ivar to the synthesize class's ivar list.
554  if (IDecl->ImplicitInterfaceDecl()) {
555    IDecl->addInstanceVariablesToClass(ivars, numIvars, RBrace);
556    return;
557  }
558  // If implementation has empty ivar list, just return.
559  if (numIvars == 0)
560    return;
561
562  assert(ivars && "missing @implementation ivars");
563
564  // Check interface's Ivar list against those in the implementation.
565  // names and types must match.
566  //
567  unsigned j = 0;
568  ObjCInterfaceDecl::ivar_iterator
569    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
570  for (; numIvars > 0 && IVI != IVE; ++IVI) {
571    ObjCIvarDecl* ImplIvar = ivars[j++];
572    ObjCIvarDecl* ClsIvar = *IVI;
573    assert (ImplIvar && "missing implementation ivar");
574    assert (ClsIvar && "missing class ivar");
575    if (ImplIvar->getCanonicalType() != ClsIvar->getCanonicalType()) {
576      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type,
577           ImplIvar->getIdentifier()->getName());
578      Diag(ClsIvar->getLocation(), diag::err_previous_definition,
579           ClsIvar->getIdentifier()->getName());
580    }
581    // TODO: Two mismatched (unequal width) Ivar bitfields should be diagnosed
582    // as error.
583    else if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
584      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name,
585           ImplIvar->getIdentifier()->getName());
586      Diag(ClsIvar->getLocation(), diag::err_previous_definition,
587           ClsIvar->getIdentifier()->getName());
588      return;
589    }
590    --numIvars;
591  }
592
593  if (numIvars > 0)
594    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
595  else if (IVI != IVE)
596    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
597}
598
599void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
600                               bool &IncompleteImpl) {
601  if (!IncompleteImpl) {
602    Diag(ImpLoc, diag::warn_incomplete_impl);
603    IncompleteImpl = true;
604  }
605  Diag(ImpLoc, diag::warn_undef_method_impl, method->getSelector().getName());
606}
607
608/// CheckProtocolMethodDefs - This routine checks unimplemented methods
609/// Declared in protocol, and those referenced by it.
610void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
611                                   ObjCProtocolDecl *PDecl,
612                                   bool& IncompleteImpl,
613                                   const llvm::DenseSet<Selector> &InsMap,
614                                   const llvm::DenseSet<Selector> &ClsMap) {
615  // check unimplemented instance methods.
616  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
617       E = PDecl->instmeth_end(); I != E; ++I) {
618    ObjCMethodDecl *method = *I;
619    if (!InsMap.count(method->getSelector()) &&
620        method->getImplementationControl() != ObjCMethodDecl::Optional)
621      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
622  }
623  // check unimplemented class methods
624  for (ObjCProtocolDecl::classmeth_iterator I = PDecl->classmeth_begin(),
625       E = PDecl->classmeth_end(); I != E; ++I) {
626    ObjCMethodDecl *method = *I;
627    if (!ClsMap.count(method->getSelector()) &&
628        method->getImplementationControl() != ObjCMethodDecl::Optional)
629      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
630  }
631  // Check on this protocols's referenced protocols, recursively.
632  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
633       E = PDecl->protocol_end(); PI != E; ++PI)
634    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap);
635}
636
637void Sema::ImplMethodsVsClassMethods(ObjCImplementationDecl* IMPDecl,
638                                     ObjCInterfaceDecl* IDecl) {
639  llvm::DenseSet<Selector> InsMap;
640  // Check and see if instance methods in class interface have been
641  // implemented in the implementation class.
642  for (ObjCImplementationDecl::instmeth_iterator I = IMPDecl->instmeth_begin(),
643       E = IMPDecl->instmeth_end(); I != E; ++I)
644    InsMap.insert((*I)->getSelector());
645
646  bool IncompleteImpl = false;
647  for (ObjCInterfaceDecl::instmeth_iterator I = IDecl->instmeth_begin(),
648       E = IDecl->instmeth_end(); I != E; ++I)
649    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector()))
650      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
651
652  llvm::DenseSet<Selector> ClsMap;
653  // Check and see if class methods in class interface have been
654  // implemented in the implementation class.
655  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
656       E = IMPDecl->classmeth_end(); I != E; ++I)
657    ClsMap.insert((*I)->getSelector());
658
659  for (ObjCInterfaceDecl::classmeth_iterator I = IDecl->classmeth_begin(),
660       E = IDecl->classmeth_end(); I != E; ++I)
661    if (!ClsMap.count((*I)->getSelector()))
662      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
663
664  // Check the protocol list for unimplemented methods in the @implementation
665  // class.
666  const ObjCList<ObjCProtocolDecl> &Protocols =
667    IDecl->getReferencedProtocols();
668  for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
669       E = Protocols.end(); I != E; ++I)
670    CheckProtocolMethodDefs(IMPDecl->getLocation(), *I,
671                            IncompleteImpl, InsMap, ClsMap);
672}
673
674/// ImplCategoryMethodsVsIntfMethods - Checks that methods declared in the
675/// category interface is implemented in the category @implementation.
676void Sema::ImplCategoryMethodsVsIntfMethods(ObjCCategoryImplDecl *CatImplDecl,
677                                            ObjCCategoryDecl *CatClassDecl) {
678  llvm::DenseSet<Selector> InsMap;
679  // Check and see if instance methods in category interface have been
680  // implemented in its implementation class.
681  for (ObjCCategoryImplDecl::instmeth_iterator I =CatImplDecl->instmeth_begin(),
682       E = CatImplDecl->instmeth_end(); I != E; ++I)
683    InsMap.insert((*I)->getSelector());
684
685  bool IncompleteImpl = false;
686  for (ObjCCategoryDecl::instmeth_iterator I = CatClassDecl->instmeth_begin(),
687       E = CatClassDecl->instmeth_end(); I != E; ++I)
688    if (!InsMap.count((*I)->getSelector()))
689      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
690
691  llvm::DenseSet<Selector> ClsMap;
692  // Check and see if class methods in category interface have been
693  // implemented in its implementation class.
694  for (ObjCCategoryImplDecl::classmeth_iterator
695       I = CatImplDecl->classmeth_begin(), E = CatImplDecl->classmeth_end();
696       I != E; ++I)
697    ClsMap.insert((*I)->getSelector());
698
699  for (ObjCCategoryDecl::classmeth_iterator I = CatClassDecl->classmeth_begin(),
700       E = CatClassDecl->classmeth_end(); I != E; ++I)
701    if (!ClsMap.count((*I)->getSelector()))
702      WarnUndefinedMethod(CatImplDecl->getLocation(), *I, IncompleteImpl);
703
704  // Check the protocol list for unimplemented methods in the @implementation
705  // class.
706  for (ObjCCategoryDecl::protocol_iterator PI = CatClassDecl->protocol_begin(),
707       E = CatClassDecl->protocol_end(); PI != E; ++PI)
708    CheckProtocolMethodDefs(CatImplDecl->getLocation(), *PI, IncompleteImpl,
709                            InsMap, ClsMap);
710}
711
712/// ActOnForwardClassDeclaration -
713Action::DeclTy *
714Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
715                                   IdentifierInfo **IdentList, unsigned NumElts)
716{
717  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
718
719  for (unsigned i = 0; i != NumElts; ++i) {
720    // Check for another declaration kind with the same name.
721    Decl *PrevDecl = LookupDecl(IdentList[i], Decl::IDNS_Ordinary, TUScope);
722    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
723      // GCC apparently allows the following idiom:
724      //
725      // typedef NSObject < XCElementTogglerP > XCElementToggler;
726      // @class XCElementToggler;
727      //
728      // FIXME: Make an extension?
729      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
730      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
731        Diag(AtClassLoc, diag::err_redefinition_different_kind,
732             IdentList[i]->getName());
733        Diag(PrevDecl->getLocation(), diag::err_previous_definition);
734      }
735    }
736    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
737    if (!IDecl) {  // Not already seen?  Make a forward decl.
738      IDecl = ObjCInterfaceDecl::Create(Context, AtClassLoc, IdentList[i],
739                                        SourceLocation(), true);
740      ObjCInterfaceDecls[IdentList[i]] = IDecl;
741
742      // Remember that this needs to be removed when the scope is popped.
743      TUScope->AddDecl(IDecl);
744    }
745
746    Interfaces.push_back(IDecl);
747  }
748
749  return ObjCClassDecl::Create(Context, AtClassLoc,
750                               &Interfaces[0], Interfaces.size());
751}
752
753
754/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
755/// returns true, or false, accordingly.
756/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
757bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
758                                      const ObjCMethodDecl *PrevMethod) {
759  if (Method->getResultType().getCanonicalType() !=
760      PrevMethod->getResultType().getCanonicalType())
761    return false;
762  for (unsigned i = 0, e = Method->getNumParams(); i != e; ++i) {
763    ParmVarDecl *ParamDecl = Method->getParamDecl(i);
764    ParmVarDecl *PrevParamDecl = PrevMethod->getParamDecl(i);
765    if (Context.getCanonicalType(ParamDecl->getType()) !=
766        Context.getCanonicalType(PrevParamDecl->getType()))
767      return false;
768  }
769  return true;
770}
771
772void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
773  ObjCMethodList &FirstMethod = InstanceMethodPool[Method->getSelector()];
774  if (!FirstMethod.Method) {
775    // Haven't seen a method with this selector name yet - add it.
776    FirstMethod.Method = Method;
777    FirstMethod.Next = 0;
778  } else {
779    // We've seen a method with this name, now check the type signature(s).
780    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
781
782    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
783         Next = Next->Next)
784      match = MatchTwoMethodDeclarations(Method, Next->Method);
785
786    if (!match) {
787      // We have a new signature for an existing method - add it.
788      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
789      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
790      FirstMethod.Next = OMI;
791    }
792  }
793}
794
795void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
796  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
797  if (!FirstMethod.Method) {
798    // Haven't seen a method with this selector name yet - add it.
799    FirstMethod.Method = Method;
800    FirstMethod.Next = 0;
801  } else {
802    // We've seen a method with this name, now check the type signature(s).
803    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
804
805    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
806         Next = Next->Next)
807      match = MatchTwoMethodDeclarations(Method, Next->Method);
808
809    if (!match) {
810      // We have a new signature for an existing method - add it.
811      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
812      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
813      FirstMethod.Next = OMI;
814    }
815  }
816}
817
818// Note: For class/category implemenations, allMethods/allProperties is
819// always null.
820void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclTy *classDecl,
821                      DeclTy **allMethods, unsigned allNum,
822                      DeclTy **allProperties, unsigned pNum) {
823  Decl *ClassDecl = static_cast<Decl *>(classDecl);
824
825  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
826  // always passing in a decl. If the decl has an error, isInvalidDecl()
827  // should be true.
828  if (!ClassDecl)
829    return;
830
831  llvm::SmallVector<ObjCMethodDecl*, 32> insMethods;
832  llvm::SmallVector<ObjCMethodDecl*, 16> clsMethods;
833
834  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
835  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
836
837  bool isInterfaceDeclKind =
838        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
839         || isa<ObjCProtocolDecl>(ClassDecl);
840  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
841
842  if (pNum != 0) {
843    if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl))
844      IDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
845    else if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
846      CDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
847    else if (ObjCProtocolDecl *PDecl = dyn_cast<ObjCProtocolDecl>(ClassDecl))
848          PDecl->addProperties((ObjCPropertyDecl**)allProperties, pNum);
849    else
850      assert(false && "ActOnAtEnd - property declaration misplaced");
851  }
852
853  for (unsigned i = 0; i < allNum; i++ ) {
854    ObjCMethodDecl *Method =
855      cast_or_null<ObjCMethodDecl>(static_cast<Decl*>(allMethods[i]));
856
857    if (!Method) continue;  // Already issued a diagnostic.
858    if (Method->isInstance()) {
859      /// Check for instance method of the same name with incompatible types
860      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
861      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
862                              : false;
863      if (isInterfaceDeclKind && PrevMethod && !match
864          || checkIdenticalMethods && match) {
865          Diag(Method->getLocation(), diag::error_duplicate_method_decl,
866               Method->getSelector().getName());
867          Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
868      } else {
869        insMethods.push_back(Method);
870        InsMap[Method->getSelector()] = Method;
871        /// The following allows us to typecheck messages to "id".
872        AddInstanceMethodToGlobalPool(Method);
873      }
874    }
875    else {
876      /// Check for class method of the same name with incompatible types
877      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
878      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
879                              : false;
880      if (isInterfaceDeclKind && PrevMethod && !match
881          || checkIdenticalMethods && match) {
882        Diag(Method->getLocation(), diag::error_duplicate_method_decl,
883             Method->getSelector().getName());
884        Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
885      } else {
886        clsMethods.push_back(Method);
887        ClsMap[Method->getSelector()] = Method;
888        /// The following allows us to typecheck messages to "Class".
889        AddFactoryMethodToGlobalPool(Method);
890      }
891    }
892  }
893
894  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
895    // Compares properties declaraed in this class to those of its
896    // super class.
897    ComparePropertiesInBaseAndSuper(I);
898    MergeProtocolPropertiesIntoClass(I, I);
899    for (ObjCInterfaceDecl::classprop_iterator P = I->classprop_begin(),
900         E = I->classprop_end(); P != E; ++P) {
901      // FIXME: It would be really nice if we could avoid this. Injecting
902      // methods into the interface makes it hard to distinguish "real" methods
903      // from synthesized "property" methods (that aren't in the source).
904      // This complicicates the rewriter's life.
905      I->addPropertyMethods(Context, *P, insMethods);
906    }
907    I->addMethods(&insMethods[0], insMethods.size(),
908                  &clsMethods[0], clsMethods.size(), AtEndLoc);
909
910  } else if (ObjCProtocolDecl *P = dyn_cast<ObjCProtocolDecl>(ClassDecl)) {
911    P->addMethods(&insMethods[0], insMethods.size(),
912                  &clsMethods[0], clsMethods.size(), AtEndLoc);
913  }
914  else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
915    C->addMethods(&insMethods[0], insMethods.size(),
916                  &clsMethods[0], clsMethods.size(), AtEndLoc);
917  }
918  else if (ObjCImplementationDecl *IC =
919                dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
920    IC->setLocEnd(AtEndLoc);
921    if (ObjCInterfaceDecl* IDecl = getObjCInterfaceDecl(IC->getIdentifier()))
922      ImplMethodsVsClassMethods(IC, IDecl);
923  } else {
924    ObjCCategoryImplDecl* CatImplClass = cast<ObjCCategoryImplDecl>(ClassDecl);
925    CatImplClass->setLocEnd(AtEndLoc);
926    ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface();
927    // Find category interface decl and then check that all methods declared
928    // in this interface is implemented in the category @implementation.
929    if (IDecl) {
930      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
931           Categories; Categories = Categories->getNextClassCategory()) {
932        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
933          ImplCategoryMethodsVsIntfMethods(CatImplClass, Categories);
934          break;
935        }
936      }
937    }
938  }
939}
940
941
942/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
943/// objective-c's type qualifier from the parser version of the same info.
944static Decl::ObjCDeclQualifier
945CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
946  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
947  if (PQTVal & ObjCDeclSpec::DQ_In)
948    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
949  if (PQTVal & ObjCDeclSpec::DQ_Inout)
950    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
951  if (PQTVal & ObjCDeclSpec::DQ_Out)
952    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
953  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
954    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
955  if (PQTVal & ObjCDeclSpec::DQ_Byref)
956    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
957  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
958    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
959
960  return ret;
961}
962
963Sema::DeclTy *Sema::ActOnMethodDeclaration(
964    SourceLocation MethodLoc, SourceLocation EndLoc,
965    tok::TokenKind MethodType, DeclTy *classDecl,
966    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
967    Selector Sel,
968    // optional arguments. The number of types/arguments is obtained
969    // from the Sel.getNumArgs().
970    ObjCDeclSpec *ArgQT, TypeTy **ArgTypes, IdentifierInfo **ArgNames,
971    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
972    bool isVariadic) {
973  Decl *ClassDecl = static_cast<Decl*>(classDecl);
974
975  // Make sure we can establish a context for the method.
976  if (!ClassDecl) {
977    Diag(MethodLoc, diag::error_missing_method_context);
978    return 0;
979  }
980  QualType resultDeclType;
981
982  if (ReturnType)
983    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
984  else // get the type for "id".
985    resultDeclType = Context.getObjCIdType();
986
987  ObjCMethodDecl* ObjCMethod =
988    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
989                           ClassDecl, AttrList,
990                           MethodType == tok::minus, isVariadic,
991                           false,
992                           MethodDeclKind == tok::objc_optional ?
993                           ObjCMethodDecl::Optional :
994                           ObjCMethodDecl::Required);
995
996  llvm::SmallVector<ParmVarDecl*, 16> Params;
997
998  for (unsigned i = 0; i < Sel.getNumArgs(); i++) {
999    // FIXME: arg->AttrList must be stored too!
1000    QualType argType;
1001
1002    if (ArgTypes[i])
1003      argType = QualType::getFromOpaquePtr(ArgTypes[i]);
1004    else
1005      argType = Context.getObjCIdType();
1006    ParmVarDecl* Param = ParmVarDecl::Create(Context, ObjCMethod,
1007                                             SourceLocation(/*FIXME*/),
1008                                             ArgNames[i], argType,
1009                                             VarDecl::None, 0, 0);
1010    Param->setObjCDeclQualifier(
1011      CvtQTToAstBitMask(ArgQT[i].getObjCDeclQualifier()));
1012    Params.push_back(Param);
1013  }
1014
1015  ObjCMethod->setMethodParams(&Params[0], Sel.getNumArgs());
1016  ObjCMethod->setObjCDeclQualifier(
1017    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1018  const ObjCMethodDecl *PrevMethod = 0;
1019
1020  // For implementations (which can be very "coarse grain"), we add the
1021  // method now. This allows the AST to implement lookup methods that work
1022  // incrementally (without waiting until we parse the @end). It also allows
1023  // us to flag multiple declaration errors as they occur.
1024  if (ObjCImplementationDecl *ImpDecl =
1025        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1026    if (MethodType == tok::minus) {
1027      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1028      ImpDecl->addInstanceMethod(ObjCMethod);
1029    } else {
1030      PrevMethod = ImpDecl->getClassMethod(Sel);
1031      ImpDecl->addClassMethod(ObjCMethod);
1032    }
1033  }
1034  else if (ObjCCategoryImplDecl *CatImpDecl =
1035            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1036    if (MethodType == tok::minus) {
1037      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1038      CatImpDecl->addInstanceMethod(ObjCMethod);
1039    } else {
1040      PrevMethod = CatImpDecl->getClassMethod(Sel);
1041      CatImpDecl->addClassMethod(ObjCMethod);
1042    }
1043  }
1044  if (PrevMethod) {
1045    // You can never have two method definitions with the same name.
1046    Diag(ObjCMethod->getLocation(), diag::error_duplicate_method_decl,
1047        ObjCMethod->getSelector().getName());
1048    Diag(PrevMethod->getLocation(), diag::err_previous_declaration);
1049  }
1050  return ObjCMethod;
1051}
1052
1053Sema::DeclTy *Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
1054                                  FieldDeclarator &FD,
1055                                  ObjCDeclSpec &ODS,
1056                                  Selector GetterSel,
1057                                  Selector SetterSel,
1058                                  tok::ObjCKeywordKind MethodImplKind) {
1059  QualType T = GetTypeForDeclarator(FD.D, S);
1060  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, AtLoc,
1061                                                     FD.D.getIdentifier(), T);
1062  // Regardless of setter/getter attribute, we save the default getter/setter
1063  // selector names in anticipation of declaration of setter/getter methods.
1064  PDecl->setGetterName(GetterSel);
1065  PDecl->setSetterName(SetterSel);
1066
1067  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readonly)
1068    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
1069
1070  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_getter)
1071    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
1072
1073  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_setter)
1074    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
1075
1076  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_assign)
1077    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
1078
1079  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_readwrite)
1080    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
1081
1082  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_retain)
1083    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1084
1085  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_copy)
1086    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1087
1088  if (ODS.getPropertyAttributes() & ObjCDeclSpec::DQ_PR_nonatomic)
1089    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
1090
1091  if (MethodImplKind == tok::objc_required)
1092    PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
1093  else if (MethodImplKind == tok::objc_optional)
1094    PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
1095
1096  return PDecl;
1097}
1098
1099/// ActOnPropertyImplDecl - This routine performs semantic checks and
1100/// builds the AST node for a property implementation declaration; declared
1101/// as @synthesize or @dynamic.
1102///
1103Sema::DeclTy *Sema::ActOnPropertyImplDecl(SourceLocation AtLoc,
1104                                          SourceLocation PropertyLoc,
1105                                          bool Synthesize,
1106                                          DeclTy *ClassCatImpDecl,
1107                                          IdentifierInfo *PropertyId,
1108                                          IdentifierInfo *PropertyIvar) {
1109  Decl *ClassImpDecl = static_cast<Decl*>(ClassCatImpDecl);
1110  // Make sure we have a context for the property implementation declaration.
1111  if (!ClassImpDecl) {
1112    Diag(AtLoc, diag::error_missing_property_context);
1113    return 0;
1114  }
1115  ObjCPropertyDecl *property = 0;
1116  ObjCInterfaceDecl* IDecl = 0;
1117  // Find the class or category class where this property must have
1118  // a declaration.
1119  ObjCImplementationDecl *IC = 0;
1120  ObjCCategoryImplDecl* CatImplClass = 0;
1121  if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
1122    IDecl = getObjCInterfaceDecl(IC->getIdentifier());
1123    // We always synthesize an interface for an implementation
1124    // without an interface decl. So, IDecl is always non-zero.
1125    assert(IDecl &&
1126           "ActOnPropertyImplDecl - @implementation without @interface");
1127
1128    // Look for this property declaration in the @implementation's @interface
1129    property = IDecl->FindPropertyDeclaration(PropertyId);
1130    if (!property) {
1131       Diag(PropertyLoc, diag::error_bad_property_decl, IDecl->getName());
1132      return 0;
1133    }
1134  }
1135  else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
1136    if (Synthesize) {
1137      Diag(AtLoc, diag::error_synthesize_category_decl);
1138      return 0;
1139    }
1140    IDecl = CatImplClass->getClassInterface();
1141    if (!IDecl) {
1142      Diag(AtLoc, diag::error_missing_property_interface);
1143      return 0;
1144    }
1145    ObjCCategoryDecl *Category =
1146      IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
1147
1148    // If category for this implementation not found, it is an error which
1149    // has already been reported eralier.
1150    if (!Category)
1151      return 0;
1152    // Look for this property declaration in @implementation's category
1153    property = Category->FindPropertyDeclaration(PropertyId);
1154    if (!property) {
1155      Diag(PropertyLoc, diag::error_bad_category_property_decl,
1156           Category->getName());
1157      return 0;
1158    }
1159  }
1160  else {
1161    Diag(AtLoc, diag::error_bad_property_context);
1162    return 0;
1163  }
1164  ObjCIvarDecl *Ivar = 0;
1165  // Check that we have a valid, previously declared ivar for @synthesize
1166  if (Synthesize) {
1167    // @synthesize
1168    if (!PropertyIvar)
1169      PropertyIvar = PropertyId;
1170    // Check that this is a previously declared 'ivar' in 'IDecl' interface
1171    Ivar = IDecl->FindIvarDeclaration(PropertyIvar);
1172    if (!Ivar) {
1173      Diag(PropertyLoc, diag::error_missing_property_ivar_decl,
1174           PropertyId->getName());
1175      return 0;
1176    }
1177    // Check that type of property and its ivar match.
1178    if (Ivar->getCanonicalType() != property->getCanonicalType()) {
1179      Diag(PropertyLoc, diag::error_property_ivar_type, property->getName(),
1180           Ivar->getName());
1181      return 0;
1182    }
1183
1184  } else if (PropertyIvar) {
1185    // @dynamic
1186    Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
1187    return 0;
1188  }
1189  assert (property && "ActOnPropertyImplDecl - property declaration missing");
1190  ObjCPropertyImplDecl *PIDecl =
1191    ObjCPropertyImplDecl::Create(Context, AtLoc, PropertyLoc, property,
1192                                 (Synthesize ?
1193                                  ObjCPropertyImplDecl::OBJC_PR_IMPL_SYNTHSIZE
1194                                  : ObjCPropertyImplDecl::OBJC_PR_IMPL_DYNAMIC),
1195                                  Ivar);
1196  if (IC)
1197    IC->addPropertyImplementation(PIDecl);
1198  else
1199    CatImplClass->addPropertyImplementation(PIDecl);
1200
1201  return PIDecl;
1202}
1203