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