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