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