SemaDeclObjC.cpp revision 8f06f84e8be64962cc478e3e8867336768cac79b
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    PushOnScopeChains(IDecl, TUScope);
103    // Remember that this needs to be removed when the scope is popped.
104    TUScope->AddDecl(DeclPtrTy::make(IDecl));
105  }
106
107  if (SuperName) {
108    // Check if a different kind of symbol declared in this scope.
109    PrevDecl = LookupName(TUScope, SuperName, LookupOrdinaryName);
110
111    ObjCInterfaceDecl *SuperClassDecl =
112                                  dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
113
114    // Diagnose classes that inherit from deprecated classes.
115    if (SuperClassDecl)
116      (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
117
118    if (PrevDecl && SuperClassDecl == 0) {
119      // The previous declaration was not a class decl. Check if we have a
120      // typedef. If we do, get the underlying class type.
121      if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
122        QualType T = TDecl->getUnderlyingType();
123        if (T->isObjCInterfaceType()) {
124          if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl())
125            SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
126        }
127      }
128
129      // This handles the following case:
130      //
131      // typedef int SuperClass;
132      // @interface MyClass : SuperClass {} @end
133      //
134      if (!SuperClassDecl) {
135        Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
136        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
137      }
138    }
139
140    if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
141      if (!SuperClassDecl)
142        Diag(SuperLoc, diag::err_undef_superclass)
143          << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
144      else if (SuperClassDecl->isForwardDecl())
145        Diag(SuperLoc, diag::err_undef_superclass)
146          << SuperClassDecl->getDeclName() << ClassName
147          << SourceRange(AtInterfaceLoc, ClassLoc);
148    }
149    IDecl->setSuperClass(SuperClassDecl);
150    IDecl->setSuperClassLoc(SuperLoc);
151    IDecl->setLocEnd(SuperLoc);
152  } else { // we have a root class.
153    IDecl->setLocEnd(ClassLoc);
154  }
155
156  /// Check then save referenced protocols.
157  if (NumProtoRefs) {
158    IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
159                           Context);
160    IDecl->setLocEnd(EndProtoLoc);
161  }
162
163  CheckObjCDeclScope(IDecl);
164  return DeclPtrTy::make(IDecl);
165}
166
167/// ActOnCompatiblityAlias - this action is called after complete parsing of
168/// @compatibility_alias declaration. It sets up the alias relationships.
169Sema::DeclPtrTy Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
170                                             IdentifierInfo *AliasName,
171                                             SourceLocation AliasLocation,
172                                             IdentifierInfo *ClassName,
173                                             SourceLocation ClassLocation) {
174  // Look for previous declaration of alias name
175  NamedDecl *ADecl = LookupName(TUScope, AliasName, LookupOrdinaryName);
176  if (ADecl) {
177    if (isa<ObjCCompatibleAliasDecl>(ADecl))
178      Diag(AliasLocation, diag::warn_previous_alias_decl);
179    else
180      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
181    Diag(ADecl->getLocation(), diag::note_previous_declaration);
182    return DeclPtrTy();
183  }
184  // Check for class declaration
185  NamedDecl *CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName);
186  if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
187    QualType T = TDecl->getUnderlyingType();
188    if (T->isObjCInterfaceType()) {
189      if (NamedDecl *IDecl = T->getAsObjCInterfaceType()->getDecl()) {
190        ClassName = IDecl->getIdentifier();
191        CDeclU = LookupName(TUScope, ClassName, LookupOrdinaryName);
192      }
193    }
194  }
195  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
196  if (CDecl == 0) {
197    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
198    if (CDeclU)
199      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
200    return DeclPtrTy();
201  }
202
203  // Everything checked out, instantiate a new alias declaration AST.
204  ObjCCompatibleAliasDecl *AliasDecl =
205    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
206
207  ObjCAliasDecls[AliasName] = AliasDecl;
208
209  PushOnScopeChains(AliasDecl, TUScope);
210  if (!CheckObjCDeclScope(AliasDecl))
211    TUScope->AddDecl(DeclPtrTy::make(AliasDecl));
212
213  return DeclPtrTy::make(AliasDecl);
214}
215
216void Sema::CheckForwardProtocolDeclarationForCircularDependency(
217  IdentifierInfo *PName,
218  SourceLocation &Ploc, SourceLocation PrevLoc,
219  const ObjCList<ObjCProtocolDecl> &PList)
220{
221  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
222       E = PList.end(); I != E; ++I) {
223
224    if (ObjCProtocolDecl *PDecl = ObjCProtocols[(*I)->getIdentifier()]) {
225      if (PDecl->getIdentifier() == PName) {
226        Diag(Ploc, diag::err_protocol_has_circular_dependency);
227        Diag(PrevLoc, diag::note_previous_definition);
228      }
229      CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
230        PDecl->getLocation(), PDecl->getReferencedProtocols());
231    }
232  }
233}
234
235Sema::DeclPtrTy
236Sema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
237                                  IdentifierInfo *ProtocolName,
238                                  SourceLocation ProtocolLoc,
239                                  const DeclPtrTy *ProtoRefs,
240                                  unsigned NumProtoRefs,
241                                  SourceLocation EndProtoLoc,
242                                  AttributeList *AttrList) {
243  // FIXME: Deal with AttrList.
244  assert(ProtocolName && "Missing protocol identifier");
245  ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolName];
246  if (PDecl) {
247    // Protocol already seen. Better be a forward protocol declaration
248    if (!PDecl->isForwardDecl()) {
249      Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
250      Diag(PDecl->getLocation(), diag::note_previous_definition);
251      // Just return the protocol we already had.
252      // FIXME: don't leak the objects passed in!
253      return DeclPtrTy::make(PDecl);
254    }
255    ObjCList<ObjCProtocolDecl> PList;
256    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
257    CheckForwardProtocolDeclarationForCircularDependency(
258      ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
259    PList.Destroy(Context);
260
261    // Make sure the cached decl gets a valid start location.
262    PDecl->setLocation(AtProtoInterfaceLoc);
263    PDecl->setForwardDecl(false);
264  } else {
265    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
266                                     AtProtoInterfaceLoc,ProtocolName);
267    // FIXME: PushOnScopeChains?
268    CurContext->addDecl(Context, PDecl);
269    PDecl->setForwardDecl(false);
270    ObjCProtocols[ProtocolName] = PDecl;
271  }
272  if (AttrList)
273    ProcessDeclAttributeList(PDecl, AttrList);
274  if (NumProtoRefs) {
275    /// Check then save referenced protocols.
276    PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,Context);
277    PDecl->setLocEnd(EndProtoLoc);
278  }
279
280  CheckObjCDeclScope(PDecl);
281  return DeclPtrTy::make(PDecl);
282}
283
284/// FindProtocolDeclaration - This routine looks up protocols and
285/// issues an error if they are not declared. It returns list of
286/// protocol declarations in its 'Protocols' argument.
287void
288Sema::FindProtocolDeclaration(bool WarnOnDeclarations,
289                              const IdentifierLocPair *ProtocolId,
290                              unsigned NumProtocols,
291                              llvm::SmallVectorImpl<DeclPtrTy> &Protocols) {
292  for (unsigned i = 0; i != NumProtocols; ++i) {
293    ObjCProtocolDecl *PDecl = ObjCProtocols[ProtocolId[i].first];
294    if (!PDecl) {
295      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
296        << ProtocolId[i].first;
297      continue;
298    }
299
300    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
301
302    // If this is a forward declaration and we are supposed to warn in this
303    // case, do it.
304    if (WarnOnDeclarations && PDecl->isForwardDecl())
305      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
306        << ProtocolId[i].first;
307    Protocols.push_back(DeclPtrTy::make(PDecl));
308  }
309}
310
311/// DiagnosePropertyMismatch - Compares two properties for their
312/// attributes and types and warns on a variety of inconsistencies.
313///
314void
315Sema::DiagnosePropertyMismatch(ObjCPropertyDecl *Property,
316                               ObjCPropertyDecl *SuperProperty,
317                               const IdentifierInfo *inheritedName) {
318  ObjCPropertyDecl::PropertyAttributeKind CAttr =
319  Property->getPropertyAttributes();
320  ObjCPropertyDecl::PropertyAttributeKind SAttr =
321  SuperProperty->getPropertyAttributes();
322  if ((CAttr & ObjCPropertyDecl::OBJC_PR_readonly)
323      && (SAttr & ObjCPropertyDecl::OBJC_PR_readwrite))
324    Diag(Property->getLocation(), diag::warn_readonly_property)
325      << Property->getDeclName() << inheritedName;
326  if ((CAttr & ObjCPropertyDecl::OBJC_PR_copy)
327      != (SAttr & ObjCPropertyDecl::OBJC_PR_copy))
328    Diag(Property->getLocation(), diag::warn_property_attribute)
329      << Property->getDeclName() << "copy" << inheritedName;
330  else if ((CAttr & ObjCPropertyDecl::OBJC_PR_retain)
331           != (SAttr & ObjCPropertyDecl::OBJC_PR_retain))
332    Diag(Property->getLocation(), diag::warn_property_attribute)
333      << Property->getDeclName() << "retain" << inheritedName;
334
335  if ((CAttr & ObjCPropertyDecl::OBJC_PR_nonatomic)
336      != (SAttr & ObjCPropertyDecl::OBJC_PR_nonatomic))
337    Diag(Property->getLocation(), diag::warn_property_attribute)
338      << Property->getDeclName() << "atomic" << inheritedName;
339  if (Property->getSetterName() != SuperProperty->getSetterName())
340    Diag(Property->getLocation(), diag::warn_property_attribute)
341      << Property->getDeclName() << "setter" << inheritedName;
342  if (Property->getGetterName() != SuperProperty->getGetterName())
343    Diag(Property->getLocation(), diag::warn_property_attribute)
344      << Property->getDeclName() << "getter" << inheritedName;
345
346  QualType LHSType =
347    Context.getCanonicalType(SuperProperty->getType());
348  QualType RHSType =
349    Context.getCanonicalType(Property->getType());
350
351  if (!Context.typesAreCompatible(LHSType, RHSType)) {
352    // FIXME: Incorporate this test with typesAreCompatible.
353    if (LHSType->isObjCQualifiedIdType() && RHSType->isObjCQualifiedIdType())
354      if (ObjCQualifiedIdTypesAreCompatible(LHSType, RHSType, false))
355        return;
356    Diag(Property->getLocation(), diag::warn_property_types_are_incompatible)
357      << Property->getType() << SuperProperty->getType() << inheritedName;
358  }
359}
360
361/// ComparePropertiesInBaseAndSuper - This routine compares property
362/// declarations in base and its super class, if any, and issues
363/// diagnostics in a variety of inconsistant situations.
364///
365void Sema::ComparePropertiesInBaseAndSuper(ObjCInterfaceDecl *IDecl) {
366  ObjCInterfaceDecl *SDecl = IDecl->getSuperClass();
367  if (!SDecl)
368    return;
369  // FIXME: O(N^2)
370  for (ObjCInterfaceDecl::prop_iterator S = SDecl->prop_begin(Context),
371       E = SDecl->prop_end(Context); S != E; ++S) {
372    ObjCPropertyDecl *SuperPDecl = (*S);
373    // Does property in super class has declaration in current class?
374    for (ObjCInterfaceDecl::prop_iterator I = IDecl->prop_begin(Context),
375         E = IDecl->prop_end(Context); I != E; ++I) {
376      ObjCPropertyDecl *PDecl = (*I);
377      if (SuperPDecl->getIdentifier() == PDecl->getIdentifier())
378          DiagnosePropertyMismatch(PDecl, SuperPDecl,
379                                   SDecl->getIdentifier());
380    }
381  }
382}
383
384/// MergeOneProtocolPropertiesIntoClass - This routine goes thru the list
385/// of properties declared in a protocol and adds them to the list
386/// of properties for current class/category if it is not there already.
387void
388Sema::MergeOneProtocolPropertiesIntoClass(Decl *CDecl,
389                                          ObjCProtocolDecl *PDecl) {
390  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
391  if (!IDecl) {
392    // Category
393    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
394    assert (CatDecl && "MergeOneProtocolPropertiesIntoClass");
395    for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(Context),
396         E = PDecl->prop_end(Context); P != E; ++P) {
397      ObjCPropertyDecl *Pr = (*P);
398      ObjCCategoryDecl::prop_iterator CP, CE;
399      // Is this property already in  category's list of properties?
400      for (CP = CatDecl->prop_begin(Context), CE = CatDecl->prop_end(Context);
401           CP != CE; ++CP)
402        if ((*CP)->getIdentifier() == Pr->getIdentifier())
403          break;
404      if (CP != CE)
405        // Property protocol already exist in class. Diagnose any mismatch.
406        DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
407    }
408    return;
409  }
410  for (ObjCProtocolDecl::prop_iterator P = PDecl->prop_begin(Context),
411       E = PDecl->prop_end(Context); P != E; ++P) {
412    ObjCPropertyDecl *Pr = (*P);
413    ObjCInterfaceDecl::prop_iterator CP, CE;
414    // Is this property already in  class's list of properties?
415    for (CP = IDecl->prop_begin(Context), CE = IDecl->prop_end(Context);
416         CP != CE; ++CP)
417      if ((*CP)->getIdentifier() == Pr->getIdentifier())
418        break;
419    if (CP != CE)
420      // Property protocol already exist in class. Diagnose any mismatch.
421      DiagnosePropertyMismatch((*CP), Pr, PDecl->getIdentifier());
422    }
423}
424
425/// MergeProtocolPropertiesIntoClass - This routine merges properties
426/// declared in 'MergeItsProtocols' objects (which can be a class or an
427/// inherited protocol into the list of properties for class/category 'CDecl'
428///
429void Sema::MergeProtocolPropertiesIntoClass(Decl *CDecl,
430                                            DeclPtrTy MergeItsProtocols) {
431  Decl *ClassDecl = MergeItsProtocols.getAs<Decl>();
432  ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDecl);
433
434  if (!IDecl) {
435    // Category
436    ObjCCategoryDecl *CatDecl = static_cast<ObjCCategoryDecl*>(CDecl);
437    assert (CatDecl && "MergeProtocolPropertiesIntoClass");
438    if (ObjCCategoryDecl *MDecl = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
439      for (ObjCCategoryDecl::protocol_iterator P = MDecl->protocol_begin(),
440           E = MDecl->protocol_end(); P != E; ++P)
441      // Merge properties of category (*P) into IDECL's
442      MergeOneProtocolPropertiesIntoClass(CatDecl, *P);
443
444      // Go thru the list of protocols for this category and recursively merge
445      // their properties into this class as well.
446      for (ObjCCategoryDecl::protocol_iterator P = CatDecl->protocol_begin(),
447           E = CatDecl->protocol_end(); P != E; ++P)
448        MergeProtocolPropertiesIntoClass(CatDecl, DeclPtrTy::make(*P));
449    } else {
450      ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
451      for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
452           E = MD->protocol_end(); P != E; ++P)
453        MergeOneProtocolPropertiesIntoClass(CatDecl, *P);
454    }
455    return;
456  }
457
458  if (ObjCInterfaceDecl *MDecl = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
459    for (ObjCInterfaceDecl::protocol_iterator P = MDecl->protocol_begin(),
460         E = MDecl->protocol_end(); P != E; ++P)
461      // Merge properties of class (*P) into IDECL's
462      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
463
464    // Go thru the list of protocols for this class and recursively merge
465    // their properties into this class as well.
466    for (ObjCInterfaceDecl::protocol_iterator P = IDecl->protocol_begin(),
467         E = IDecl->protocol_end(); P != E; ++P)
468      MergeProtocolPropertiesIntoClass(IDecl, DeclPtrTy::make(*P));
469  } else {
470    ObjCProtocolDecl *MD = cast<ObjCProtocolDecl>(ClassDecl);
471    for (ObjCProtocolDecl::protocol_iterator P = MD->protocol_begin(),
472         E = MD->protocol_end(); P != E; ++P)
473      MergeOneProtocolPropertiesIntoClass(IDecl, *P);
474  }
475}
476
477/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
478/// a class method in its extension.
479///
480void Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
481                                            ObjCInterfaceDecl *ID) {
482  if (!ID)
483    return;  // Possibly due to previous error
484
485  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
486  for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(Context),
487       e =  ID->meth_end(Context); i != e; ++i) {
488    ObjCMethodDecl *MD = *i;
489    MethodMap[MD->getSelector()] = MD;
490  }
491
492  if (MethodMap.empty())
493    return;
494  for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(Context),
495       e =  CAT->meth_end(Context); i != e; ++i) {
496    ObjCMethodDecl *Method = *i;
497    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
498    if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
499      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
500            << Method->getDeclName();
501      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
502    }
503  }
504}
505
506/// ActOnForwardProtocolDeclaration - Handle @protocol foo;
507Action::DeclPtrTy
508Sema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
509                                      const IdentifierLocPair *IdentList,
510                                      unsigned NumElts,
511                                      AttributeList *attrList) {
512  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
513
514  for (unsigned i = 0; i != NumElts; ++i) {
515    IdentifierInfo *Ident = IdentList[i].first;
516    ObjCProtocolDecl *&PDecl = ObjCProtocols[Ident];
517    if (PDecl == 0) { // Not already seen?
518      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
519                                       IdentList[i].second, Ident);
520      // FIXME: PushOnScopeChains?
521      CurContext->addDecl(Context, PDecl);
522    }
523    if (attrList)
524      ProcessDeclAttributeList(PDecl, attrList);
525    Protocols.push_back(PDecl);
526  }
527
528  ObjCForwardProtocolDecl *PDecl =
529    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
530                                    &Protocols[0], Protocols.size());
531  CurContext->addDecl(Context, PDecl);
532  CheckObjCDeclScope(PDecl);
533  return DeclPtrTy::make(PDecl);
534}
535
536Sema::DeclPtrTy Sema::
537ActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
538                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
539                            IdentifierInfo *CategoryName,
540                            SourceLocation CategoryLoc,
541                            const DeclPtrTy *ProtoRefs,
542                            unsigned NumProtoRefs,
543                            SourceLocation EndProtoLoc) {
544  ObjCCategoryDecl *CDecl =
545    ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc, CategoryName);
546  // FIXME: PushOnScopeChains?
547  CurContext->addDecl(Context, CDecl);
548
549  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
550  /// Check that class of this category is already completely declared.
551  if (!IDecl || IDecl->isForwardDecl()) {
552    CDecl->setInvalidDecl();
553    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
554    return DeclPtrTy::make(CDecl);
555  }
556
557  CDecl->setClassInterface(IDecl);
558
559  // If the interface is deprecated, warn about it.
560  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
561
562  /// Check for duplicate interface declaration for this category
563  ObjCCategoryDecl *CDeclChain;
564  for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
565       CDeclChain = CDeclChain->getNextClassCategory()) {
566    if (CategoryName && CDeclChain->getIdentifier() == CategoryName) {
567      Diag(CategoryLoc, diag::warn_dup_category_def)
568      << ClassName << CategoryName;
569      Diag(CDeclChain->getLocation(), diag::note_previous_definition);
570      break;
571    }
572  }
573  if (!CDeclChain)
574    CDecl->insertNextClassCategory();
575
576  if (NumProtoRefs) {
577    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,Context);
578    CDecl->setLocEnd(EndProtoLoc);
579  }
580
581  CheckObjCDeclScope(CDecl);
582  return DeclPtrTy::make(CDecl);
583}
584
585/// ActOnStartCategoryImplementation - Perform semantic checks on the
586/// category implementation declaration and build an ObjCCategoryImplDecl
587/// object.
588Sema::DeclPtrTy Sema::ActOnStartCategoryImplementation(
589                      SourceLocation AtCatImplLoc,
590                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
591                      IdentifierInfo *CatName, SourceLocation CatLoc) {
592  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName);
593  ObjCCategoryImplDecl *CDecl =
594    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
595                                 IDecl);
596  /// Check that class of this category is already completely declared.
597  if (!IDecl || IDecl->isForwardDecl())
598    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
599
600  // FIXME: PushOnScopeChains?
601  CurContext->addDecl(Context, CDecl);
602
603  /// TODO: Check that CatName, category name, is not used in another
604  // implementation.
605  ObjCCategoryImpls.push_back(CDecl);
606
607  CheckObjCDeclScope(CDecl);
608  return DeclPtrTy::make(CDecl);
609}
610
611Sema::DeclPtrTy Sema::ActOnStartClassImplementation(
612                      SourceLocation AtClassImplLoc,
613                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
614                      IdentifierInfo *SuperClassname,
615                      SourceLocation SuperClassLoc) {
616  ObjCInterfaceDecl* IDecl = 0;
617  // Check for another declaration kind with the same name.
618  NamedDecl *PrevDecl = LookupName(TUScope, ClassName, LookupOrdinaryName);
619  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
620    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
621    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
622  }  else {
623    // Is there an interface declaration of this class; if not, warn!
624    IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
625    if (!IDecl)
626      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
627  }
628
629  // Check that super class name is valid class name
630  ObjCInterfaceDecl* SDecl = 0;
631  if (SuperClassname) {
632    // Check if a different kind of symbol declared in this scope.
633    PrevDecl = LookupName(TUScope, SuperClassname, LookupOrdinaryName);
634    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
635      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
636        << SuperClassname;
637      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
638    } else {
639      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
640      if (!SDecl)
641        Diag(SuperClassLoc, diag::err_undef_superclass)
642          << SuperClassname << ClassName;
643      else if (IDecl && IDecl->getSuperClass() != SDecl) {
644        // This implementation and its interface do not have the same
645        // super class.
646        Diag(SuperClassLoc, diag::err_conflicting_super_class)
647          << SDecl->getDeclName();
648        Diag(SDecl->getLocation(), diag::note_previous_definition);
649      }
650    }
651  }
652
653  if (!IDecl) {
654    // Legacy case of @implementation with no corresponding @interface.
655    // Build, chain & install the interface decl into the identifier.
656
657    // FIXME: Do we support attributes on the @implementation? If so
658    // we should copy them over.
659    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
660                                      ClassName, ClassLoc, false, true);
661    ObjCInterfaceDecls[ClassName] = IDecl;
662    IDecl->setSuperClass(SDecl);
663    IDecl->setLocEnd(ClassLoc);
664
665    // FIXME: PushOnScopeChains?
666    CurContext->addDecl(Context, IDecl);
667    // Remember that this needs to be removed when the scope is popped.
668    TUScope->AddDecl(DeclPtrTy::make(IDecl));
669  } else {
670    // Mark the interface as being completed, even if it was just as
671    //   @class ....;
672    // declaration; the user cannot reopen it.
673    IDecl->setForwardDecl(false);
674  }
675
676  ObjCImplementationDecl* IMPDecl =
677    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
678                                   IDecl, SDecl);
679
680  // FIXME: PushOnScopeChains?
681  CurContext->addDecl(Context, IMPDecl);
682
683  if (CheckObjCDeclScope(IMPDecl))
684    return DeclPtrTy::make(IMPDecl);
685
686  // Check that there is no duplicate implementation of this class.
687  if (ObjCImplementations[ClassName])
688    // FIXME: Don't leak everything!
689    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
690  else // add it to the list.
691    ObjCImplementations[ClassName] = IMPDecl;
692  return DeclPtrTy::make(IMPDecl);
693}
694
695void Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
696                                    ObjCIvarDecl **ivars, unsigned numIvars,
697                                    SourceLocation RBrace) {
698  assert(ImpDecl && "missing implementation decl");
699  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
700  if (!IDecl)
701    return;
702  /// Check case of non-existing @interface decl.
703  /// (legacy objective-c @implementation decl without an @interface decl).
704  /// Add implementations's ivar to the synthesize class's ivar list.
705  if (IDecl->isImplicitInterfaceDecl()) {
706    IDecl->setIVarList(ivars, numIvars, Context);
707    IDecl->setLocEnd(RBrace);
708    return;
709  }
710  // If implementation has empty ivar list, just return.
711  if (numIvars == 0)
712    return;
713
714  assert(ivars && "missing @implementation ivars");
715
716  // Check interface's Ivar list against those in the implementation.
717  // names and types must match.
718  //
719  unsigned j = 0;
720  ObjCInterfaceDecl::ivar_iterator
721    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
722  for (; numIvars > 0 && IVI != IVE; ++IVI) {
723    ObjCIvarDecl* ImplIvar = ivars[j++];
724    ObjCIvarDecl* ClsIvar = *IVI;
725    assert (ImplIvar && "missing implementation ivar");
726    assert (ClsIvar && "missing class ivar");
727
728    // First, make sure the types match.
729    if (Context.getCanonicalType(ImplIvar->getType()) !=
730        Context.getCanonicalType(ClsIvar->getType())) {
731      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
732        << ImplIvar->getIdentifier()
733        << ImplIvar->getType() << ClsIvar->getType();
734      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
735    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
736      Expr *ImplBitWidth = ImplIvar->getBitWidth();
737      Expr *ClsBitWidth = ClsIvar->getBitWidth();
738      if (ImplBitWidth->getIntegerConstantExprValue(Context).getZExtValue() !=
739          ClsBitWidth->getIntegerConstantExprValue(Context).getZExtValue()) {
740        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
741          << ImplIvar->getIdentifier();
742        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
743      }
744    }
745    // Make sure the names are identical.
746    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
747      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
748        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
749      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
750    }
751    --numIvars;
752  }
753
754  if (numIvars > 0)
755    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
756  else if (IVI != IVE)
757    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
758}
759
760void Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
761                               bool &IncompleteImpl) {
762  if (!IncompleteImpl) {
763    Diag(ImpLoc, diag::warn_incomplete_impl);
764    IncompleteImpl = true;
765  }
766  Diag(ImpLoc, diag::warn_undef_method_impl) << method->getDeclName();
767}
768
769void Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
770                                       ObjCMethodDecl *IntfMethodDecl) {
771  if (!Context.typesAreCompatible(IntfMethodDecl->getResultType(),
772                                  ImpMethodDecl->getResultType())) {
773    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_ret_types)
774      << ImpMethodDecl->getDeclName() << IntfMethodDecl->getResultType()
775      << ImpMethodDecl->getResultType();
776    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
777  }
778
779  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
780       IF = IntfMethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
781       IM != EM; ++IM, ++IF) {
782    if (Context.typesAreCompatible((*IF)->getType(), (*IM)->getType()))
783      continue;
784
785    Diag((*IM)->getLocation(), diag::warn_conflicting_param_types)
786      << ImpMethodDecl->getDeclName() << (*IF)->getType()
787      << (*IM)->getType();
788    Diag((*IF)->getLocation(), diag::note_previous_definition);
789  }
790}
791
792/// isPropertyReadonly - Return true if property is readonly, by searching
793/// for the property in the class and in its categories and implementations
794///
795bool Sema::isPropertyReadonly(ObjCPropertyDecl *PDecl,
796                              ObjCInterfaceDecl *IDecl) {
797  // by far the most common case.
798  if (!PDecl->isReadOnly())
799    return false;
800  // Even if property is ready only, if interface has a user defined setter,
801  // it is not considered read only.
802  if (IDecl->getInstanceMethod(Context, PDecl->getSetterName()))
803    return false;
804
805  // Main class has the property as 'readonly'. Must search
806  // through the category list to see if the property's
807  // attribute has been over-ridden to 'readwrite'.
808  for (ObjCCategoryDecl *Category = IDecl->getCategoryList();
809       Category; Category = Category->getNextClassCategory()) {
810    // Even if property is ready only, if a category has a user defined setter,
811    // it is not considered read only.
812    if (Category->getInstanceMethod(Context, PDecl->getSetterName()))
813      return false;
814    ObjCPropertyDecl *P =
815      Category->FindPropertyDeclaration(Context, PDecl->getIdentifier());
816    if (P && !P->isReadOnly())
817      return false;
818  }
819
820  // Also, check for definition of a setter method in the implementation if
821  // all else failed.
822  if (ObjCMethodDecl *OMD = dyn_cast<ObjCMethodDecl>(CurContext)) {
823    if (ObjCImplementationDecl *IMD =
824        dyn_cast<ObjCImplementationDecl>(OMD->getDeclContext())) {
825      if (IMD->getInstanceMethod(Context, PDecl->getSetterName()))
826        return false;
827    }
828    else if (ObjCCategoryImplDecl *CIMD =
829             dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
830      if (CIMD->getInstanceMethod(Context, PDecl->getSetterName()))
831        return false;
832    }
833  }
834  // Lastly, look through the implementation (if one is in scope).
835  if (ObjCImplementationDecl *ImpDecl =
836        ObjCImplementations[IDecl->getIdentifier()])
837    if (ImpDecl->getInstanceMethod(Context, PDecl->getSetterName()))
838      return false;
839  // If all fails, look at the super class.
840  if (ObjCInterfaceDecl *SIDecl = IDecl->getSuperClass())
841    return isPropertyReadonly(PDecl, SIDecl);
842  return true;
843}
844
845/// FIXME: Type hierarchies in Objective-C can be deep. We could most
846/// likely improve the efficiency of selector lookups and type
847/// checking by associating with each protocol / interface / category
848/// the flattened instance tables. If we used an immutable set to keep
849/// the table then it wouldn't add significant memory cost and it
850/// would be handy for lookups.
851
852/// CheckProtocolMethodDefs - This routine checks unimplemented methods
853/// Declared in protocol, and those referenced by it.
854void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
855                                   ObjCProtocolDecl *PDecl,
856                                   bool& IncompleteImpl,
857                                   const llvm::DenseSet<Selector> &InsMap,
858                                   const llvm::DenseSet<Selector> &ClsMap,
859                                   ObjCInterfaceDecl *IDecl) {
860  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
861
862  // If a method lookup fails locally we still need to look and see if
863  // the method was implemented by a base class or an inherited
864  // protocol. This lookup is slow, but occurs rarely in correct code
865  // and otherwise would terminate in a warning.
866
867  // check unimplemented instance methods.
868  for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(Context),
869       E = PDecl->instmeth_end(Context); I != E; ++I) {
870    ObjCMethodDecl *method = *I;
871    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
872        !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
873        (!Super ||
874         !Super->lookupInstanceMethod(Context, method->getSelector()))) {
875        // Ugly, but necessary. Method declared in protcol might have
876        // have been synthesized due to a property declared in the class which
877        // uses the protocol.
878        ObjCMethodDecl *MethodInClass =
879          IDecl->lookupInstanceMethod(Context, method->getSelector());
880        if (!MethodInClass || !MethodInClass->isSynthesized())
881          WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
882      }
883  }
884  // check unimplemented class methods
885  for (ObjCProtocolDecl::classmeth_iterator
886         I = PDecl->classmeth_begin(Context),
887         E = PDecl->classmeth_end(Context);
888       I != E; ++I) {
889    ObjCMethodDecl *method = *I;
890    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
891        !ClsMap.count(method->getSelector()) &&
892        (!Super || !Super->lookupClassMethod(Context, method->getSelector())))
893      WarnUndefinedMethod(ImpLoc, method, IncompleteImpl);
894  }
895  // Check on this protocols's referenced protocols, recursively.
896  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
897       E = PDecl->protocol_end(); PI != E; ++PI)
898    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
899}
900
901void Sema::ImplMethodsVsClassMethods(ObjCImplDecl* IMPDecl,
902                                     ObjCContainerDecl* CDecl,
903                                     bool IncompleteImpl) {
904  llvm::DenseSet<Selector> InsMap;
905  // Check and see if instance methods in class interface have been
906  // implemented in the implementation class.
907  for (ObjCImplementationDecl::instmeth_iterator
908         I = IMPDecl->instmeth_begin(Context),
909         E = IMPDecl->instmeth_end(Context); I != E; ++I)
910    InsMap.insert((*I)->getSelector());
911
912  // Check and see if properties declared in the interface have either 1)
913  // an implementation or 2) there is a @synthesize/@dynamic implementation
914  // of the property in the @implementation.
915  if (isa<ObjCInterfaceDecl>(CDecl))
916      for (ObjCContainerDecl::prop_iterator P = CDecl->prop_begin(Context),
917       E = CDecl->prop_end(Context); P != E; ++P) {
918        ObjCPropertyDecl *Prop = (*P);
919        if (Prop->isInvalidDecl())
920          continue;
921        ObjCPropertyImplDecl *PI = 0;
922        // Is there a matching propery synthesize/dynamic?
923        for (ObjCImplDecl::propimpl_iterator
924               I = IMPDecl->propimpl_begin(Context),
925               EI = IMPDecl->propimpl_end(Context); 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(Context, (*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
971         I = IMPDecl->classmeth_begin(Context),
972         E = IMPDecl->classmeth_end(Context); I != E; ++I)
973    ClsMap.insert((*I)->getSelector());
974
975  for (ObjCInterfaceDecl::classmeth_iterator
976         I = CDecl->classmeth_begin(Context),
977         E = CDecl->classmeth_end(Context);
978       I != E; ++I)
979    if (!ClsMap.count((*I)->getSelector()))
980      WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl);
981    else {
982      ObjCMethodDecl *ImpMethodDecl =
983        IMPDecl->getClassMethod(Context, (*I)->getSelector());
984      ObjCMethodDecl *IntfMethodDecl =
985        CDecl->getClassMethod(Context, (*I)->getSelector());
986      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
987    }
988
989
990  // Check the protocol list for unimplemented methods in the @implementation
991  // class.
992  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
993    for (ObjCCategoryDecl::protocol_iterator PI = I->protocol_begin(),
994         E = I->protocol_end(); PI != E; ++PI)
995      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
996                              InsMap, ClsMap, I);
997    // Check class extensions (unnamed categories)
998    for (ObjCCategoryDecl *Categories = I->getCategoryList();
999         Categories; Categories = Categories->getNextClassCategory()) {
1000      if (!Categories->getIdentifier()) {
1001        ImplMethodsVsClassMethods(IMPDecl, Categories, IncompleteImpl);
1002        break;
1003      }
1004    }
1005  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
1006    for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
1007         E = C->protocol_end(); PI != E; ++PI)
1008      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
1009                              InsMap, ClsMap, C->getClassInterface());
1010  } else
1011    assert(false && "invalid ObjCContainerDecl type.");
1012}
1013
1014/// ActOnForwardClassDeclaration -
1015Action::DeclPtrTy
1016Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1017                                   IdentifierInfo **IdentList,
1018                                   unsigned NumElts) {
1019  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1020
1021  for (unsigned i = 0; i != NumElts; ++i) {
1022    // Check for another declaration kind with the same name.
1023    NamedDecl *PrevDecl = LookupName(TUScope, IdentList[i], LookupOrdinaryName);
1024    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1025      // Maybe we will complain about the shadowed template parameter.
1026      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1027      // Just pretend that we didn't see the previous declaration.
1028      PrevDecl = 0;
1029    }
1030
1031    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1032      // GCC apparently allows the following idiom:
1033      //
1034      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1035      // @class XCElementToggler;
1036      //
1037      // FIXME: Make an extension?
1038      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
1039      if (!TDD || !isa<ObjCInterfaceType>(TDD->getUnderlyingType())) {
1040        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1041        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1042      }
1043    }
1044    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1045    if (!IDecl) {  // Not already seen?  Make a forward decl.
1046      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1047                                        IdentList[i], SourceLocation(), true);
1048      ObjCInterfaceDecls[IdentList[i]] = IDecl;
1049
1050      PushOnScopeChains(IDecl, TUScope);
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(Context, Sel);
1530      ImpDecl->addInstanceMethod(Context, ObjCMethod);
1531    } else {
1532      PrevMethod = ImpDecl->getClassMethod(Context, Sel);
1533      ImpDecl->addClassMethod(Context, ObjCMethod);
1534    }
1535  }
1536  else if (ObjCCategoryImplDecl *CatImpDecl =
1537            dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1538    if (MethodType == tok::minus) {
1539      PrevMethod = CatImpDecl->getInstanceMethod(Context, Sel);
1540      CatImpDecl->addInstanceMethod(Context, ObjCMethod);
1541    } else {
1542      PrevMethod = CatImpDecl->getClassMethod(Context, Sel);
1543      CatImpDecl->addClassMethod(Context, 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  if (IC) {
1902    if (Synthesize)
1903      if (ObjCPropertyImplDecl *PPIDecl =
1904          IC->FindPropertyImplIvarDecl(Context, PropertyIvar)) {
1905        Diag(PropertyLoc, diag::error_duplicate_ivar_use)
1906          << PropertyId << PPIDecl->getPropertyDecl()->getIdentifier()
1907          << PropertyIvar;
1908        Diag(PPIDecl->getLocation(), diag::note_previous_use);
1909      }
1910
1911    if (ObjCPropertyImplDecl *PPIDecl
1912          = IC->FindPropertyImplDecl(Context, PropertyId)) {
1913      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1914      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1915      return DeclPtrTy();
1916    }
1917    IC->addPropertyImplementation(Context, PIDecl);
1918  }
1919  else {
1920    if (Synthesize)
1921      if (ObjCPropertyImplDecl *PPIDecl =
1922          CatImplClass->FindPropertyImplIvarDecl(Context, 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(Context, PropertyId)) {
1931      Diag(PropertyLoc, diag::error_property_implemented) << PropertyId;
1932      Diag(PPIDecl->getLocation(), diag::note_previous_declaration);
1933      return DeclPtrTy();
1934    }
1935    CatImplClass->addPropertyImplementation(Context, 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