SemaDeclObjC.cpp revision 24c8991f4dd0ab86678b5ab11f05586687b55be9
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(PDecl->getSetterName()))
828        return false;
829    }
830    else if (ObjCCategoryImplDecl *CIMD =
831             dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
832      if (CIMD->getInstanceMethod(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(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 I = IMPDecl->instmeth_begin(),
910         E = IMPDecl->instmeth_end(); I != E; ++I)
911    InsMap.insert((*I)->getSelector());
912
913  // Check and see if properties declared in the interface have either 1)
914  // an implementation or 2) there is a @synthesize/@dynamic implementation
915  // of the property in the @implementation.
916  if (isa<ObjCInterfaceDecl>(CDecl))
917      for (ObjCContainerDecl::prop_iterator P = CDecl->prop_begin(Context),
918       E = CDecl->prop_end(Context); P != E; ++P) {
919        ObjCPropertyDecl *Prop = (*P);
920        if (Prop->isInvalidDecl())
921          continue;
922        ObjCPropertyImplDecl *PI = 0;
923        // Is there a matching propery synthesize/dynamic?
924        for (ObjCImplDecl::propimpl_iterator I = IMPDecl->propimpl_begin(),
925             EI = IMPDecl->propimpl_end(); I != EI; ++I)
926          if ((*I)->getPropertyDecl() == Prop) {
927            PI = (*I);
928            break;
929          }
930        if (PI)
931          continue;
932        if (!InsMap.count(Prop->getGetterName())) {
933          Diag(Prop->getLocation(),
934               diag::warn_setter_getter_impl_required)
935          << Prop->getDeclName() << Prop->getGetterName();
936          Diag(IMPDecl->getLocation(),
937               diag::note_property_impl_required);
938        }
939
940        if (!Prop->isReadOnly() && !InsMap.count(Prop->getSetterName())) {
941          Diag(Prop->getLocation(),
942               diag::warn_setter_getter_impl_required)
943          << Prop->getDeclName() << Prop->getSetterName();
944          Diag(IMPDecl->getLocation(),
945               diag::note_property_impl_required);
946        }
947      }
948
949  for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(Context),
950       E = CDecl->instmeth_end(Context); I != E; ++I) {
951    if (!(*I)->isSynthesized() && !InsMap.count((*I)->getSelector())) {
952      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
953      continue;
954    }
955
956    ObjCMethodDecl *ImpMethodDecl =
957      IMPDecl->getInstanceMethod((*I)->getSelector());
958    ObjCMethodDecl *IntfMethodDecl =
959      CDecl->getInstanceMethod(Context, (*I)->getSelector());
960    assert(IntfMethodDecl &&
961           "IntfMethodDecl is null in ImplMethodsVsClassMethods");
962    // ImpMethodDecl may be null as in a @dynamic property.
963    if (ImpMethodDecl)
964      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
965  }
966
967  llvm::DenseSet<Selector> ClsMap;
968  // Check and see if class methods in class interface have been
969  // implemented in the implementation class.
970  for (ObjCImplementationDecl::classmeth_iterator I =IMPDecl->classmeth_begin(),
971       E = IMPDecl->classmeth_end(); I != E; ++I)
972    ClsMap.insert((*I)->getSelector());
973
974  for (ObjCInterfaceDecl::classmeth_iterator
975         I = CDecl->classmeth_begin(Context),
976         E = CDecl->classmeth_end(Context);
977       I != E; ++I)
978    if (!ClsMap.count((*I)->getSelector()))
979      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
980    else {
981      ObjCMethodDecl *ImpMethodDecl =
982        IMPDecl->getClassMethod((*I)->getSelector());
983      ObjCMethodDecl *IntfMethodDecl =
984        CDecl->getClassMethod(Context, (*I)->getSelector());
985      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
986    }
987
988
989  // Check the protocol list for unimplemented methods in the @implementation
990  // class.
991  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
992    for (ObjCCategoryDecl::protocol_iterator PI = I->protocol_begin(),
993         E = I->protocol_end(); PI != E; ++PI)
994      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
995                              InsMap, ClsMap, I);
996    // Check class extensions (unnamed categories)
997    for (ObjCCategoryDecl *Categories = I->getCategoryList();
998         Categories; Categories = Categories->getNextClassCategory()) {
999      if (!Categories->getIdentifier()) {
1000        ImplMethodsVsClassMethods(IMPDecl, Categories, IncompleteImpl);
1001        break;
1002      }
1003    }
1004  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1005    for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1006         E = C->protocol_end(); PI != E; ++PI)
1007      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1008                              InsMap, ClsMap, C->getClassInterface());
1009  } else
1010    assert(false && "invalid ObjCContainerDecl type.");
1011}
1012
1013/// ActOnForwardClassDeclaration -
1014Action::DeclPtrTy
1015Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1016                                   IdentifierInfo **IdentList,
1017                                   unsigned NumElts) {
1018  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1019
1020  for (unsigned i = 0; i != NumElts; ++i) {
1021    // Check for another declaration kind with the same name.
1022    NamedDecl *PrevDecl = LookupName(TUScope, IdentList[i], LookupOrdinaryName);
1023    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1024      // Maybe we will complain about the shadowed template parameter.
1025      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1026      // Just pretend that we didn't see the previous declaration.
1027      PrevDecl = 0;
1028    }
1029
1030    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1031      // GCC apparently allows the following idiom:
1032      //
1033      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1034      // @class XCElementToggler;
1035      //
1036      // FIXME: Make an extension?
1037      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
1038      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
1039        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1040        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1041      }
1042    }
1043    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1044    if (!IDecl) {  // Not already seen?  Make a forward decl.
1045      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1046                                        IdentList[i], SourceLocation(), true);
1047      ObjCInterfaceDecls[IdentList[i]] = IDecl;
1048
1049      // FIXME: PushOnScopeChains?
1050      CurContext->addDecl(Context, IDecl);
1051      // Remember that this needs to be removed when the scope is popped.
1052      TUScope->AddDecl(DeclPtrTy::make(IDecl));
1053    }
1054
1055    Interfaces.push_back(IDecl);
1056  }
1057
1058  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1059                                               &Interfaces[0],
1060                                               Interfaces.size());
1061  CurContext->addDecl(Context, CDecl);
1062  CheckObjCDeclScope(CDecl);
1063  return DeclPtrTy::make(CDecl);
1064}
1065
1066
1067/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1068/// returns true, or false, accordingly.
1069/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1070bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1071                                      const ObjCMethodDecl *PrevMethod,
1072                                      bool matchBasedOnSizeAndAlignment) {
1073  QualType T1 = Context.getCanonicalType(Method->getResultType());
1074  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1075
1076  if (T1 != T2) {
1077    // The result types are different.
1078    if (!matchBasedOnSizeAndAlignment)
1079      return false;
1080    // Incomplete types don't have a size and alignment.
1081    if (T1->isIncompleteType() || T2->isIncompleteType())
1082      return false;
1083    // Check is based on size and alignment.
1084    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1085      return false;
1086  }
1087
1088  ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1089       E = Method->param_end();
1090  ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1091
1092  for (; ParamI != E; ++ParamI, ++PrevI) {
1093    assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1094    T1 = Context.getCanonicalType((*ParamI)->getType());
1095    T2 = Context.getCanonicalType((*PrevI)->getType());
1096    if (T1 != T2) {
1097      // The result types are different.
1098      if (!matchBasedOnSizeAndAlignment)
1099        return false;
1100      // Incomplete types don't have a size and alignment.
1101      if (T1->isIncompleteType() || T2->isIncompleteType())
1102        return false;
1103      // Check is based on size and alignment.
1104      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1105        return false;
1106    }
1107  }
1108  return true;
1109}
1110
1111void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
1112  ObjCMethodList &Entry = InstanceMethodPool[Method->getSelector()];
1113  if (Entry.Method == 0) {
1114    // Haven't seen a method with this selector name yet - add it.
1115    Entry.Method = Method;
1116    Entry.Next = 0;
1117    return;
1118  }
1119
1120  // We've seen a method with this name, see if we have already seen this type
1121  // signature.
1122  for (ObjCMethodList *List = &Entry; List; List = List->Next)
1123    if (MatchTwoMethodDeclarations(Method, List->Method))
1124      return;
1125
1126  // We have a new signature for an existing method - add it.
1127  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1128  Entry.Next = new ObjCMethodList(Method, Entry.Next);
1129}
1130
1131// FIXME: Finish implementing -Wno-strict-selector-match.
1132ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
1133                                                       SourceRange R) {
1134  ObjCMethodList &MethList = InstanceMethodPool[Sel];
1135  bool issueWarning = false;
1136
1137  if (MethList.Method && MethList.Next) {
1138    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1139      // This checks if the methods differ by size & alignment.
1140      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1141        issueWarning = true;
1142  }
1143  if (issueWarning && (MethList.Method && MethList.Next)) {
1144    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1145    Diag(MethList.Method->getLocStart(), diag::note_using_decl)
1146      << MethList.Method->getSourceRange();
1147    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1148      Diag(Next->Method->getLocStart(), diag::note_also_found_decl)
1149        << Next->Method->getSourceRange();
1150  }
1151  return MethList.Method;
1152}
1153
1154void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
1155  ObjCMethodList &FirstMethod = FactoryMethodPool[Method->getSelector()];
1156  if (!FirstMethod.Method) {
1157    // Haven't seen a method with this selector name yet - add it.
1158    FirstMethod.Method = Method;
1159    FirstMethod.Next = 0;
1160  } else {
1161    // We've seen a method with this name, now check the type signature(s).
1162    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1163
1164    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1165         Next = Next->Next)
1166      match = MatchTwoMethodDeclarations(Method, Next->Method);
1167
1168    if (!match) {
1169      // We have a new signature for an existing method - add it.
1170      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1171      struct ObjCMethodList *OMI = new ObjCMethodList(Method, FirstMethod.Next);
1172      FirstMethod.Next = OMI;
1173    }
1174  }
1175}
1176
1177/// ProcessPropertyDecl - Make sure that any user-defined setter/getter methods
1178/// have the property type and issue diagnostics if they don't.
1179/// Also synthesize a getter/setter method if none exist (and update the
1180/// appropriate lookup tables. FIXME: Should reconsider if adding synthesized
1181/// methods is the "right" thing to do.
1182void Sema::ProcessPropertyDecl(ObjCPropertyDecl *property,
1183                               ObjCContainerDecl *CD) {
1184  ObjCMethodDecl *GetterMethod, *SetterMethod;
1185
1186  GetterMethod = CD->getInstanceMethod(Context, property->getGetterName());
1187  SetterMethod = CD->getInstanceMethod(Context, property->getSetterName());
1188
1189  if (GetterMethod &&
1190      GetterMethod->getResultType() != property->getType()) {
1191    Diag(property->getLocation(),
1192         diag::err_accessor_property_type_mismatch)
1193      << property->getDeclName()
1194      << GetterMethod->getSelector();
1195    Diag(GetterMethod->getLocation(), diag::note_declared_at);
1196  }
1197
1198  if (SetterMethod) {
1199    if (Context.getCanonicalType(SetterMethod->getResultType())
1200        != Context.VoidTy)
1201      Diag(SetterMethod->getLocation(), diag::err_setter_type_void);
1202    if (SetterMethod->param_size() != 1 ||
1203        ((*SetterMethod->param_begin())->getType() != property->getType())) {
1204      Diag(property->getLocation(),
1205           diag::err_accessor_property_type_mismatch)
1206        << property->getDeclName()
1207        << SetterMethod->getSelector();
1208      Diag(SetterMethod->getLocation(), diag::note_declared_at);
1209    }
1210  }
1211
1212  // Synthesize getter/setter methods if none exist.
1213  // Find the default getter and if one not found, add one.
1214  // FIXME: The synthesized property we set here is misleading. We
1215  // almost always synthesize these methods unless the user explicitly
1216  // provided prototypes (which is odd, but allowed). Sema should be
1217  // typechecking that the declarations jive in that situation (which
1218  // it is not currently).
1219  if (!GetterMethod) {
1220    // No instance method of same name as property getter name was found.
1221    // Declare a getter method and add it to the list of methods
1222    // for this class.
1223    GetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(),
1224                             property->getLocation(), property->getGetterName(),
1225                             property->getType(), CD, true, false, true,
1226                             (property->getPropertyImplementation() ==
1227                              ObjCPropertyDecl::Optional) ?
1228                             ObjCMethodDecl::Optional :
1229                             ObjCMethodDecl::Required);
1230    CD->addDecl(Context, GetterMethod);
1231  } else
1232    // A user declared getter will be synthesize when @synthesize of
1233    // the property with the same name is seen in the @implementation
1234    GetterMethod->setSynthesized(true);
1235  property->setGetterMethodDecl(GetterMethod);
1236
1237  // Skip setter if property is read-only.
1238  if (!property->isReadOnly()) {
1239    // Find the default setter and if one not found, add one.
1240    if (!SetterMethod) {
1241      // No instance method of same name as property setter name was found.
1242      // Declare a setter method and add it to the list of methods
1243      // for this class.
1244      SetterMethod = ObjCMethodDecl::Create(Context, property->getLocation(),
1245                               property->getLocation(),
1246                               property->getSetterName(),
1247                               Context.VoidTy, CD, true, false, true,
1248                               (property->getPropertyImplementation() ==
1249                                ObjCPropertyDecl::Optional) ?
1250                               ObjCMethodDecl::Optional :
1251                               ObjCMethodDecl::Required);
1252      // Invent the arguments for the setter. We don't bother making a
1253      // nice name for the argument.
1254      ParmVarDecl *Argument = ParmVarDecl::Create(Context, SetterMethod,
1255                                                  property->getLocation(),
1256                                                  property->getIdentifier(),
1257                                                  property->getType(),
1258                                                  VarDecl::None,
1259                                                  0);
1260      SetterMethod->setMethodParams(Context, &Argument, 1);
1261      CD->addDecl(Context, SetterMethod);
1262    } else
1263      // A user declared setter will be synthesize when @synthesize of
1264      // the property with the same name is seen in the @implementation
1265      SetterMethod->setSynthesized(true);
1266    property->setSetterMethodDecl(SetterMethod);
1267  }
1268  // Add any synthesized methods to the global pool. This allows us to
1269  // handle the following, which is supported by GCC (and part of the design).
1270  //
1271  // @interface Foo
1272  // @property double bar;
1273  // @end
1274  //
1275  // void thisIsUnfortunate() {
1276  //   id foo;
1277  //   double bar = [foo bar];
1278  // }
1279  //
1280  if (GetterMethod)
1281    AddInstanceMethodToGlobalPool(GetterMethod);
1282  if (SetterMethod)
1283    AddInstanceMethodToGlobalPool(SetterMethod);
1284}
1285
1286// Note: For class/category implemenations, allMethods/allProperties is
1287// always null.
1288void Sema::ActOnAtEnd(SourceLocation AtEndLoc, DeclPtrTy classDecl,
1289                      DeclPtrTy *allMethods, unsigned allNum,
1290                      DeclPtrTy *allProperties, unsigned pNum,
1291                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1292  Decl *ClassDecl = classDecl.getAs<Decl>();
1293
1294  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1295  // always passing in a decl. If the decl has an error, isInvalidDecl()
1296  // should be true.
1297  if (!ClassDecl)
1298    return;
1299
1300  bool isInterfaceDeclKind =
1301        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1302         || isa<ObjCProtocolDecl>(ClassDecl);
1303  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1304
1305  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1306
1307  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1308  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1309  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1310
1311  for (unsigned i = 0; i < allNum; i++ ) {
1312    ObjCMethodDecl *Method =
1313      cast_or_null<ObjCMethodDecl>(allMethods[i].getAs<Decl>());
1314
1315    if (!Method) continue;  // Already issued a diagnostic.
1316    if (Method->isInstanceMethod()) {
1317      /// Check for instance method of the same name with incompatible types
1318      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1319      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1320                              : false;
1321      if ((isInterfaceDeclKind && PrevMethod && !match)
1322          || (checkIdenticalMethods && match)) {
1323          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1324            << Method->getDeclName();
1325          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1326      } else {
1327        DC->addDecl(Context, Method);
1328        InsMap[Method->getSelector()] = Method;
1329        /// The following allows us to typecheck messages to "id".
1330        AddInstanceMethodToGlobalPool(Method);
1331      }
1332    }
1333    else {
1334      /// Check for class method of the same name with incompatible types
1335      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1336      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1337                              : false;
1338      if ((isInterfaceDeclKind && PrevMethod && !match)
1339          || (checkIdenticalMethods && match)) {
1340        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1341          << Method->getDeclName();
1342        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1343      } else {
1344        DC->addDecl(Context, Method);
1345        ClsMap[Method->getSelector()] = Method;
1346        /// The following allows us to typecheck messages to "Class".
1347        AddFactoryMethodToGlobalPool(Method);
1348      }
1349    }
1350  }
1351  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1352    // Compares properties declared in this class to those of its
1353    // super class.
1354    ComparePropertiesInBaseAndSuper(I);
1355    MergeProtocolPropertiesIntoClass(I, DeclPtrTy::make(I));
1356  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1357    // Categories are used to extend the class by declaring new methods.
1358    // By the same token, they are also used to add new properties. No
1359    // need to compare the added property to those in the class.
1360
1361    // Merge protocol properties into category
1362    MergeProtocolPropertiesIntoClass(C, DeclPtrTy::make(C));
1363    if (C->getIdentifier() == 0)
1364      DiagnoseClassExtensionDupMethods(C, C->getClassInterface());
1365  }
1366  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1367    // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1368    // user-defined setter/getter. It also synthesizes setter/getter methods
1369    // and adds them to the DeclContext and global method pools.
1370    for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(Context),
1371                                          E = CDecl->prop_end(Context);
1372         I != E; ++I)
1373      ProcessPropertyDecl(*I, CDecl);
1374    CDecl->setAtEndLoc(AtEndLoc);
1375  }
1376  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1377    IC->setLocEnd(AtEndLoc);
1378    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface())
1379      ImplMethodsVsClassMethods(IC, IDecl);
1380  } else if (ObjCCategoryImplDecl* CatImplClass =
1381                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1382    CatImplClass->setLocEnd(AtEndLoc);
1383
1384    // Find category interface decl and then check that all methods declared
1385    // in this interface are implemented in the category @implementation.
1386    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1387      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1388           Categories; Categories = Categories->getNextClassCategory()) {
1389        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1390          ImplMethodsVsClassMethods(CatImplClass, Categories);
1391          break;
1392        }
1393      }
1394    }
1395  }
1396  if (isInterfaceDeclKind) {
1397    // Reject invalid vardecls.
1398    for (unsigned i = 0; i != tuvNum; i++) {
1399      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1400      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1401        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1402          if (!VDecl->hasExternalStorage())
1403            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1404        }
1405    }
1406  }
1407}
1408
1409
1410/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1411/// objective-c's type qualifier from the parser version of the same info.
1412static Decl::ObjCDeclQualifier
1413CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1414  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1415  if (PQTVal & ObjCDeclSpec::DQ_In)
1416    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1417  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1418    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1419  if (PQTVal & ObjCDeclSpec::DQ_Out)
1420    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1421  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1422    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1423  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1424    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1425  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1426    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1427
1428  return ret;
1429}
1430
1431Sema::DeclPtrTy Sema::ActOnMethodDeclaration(
1432    SourceLocation MethodLoc, SourceLocation EndLoc,
1433    tok::TokenKind MethodType, DeclPtrTy classDecl,
1434    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1435    Selector Sel,
1436    // optional arguments. The number of types/arguments is obtained
1437    // from the Sel.getNumArgs().
1438    ObjCArgInfo *ArgInfo,
1439    llvm::SmallVectorImpl<Declarator> &Cdecls,
1440    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1441    bool isVariadic) {
1442  Decl *ClassDecl = classDecl.getAs<Decl>();
1443
1444  // Make sure we can establish a context for the method.
1445  if (!ClassDecl) {
1446    Diag(MethodLoc, diag::error_missing_method_context);
1447    return DeclPtrTy();
1448  }
1449  QualType resultDeclType;
1450
1451  if (ReturnType) {
1452    resultDeclType = QualType::getFromOpaquePtr(ReturnType);
1453
1454    // Methods cannot return interface types. All ObjC objects are
1455    // passed by reference.
1456    if (resultDeclType->isObjCInterfaceType()) {
1457      Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1458        << 0 << resultDeclType;
1459      return DeclPtrTy();
1460    }
1461  } else // get the type for "id".
1462    resultDeclType = Context.getObjCIdType();
1463
1464  ObjCMethodDecl* ObjCMethod =
1465    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1466                           cast<DeclContext>(ClassDecl),
1467                           MethodType == tok::minus, isVariadic,
1468                           false,
1469                           MethodDeclKind == tok::objc_optional ?
1470                           ObjCMethodDecl::Optional :
1471                           ObjCMethodDecl::Required);
1472
1473  llvm::SmallVector<ParmVarDecl*, 16> Params;
1474
1475  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1476    QualType ArgType, UnpromotedArgType;
1477
1478    if (ArgInfo[i].Type == 0) {
1479      UnpromotedArgType = ArgType = Context.getObjCIdType();
1480    } else {
1481      UnpromotedArgType = ArgType = QualType::getFromOpaquePtr(ArgInfo[i].Type);
1482      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1483      ArgType = adjustParameterType(ArgType);
1484    }
1485
1486    ParmVarDecl* Param;
1487    if (ArgType == UnpromotedArgType)
1488      Param = ParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc,
1489                                  ArgInfo[i].Name, ArgType,
1490                                  VarDecl::None, 0);
1491    else
1492      Param = OriginalParmVarDecl::Create(Context, ObjCMethod,
1493                                          ArgInfo[i].NameLoc,
1494                                          ArgInfo[i].Name, ArgType,
1495                                          UnpromotedArgType,
1496                                          VarDecl::None, 0);
1497
1498    if (ArgType->isObjCInterfaceType()) {
1499      Diag(ArgInfo[i].NameLoc,
1500           diag::err_object_cannot_be_passed_returned_by_value)
1501        << 1 << ArgType;
1502      Param->setInvalidDecl();
1503    }
1504
1505    Param->setObjCDeclQualifier(
1506      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
1507
1508    // Apply the attributes to the parameter.
1509    ProcessDeclAttributeList(Param, ArgInfo[i].ArgAttrs);
1510
1511    Params.push_back(Param);
1512  }
1513
1514  ObjCMethod->setMethodParams(Context, &Params[0], Sel.getNumArgs());
1515  ObjCMethod->setObjCDeclQualifier(
1516    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1517  const ObjCMethodDecl *PrevMethod = 0;
1518
1519  if (AttrList)
1520    ProcessDeclAttributeList(ObjCMethod, AttrList);
1521
1522  // For implementations (which can be very "coarse grain"), we add the
1523  // method now. This allows the AST to implement lookup methods that work
1524  // incrementally (without waiting until we parse the @end). It also allows
1525  // us to flag multiple declaration errors as they occur.
1526  if (ObjCImplementationDecl *ImpDecl =
1527        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1528    if (MethodType == tok::minus) {
1529      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1530      ImpDecl->addInstanceMethod(ObjCMethod);
1531    } else {
1532      PrevMethod = ImpDecl->getClassMethod(Sel);
1533      ImpDecl->addClassMethod(ObjCMethod);
1534    }
1535  }
1536  else if (ObjCCategoryImplDecl *CatImpDecl =
1537            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1538    if (MethodType == tok::minus) {
1539      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1540      CatImpDecl->addInstanceMethod(ObjCMethod);
1541    } else {
1542      PrevMethod = CatImpDecl->getClassMethod(Sel);
1543      CatImpDecl->addClassMethod(ObjCMethod);
1544    }
1545  }
1546  if (PrevMethod) {
1547    // You can never have two method definitions with the same name.
1548    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1549      << ObjCMethod->getDeclName();
1550    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1551  }
1552  return DeclPtrTy::make(ObjCMethod);
1553}
1554
1555void Sema::CheckObjCPropertyAttributes(QualType PropertyTy,
1556                                       SourceLocation Loc,
1557                                       unsigned &Attributes) {
1558  // FIXME: Improve the reported location.
1559
1560  // readonly and readwrite/assign/retain/copy conflict.
1561  if ((Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1562      (Attributes & (ObjCDeclSpec::DQ_PR_readwrite |
1563                     ObjCDeclSpec::DQ_PR_assign |
1564                     ObjCDeclSpec::DQ_PR_copy |
1565                     ObjCDeclSpec::DQ_PR_retain))) {
1566    const char * which = (Attributes & ObjCDeclSpec::DQ_PR_readwrite) ?
1567                          "readwrite" :
1568                         (Attributes & ObjCDeclSpec::DQ_PR_assign) ?
1569                          "assign" :
1570                         (Attributes & ObjCDeclSpec::DQ_PR_copy) ?
1571                          "copy" : "retain";
1572
1573    Diag(Loc, (Attributes & (ObjCDeclSpec::DQ_PR_readwrite)) ?
1574                 diag::err_objc_property_attr_mutually_exclusive :
1575                 diag::warn_objc_property_attr_mutually_exclusive)
1576      << "readonly" << which;
1577  }
1578
1579  // Check for copy or retain on non-object types.
1580  if ((Attributes & (ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain)) &&
1581      !Context.isObjCObjectPointerType(PropertyTy)) {
1582    Diag(Loc, diag::err_objc_property_requires_object)
1583      << (Attributes & ObjCDeclSpec::DQ_PR_copy ? "copy" : "retain");
1584    Attributes &= ~(ObjCDeclSpec::DQ_PR_copy | ObjCDeclSpec::DQ_PR_retain);
1585  }
1586
1587  // Check for more than one of { assign, copy, retain }.
1588  if (Attributes & ObjCDeclSpec::DQ_PR_assign) {
1589    if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1590      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1591        << "assign" << "copy";
1592      Attributes &= ~ObjCDeclSpec::DQ_PR_copy;
1593    }
1594    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1595      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1596        << "assign" << "retain";
1597      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1598    }
1599  } else if (Attributes & ObjCDeclSpec::DQ_PR_copy) {
1600    if (Attributes & ObjCDeclSpec::DQ_PR_retain) {
1601      Diag(Loc, diag::err_objc_property_attr_mutually_exclusive)
1602        << "copy" << "retain";
1603      Attributes &= ~ObjCDeclSpec::DQ_PR_retain;
1604    }
1605  }
1606
1607  // Warn if user supplied no assignment attribute, property is
1608  // readwrite, and this is an object type.
1609  if (!(Attributes & (ObjCDeclSpec::DQ_PR_assign | ObjCDeclSpec::DQ_PR_copy |
1610                      ObjCDeclSpec::DQ_PR_retain)) &&
1611      !(Attributes & ObjCDeclSpec::DQ_PR_readonly) &&
1612      Context.isObjCObjectPointerType(PropertyTy)) {
1613    // Skip this warning in gc-only mode.
1614    if (getLangOptions().getGCMode() != LangOptions::GCOnly)
1615      Diag(Loc, diag::warn_objc_property_no_assignment_attribute);
1616
1617    // If non-gc code warn that this is likely inappropriate.
1618    if (getLangOptions().getGCMode() == LangOptions::NonGC)
1619      Diag(Loc, diag::warn_objc_property_default_assign_on_object);
1620
1621    // FIXME: Implement warning dependent on NSCopying being
1622    // implemented. See also:
1623    // <rdar://5168496&4855821&5607453&5096644&4947311&5698469&4947014&5168496>
1624    // (please trim this list while you are at it).
1625  }
1626}
1627
1628Sema::DeclPtrTy Sema::ActOnProperty(Scope *S, SourceLocation AtLoc,
1629                                    FieldDeclarator &FD,
1630                                    ObjCDeclSpec &ODS,
1631                                    Selector GetterSel,
1632                                    Selector SetterSel,
1633                                    DeclPtrTy ClassCategory,
1634                                    bool *isOverridingProperty,
1635                                    tok::ObjCKeywordKind MethodImplKind) {
1636  unsigned Attributes = ODS.getPropertyAttributes();
1637  bool isReadWrite = ((Attributes & ObjCDeclSpec::DQ_PR_readwrite) ||
1638                      // default is readwrite!
1639                      !(Attributes & ObjCDeclSpec::DQ_PR_readonly));
1640  // property is defaulted to 'assign' if it is readwrite and is
1641  // not retain or copy
1642  bool isAssign = ((Attributes & ObjCDeclSpec::DQ_PR_assign) ||
1643                   (isReadWrite &&
1644                    !(Attributes & ObjCDeclSpec::DQ_PR_retain) &&
1645                    !(Attributes & ObjCDeclSpec::DQ_PR_copy)));
1646  QualType T = GetTypeForDeclarator(FD.D, S);
1647  Decl *ClassDecl = ClassCategory.getAs<Decl>();
1648  ObjCInterfaceDecl *CCPrimary = 0; // continuation class's primary class
1649  // May modify Attributes.
1650  CheckObjCPropertyAttributes(T, AtLoc, Attributes);
1651  if (ObjCCategoryDecl *CDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl))
1652    if (!CDecl->getIdentifier()) {
1653      // This is a continuation class. property requires special
1654      // handling.
1655      if ((CCPrimary = CDecl->getClassInterface())) {
1656        // Find the property in continuation class's primary class only.
1657        ObjCPropertyDecl *PIDecl = 0;
1658        IdentifierInfo *PropertyId = FD.D.getIdentifier();
1659        for (ObjCInterfaceDecl::prop_iterator
1660               I = CCPrimary->prop_begin(Context),
1661               E = CCPrimary->prop_end(Context);
1662             I != E; ++I)
1663          if ((*I)->getIdentifier() == PropertyId) {
1664            PIDecl = *I;
1665            break;
1666          }
1667
1668        if (PIDecl) {
1669          // property 'PIDecl's readonly attribute will be over-ridden
1670          // with continuation class's readwrite property attribute!
1671          unsigned PIkind = PIDecl->getPropertyAttributes();
1672          if (isReadWrite && (PIkind & ObjCPropertyDecl::OBJC_PR_readonly)) {
1673            if ((Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) !=
1674                (PIkind & ObjCPropertyDecl::OBJC_PR_nonatomic))
1675              Diag(AtLoc, diag::warn_property_attr_mismatch);
1676            PIDecl->makeitReadWriteAttribute();
1677            if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1678              PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1679            if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1680              PIDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1681            PIDecl->setSetterName(SetterSel);
1682          }
1683          else
1684            Diag(AtLoc, diag::err_use_continuation_class)
1685              << CCPrimary->getDeclName();
1686          *isOverridingProperty = true;
1687          // Make sure setter decl is synthesized, and added to primary
1688          // class's list.
1689          ProcessPropertyDecl(PIDecl, CCPrimary);
1690          return DeclPtrTy();
1691        }
1692        // No matching property found in the primary class. Just fall thru
1693        // and add property to continuation class's primary class.
1694        ClassDecl = CCPrimary;
1695      } else {
1696        Diag(CDecl->getLocation(), diag::err_continuation_class);
1697        *isOverridingProperty = true;
1698        return DeclPtrTy();
1699      }
1700    }
1701
1702  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1703  assert(DC && "ClassDecl is not a DeclContext");
1704  ObjCPropertyDecl *PDecl = ObjCPropertyDecl::Create(Context, DC,
1705                                                     FD.D.getIdentifierLoc(),
1706                                                     FD.D.getIdentifier(), T);
1707  DC->addDecl(Context, PDecl);
1708
1709  if (T->isArrayType() || T->isFunctionType()) {
1710    Diag(AtLoc, diag::err_property_type) << T;
1711    PDecl->setInvalidDecl();
1712  }
1713
1714  ProcessDeclAttributes(PDecl, FD.D);
1715
1716  // Regardless of setter/getter attribute, we save the default getter/setter
1717  // selector names in anticipation of declaration of setter/getter methods.
1718  PDecl->setGetterName(GetterSel);
1719  PDecl->setSetterName(SetterSel);
1720
1721  if (Attributes & ObjCDeclSpec::DQ_PR_readonly)
1722    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readonly);
1723
1724  if (Attributes & ObjCDeclSpec::DQ_PR_getter)
1725    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_getter);
1726
1727  if (Attributes & ObjCDeclSpec::DQ_PR_setter)
1728    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_setter);
1729
1730  if (isReadWrite)
1731    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_readwrite);
1732
1733  if (Attributes & ObjCDeclSpec::DQ_PR_retain)
1734    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_retain);
1735
1736  if (Attributes & ObjCDeclSpec::DQ_PR_copy)
1737    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_copy);
1738
1739  if (isAssign)
1740    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_assign);
1741
1742  if (Attributes & ObjCDeclSpec::DQ_PR_nonatomic)
1743    PDecl->setPropertyAttributes(ObjCPropertyDecl::OBJC_PR_nonatomic);
1744
1745  if (MethodImplKind == tok::objc_required)
1746    PDecl->setPropertyImplementation(ObjCPropertyDecl::Required);
1747  else if (MethodImplKind == tok::objc_optional)
1748    PDecl->setPropertyImplementation(ObjCPropertyDecl::Optional);
1749  // A case of continuation class adding a new property in the class. This
1750  // is not what it was meant for. However, gcc supports it and so should we.
1751  // Make sure setter/getters are declared here.
1752  if (CCPrimary)
1753    ProcessPropertyDecl(PDecl, CCPrimary);
1754
1755  return DeclPtrTy::make(PDecl);
1756}
1757
1758/// ActOnPropertyImplDecl - This routine performs semantic checks and
1759/// builds the AST node for a property implementation declaration; declared
1760/// as @synthesize or @dynamic.
1761///
1762Sema::DeclPtrTy Sema::ActOnPropertyImplDecl(SourceLocation AtLoc,
1763                                            SourceLocation PropertyLoc,
1764                                            bool Synthesize,
1765                                            DeclPtrTy ClassCatImpDecl,
1766                                            IdentifierInfo *PropertyId,
1767                                            IdentifierInfo *PropertyIvar) {
1768  Decl *ClassImpDecl = ClassCatImpDecl.getAs<Decl>();
1769  // Make sure we have a context for the property implementation declaration.
1770  if (!ClassImpDecl) {
1771    Diag(AtLoc, diag::error_missing_property_context);
1772    return DeclPtrTy();
1773  }
1774  ObjCPropertyDecl *property = 0;
1775  ObjCInterfaceDecl* IDecl = 0;
1776  // Find the class or category class where this property must have
1777  // a declaration.
1778  ObjCImplementationDecl *IC = 0;
1779  ObjCCategoryImplDecl* CatImplClass = 0;
1780  if ((IC = dyn_cast<ObjCImplementationDecl>(ClassImpDecl))) {
1781    IDecl = IC->getClassInterface();
1782    // We always synthesize an interface for an implementation
1783    // without an interface decl. So, IDecl is always non-zero.
1784    assert(IDecl &&
1785           "ActOnPropertyImplDecl - @implementation without @interface");
1786
1787    // Look for this property declaration in the @implementation's @interface
1788    property = IDecl->FindPropertyDeclaration(Context, PropertyId);
1789    if (!property) {
1790      Diag(PropertyLoc, diag::error_bad_property_decl) << IDecl->getDeclName();
1791      return DeclPtrTy();
1792    }
1793  }
1794  else if ((CatImplClass = dyn_cast<ObjCCategoryImplDecl>(ClassImpDecl))) {
1795    if (Synthesize) {
1796      Diag(AtLoc, diag::error_synthesize_category_decl);
1797      return DeclPtrTy();
1798    }
1799    IDecl = CatImplClass->getClassInterface();
1800    if (!IDecl) {
1801      Diag(AtLoc, diag::error_missing_property_interface);
1802      return DeclPtrTy();
1803    }
1804    ObjCCategoryDecl *Category =
1805      IDecl->FindCategoryDeclaration(CatImplClass->getIdentifier());
1806
1807    // If category for this implementation not found, it is an error which
1808    // has already been reported eralier.
1809    if (!Category)
1810      return DeclPtrTy();
1811    // Look for this property declaration in @implementation's category
1812    property = Category->FindPropertyDeclaration(Context, PropertyId);
1813    if (!property) {
1814      Diag(PropertyLoc, diag::error_bad_category_property_decl)
1815        << Category->getDeclName();
1816      return DeclPtrTy();
1817    }
1818  } else {
1819    Diag(AtLoc, diag::error_bad_property_context);
1820    return DeclPtrTy();
1821  }
1822  ObjCIvarDecl *Ivar = 0;
1823  // Check that we have a valid, previously declared ivar for @synthesize
1824  if (Synthesize) {
1825    // @synthesize
1826    bool NoExplicitPropertyIvar = (!PropertyIvar);
1827    if (!PropertyIvar)
1828      PropertyIvar = PropertyId;
1829    QualType PropType = Context.getCanonicalType(property->getType());
1830    // Check that this is a previously declared 'ivar' in 'IDecl' interface
1831    ObjCInterfaceDecl *ClassDeclared;
1832    Ivar = IDecl->lookupInstanceVariable(Context, PropertyIvar, ClassDeclared);
1833    if (!Ivar) {
1834      Ivar = ObjCIvarDecl::Create(Context, CurContext, PropertyLoc,
1835                                  PropertyIvar, PropType,
1836                                  ObjCIvarDecl::Public,
1837                                  (Expr *)0);
1838      property->setPropertyIvarDecl(Ivar);
1839      if (!getLangOptions().ObjCNonFragileABI)
1840        Diag(PropertyLoc, diag::error_missing_property_ivar_decl) << PropertyId;
1841        // Note! I deliberately want it to fall thru so, we have a
1842        // a property implementation and to avoid future warnings.
1843    }
1844    else if (getLangOptions().ObjCNonFragileABI &&
1845             NoExplicitPropertyIvar && ClassDeclared != IDecl) {
1846      Diag(PropertyLoc, diag::error_ivar_in_superclass_use)
1847        << property->getDeclName() << Ivar->getDeclName()
1848        << ClassDeclared->getDeclName();
1849      Diag(Ivar->getLocation(), diag::note_previous_access_declaration)
1850        << Ivar << Ivar->getNameAsCString();
1851      // Note! I deliberately want it to fall thru so more errors are caught.
1852    }
1853    QualType IvarType = Context.getCanonicalType(Ivar->getType());
1854
1855    // Check that type of property and its ivar are type compatible.
1856    if (PropType != IvarType) {
1857      if (CheckAssignmentConstraints(PropType, IvarType) != Compatible) {
1858        Diag(PropertyLoc, diag::error_property_ivar_type)
1859          << property->getDeclName() << Ivar->getDeclName();
1860        // Note! I deliberately want it to fall thru so, we have a
1861        // a property implementation and to avoid future warnings.
1862      }
1863
1864      // FIXME! Rules for properties are somewhat different that those
1865      // for assignments. Use a new routine to consolidate all cases;
1866      // specifically for property redeclarations as well as for ivars.
1867      QualType lhsType =Context.getCanonicalType(PropType).getUnqualifiedType();
1868      QualType rhsType =Context.getCanonicalType(IvarType).getUnqualifiedType();
1869      if (lhsType != rhsType &&
1870          lhsType->isArithmeticType()) {
1871        Diag(PropertyLoc, diag::error_property_ivar_type)
1872        << property->getDeclName() << Ivar->getDeclName();
1873        // Fall thru - see previous comment
1874      }
1875      // __weak is explicit. So it works on Canonical type.
1876      if (PropType.isObjCGCWeak() && !IvarType.isObjCGCWeak() &&
1877          getLangOptions().getGCMode() != LangOptions::NonGC) {
1878        Diag(PropertyLoc, diag::error_weak_property)
1879        << property->getDeclName() << Ivar->getDeclName();
1880        // Fall thru - see previous comment
1881      }
1882      if ((Context.isObjCObjectPointerType(property->getType()) ||
1883           PropType.isObjCGCStrong()) && IvarType.isObjCGCWeak() &&
1884           getLangOptions().getGCMode() != LangOptions::NonGC) {
1885        Diag(PropertyLoc, diag::error_strong_property)
1886        << property->getDeclName() << Ivar->getDeclName();
1887        // Fall	thru - see previous comment
1888      }
1889    }
1890  } else if (PropertyIvar)
1891      // @dynamic
1892      Diag(PropertyLoc, diag::error_dynamic_property_ivar_decl);
1893  assert (property && "ActOnPropertyImplDecl - property declaration missing");
1894  ObjCPropertyImplDecl *PIDecl =
1895    ObjCPropertyImplDecl::Create(Context, CurContext, AtLoc, PropertyLoc,
1896                                 property,
1897                                 (Synthesize ?
1898                                  ObjCPropertyImplDecl::Synthesize
1899                                  : ObjCPropertyImplDecl::Dynamic),
1900                                 Ivar);
1901  CurContext->addDecl(Context, PIDecl);
1902  if (IC) {
1903    if (Synthesize)
1904      if (ObjCPropertyImplDecl *PPIDecl =
1905          IC->FindPropertyImplIvarDecl(PropertyIvar)) {
1906        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1907          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1908          << PropertyIvar;
1909        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1910      }
1911
1912    if (ObjCPropertyImplDecl *PPIDecl = IC->FindPropertyImplDecl(PropertyId)) {
1913      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1914      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1915      return DeclPtrTy();
1916    }
1917    IC->addPropertyImplementation(PIDecl);
1918  }
1919  else {
1920    if (Synthesize)
1921      if (ObjCPropertyImplDecl *PPIDecl =
1922          CatImplClass->FindPropertyImplIvarDecl(PropertyIvar)) {
1923        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1924          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1925          << PropertyIvar;
1926        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1927      }
1928
1929    if (ObjCPropertyImplDecl *PPIDecl =
1930          CatImplClass->FindPropertyImplDecl(PropertyId)) {
1931      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1932      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1933      return DeclPtrTy();
1934    }
1935    CatImplClass->addPropertyImplementation(PIDecl);
1936  }
1937
1938  return DeclPtrTy::make(PIDecl);
1939}
1940
1941bool Sema::CheckObjCDeclScope(Decl *D) {
1942  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1943    return false;
1944
1945  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1946  D->setInvalidDecl();
1947
1948  return true;
1949}
1950
1951/// Collect the instance variables declared in an Objective-C object.  Used in
1952/// the creation of structures from objects using the @defs directive.
1953/// FIXME: This should be consolidated with CollectObjCIvars as it is also
1954/// part of the AST generation logic of @defs.
1955static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
1956                         ASTContext& Ctx,
1957                         llvm::SmallVectorImpl<Sema::DeclPtrTy> &ivars) {
1958  if (Class->getSuperClass())
1959    CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
1960
1961  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1962  for (ObjCInterfaceDecl::ivar_iterator I = Class->ivar_begin(),
1963       E = Class->ivar_end(); I != E; ++I) {
1964    ObjCIvarDecl* ID = *I;
1965    Decl *FD = ObjCAtDefsFieldDecl::Create(Ctx, Record, ID->getLocation(),
1966                                           ID->getIdentifier(), ID->getType(),
1967                                           ID->getBitWidth());
1968    ivars.push_back(Sema::DeclPtrTy::make(FD));
1969  }
1970}
1971
1972/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1973/// instance variables of ClassName into Decls.
1974void Sema::ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart,
1975                     IdentifierInfo *ClassName,
1976                     llvm::SmallVectorImpl<DeclPtrTy> &Decls) {
1977  // Check that ClassName is a valid class
1978  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1979  if (!Class) {
1980    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1981    return;
1982  }
1983  if (LangOpts.ObjCNonFragileABI) {
1984    Diag(DeclStart, diag::err_atdef_nonfragile_interface);
1985    return;
1986  }
1987
1988  // Collect the instance variables
1989  CollectIvars(Class, dyn_cast<RecordDecl>(TagD.getAs<Decl>()), Context, Decls);
1990
1991  // Introduce all of these fields into the appropriate scope.
1992  for (llvm::SmallVectorImpl<DeclPtrTy>::iterator D = Decls.begin();
1993       D != Decls.end(); ++D) {
1994    FieldDecl *FD = cast<FieldDecl>(D->getAs<Decl>());
1995    if (getLangOptions().CPlusPlus)
1996      PushOnScopeChains(cast<FieldDecl>(FD), S);
1997    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>()))
1998      Record->addDecl(Context, FD);
1999  }
2000}
2001
2002