SemaDeclObjC.cpp revision 208600
1262395Sbapt//===--- SemaDeclObjC.cpp - Semantic Analysis for ObjC Declarations -------===//
2262395Sbapt//
3262395Sbapt//                     The LLVM Compiler Infrastructure
4262395Sbapt//
5262395Sbapt// This file is distributed under the University of Illinois Open Source
6262395Sbapt// License. See LICENSE.TXT for details.
7262395Sbapt//
8262395Sbapt//===----------------------------------------------------------------------===//
9262395Sbapt//
10262395Sbapt//  This file implements semantic analysis for Objective C declarations.
11262395Sbapt//
12262395Sbapt//===----------------------------------------------------------------------===//
13262395Sbapt
14262395Sbapt#include "Sema.h"
15262395Sbapt#include "Lookup.h"
16262395Sbapt#include "clang/Sema/ExternalSemaSource.h"
17262395Sbapt#include "clang/AST/Expr.h"
18262395Sbapt#include "clang/AST/ASTContext.h"
19262395Sbapt#include "clang/AST/DeclObjC.h"
20262395Sbapt#include "clang/Parse/DeclSpec.h"
21262395Sbaptusing namespace clang;
22262395Sbapt
23262395Sbapt/// ActOnStartOfObjCMethodDef - This routine sets up parameters; invisible
24262395Sbapt/// and user declared, in the method definition's AST.
25262395Sbaptvoid Sema::ActOnStartOfObjCMethodDef(Scope *FnBodyScope, DeclPtrTy D) {
26262395Sbapt  assert(getCurMethodDecl() == 0 && "Method parsing confused");
27262395Sbapt  ObjCMethodDecl *MDecl = dyn_cast_or_null<ObjCMethodDecl>(D.getAs<Decl>());
28262395Sbapt
29262395Sbapt  // If we don't have a valid method decl, simply return.
30262395Sbapt  if (!MDecl)
31262395Sbapt    return;
32262395Sbapt
33262395Sbapt  // Allow the rest of sema to find private method decl implementations.
34262395Sbapt  if (MDecl->isInstanceMethod())
35262395Sbapt    AddInstanceMethodToGlobalPool(MDecl);
36262395Sbapt  else
37262395Sbapt    AddFactoryMethodToGlobalPool(MDecl);
38262395Sbapt
39262395Sbapt  // Allow all of Sema to see that we are entering a method definition.
40262395Sbapt  PushDeclContext(FnBodyScope, MDecl);
41262395Sbapt  PushFunctionScope();
42262395Sbapt
43262395Sbapt  // Create Decl objects for each parameter, entrring them in the scope for
44262395Sbapt  // binding to their use.
45262395Sbapt
46262395Sbapt  // Insert the invisible arguments, self and _cmd!
47262395Sbapt  MDecl->createImplicitParams(Context, MDecl->getClassInterface());
48262395Sbapt
49262395Sbapt  PushOnScopeChains(MDecl->getSelfDecl(), FnBodyScope);
50262395Sbapt  PushOnScopeChains(MDecl->getCmdDecl(), FnBodyScope);
51262395Sbapt
52262395Sbapt  // Introduce all of the other parameters into this scope.
53262395Sbapt  for (ObjCMethodDecl::param_iterator PI = MDecl->param_begin(),
54262395Sbapt       E = MDecl->param_end(); PI != E; ++PI)
55262395Sbapt    if ((*PI)->getIdentifier())
56262395Sbapt      PushOnScopeChains(*PI, FnBodyScope);
57262395Sbapt}
58262395Sbapt
59262395SbaptSema::DeclPtrTy Sema::
60262395SbaptActOnStartClassInterface(SourceLocation AtInterfaceLoc,
61262395Sbapt                         IdentifierInfo *ClassName, SourceLocation ClassLoc,
62262395Sbapt                         IdentifierInfo *SuperName, SourceLocation SuperLoc,
63262395Sbapt                         const DeclPtrTy *ProtoRefs, unsigned NumProtoRefs,
64262395Sbapt                         const SourceLocation *ProtoLocs,
65262395Sbapt                         SourceLocation EndProtoLoc, AttributeList *AttrList) {
66262395Sbapt  assert(ClassName && "Missing class identifier");
67262395Sbapt
68262395Sbapt  // Check for another declaration kind with the same name.
69262395Sbapt  NamedDecl *PrevDecl = LookupSingleName(TUScope, ClassName, ClassLoc,
70262395Sbapt                                         LookupOrdinaryName, ForRedeclaration);
71262395Sbapt
72262395Sbapt  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
73262395Sbapt    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
74262395Sbapt    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
75262395Sbapt  }
76262395Sbapt
77262395Sbapt  ObjCInterfaceDecl* IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
78262395Sbapt  if (IDecl) {
79262395Sbapt    // Class already seen. Is it a forward declaration?
80262395Sbapt    if (!IDecl->isForwardDecl()) {
81262395Sbapt      IDecl->setInvalidDecl();
82262395Sbapt      Diag(AtInterfaceLoc, diag::err_duplicate_class_def)<<IDecl->getDeclName();
83262395Sbapt      Diag(IDecl->getLocation(), diag::note_previous_definition);
84262395Sbapt
85262395Sbapt      // Return the previous class interface.
86262395Sbapt      // FIXME: don't leak the objects passed in!
87262395Sbapt      return DeclPtrTy::make(IDecl);
88262395Sbapt    } else {
89262395Sbapt      IDecl->setLocation(AtInterfaceLoc);
90262395Sbapt      IDecl->setForwardDecl(false);
91262395Sbapt      IDecl->setClassLoc(ClassLoc);
92262395Sbapt
93262395Sbapt      // Since this ObjCInterfaceDecl was created by a forward declaration,
94262395Sbapt      // we now add it to the DeclContext since it wasn't added before
95262395Sbapt      // (see ActOnForwardClassDeclaration).
96262395Sbapt      IDecl->setLexicalDeclContext(CurContext);
97262395Sbapt      CurContext->addDecl(IDecl);
98262395Sbapt
99262395Sbapt      if (AttrList)
100262395Sbapt        ProcessDeclAttributeList(TUScope, IDecl, AttrList);
101262395Sbapt    }
102262395Sbapt  } else {
103262395Sbapt    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtInterfaceLoc,
104262395Sbapt                                      ClassName, ClassLoc);
105262395Sbapt    if (AttrList)
106262395Sbapt      ProcessDeclAttributeList(TUScope, IDecl, AttrList);
107262395Sbapt
108262395Sbapt    PushOnScopeChains(IDecl, TUScope);
109262395Sbapt  }
110262395Sbapt
111262395Sbapt  if (SuperName) {
112262395Sbapt    // Check if a different kind of symbol declared in this scope.
113262395Sbapt    PrevDecl = LookupSingleName(TUScope, SuperName, SuperLoc,
114262395Sbapt                                LookupOrdinaryName);
115262395Sbapt
116262395Sbapt    if (!PrevDecl) {
117262395Sbapt      // Try to correct for a typo in the superclass name.
118262395Sbapt      LookupResult R(*this, SuperName, SuperLoc, LookupOrdinaryName);
119262395Sbapt      if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
120262395Sbapt          (PrevDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
121262395Sbapt        Diag(SuperLoc, diag::err_undef_superclass_suggest)
122262395Sbapt          << SuperName << ClassName << PrevDecl->getDeclName();
123262395Sbapt        Diag(PrevDecl->getLocation(), diag::note_previous_decl)
124262395Sbapt          << PrevDecl->getDeclName();
125262395Sbapt      }
126262395Sbapt    }
127262395Sbapt
128262395Sbapt    if (PrevDecl == IDecl) {
129262395Sbapt      Diag(SuperLoc, diag::err_recursive_superclass)
130262395Sbapt        << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
131262395Sbapt      IDecl->setLocEnd(ClassLoc);
132262395Sbapt    } else {
133262395Sbapt      ObjCInterfaceDecl *SuperClassDecl =
134262395Sbapt                                dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
135262395Sbapt
136262395Sbapt      // Diagnose classes that inherit from deprecated classes.
137262395Sbapt      if (SuperClassDecl)
138262395Sbapt        (void)DiagnoseUseOfDecl(SuperClassDecl, SuperLoc);
139262395Sbapt
140262395Sbapt      if (PrevDecl && SuperClassDecl == 0) {
141262395Sbapt        // The previous declaration was not a class decl. Check if we have a
142262395Sbapt        // typedef. If we do, get the underlying class type.
143262395Sbapt        if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
144262395Sbapt          QualType T = TDecl->getUnderlyingType();
145262395Sbapt          if (T->isObjCObjectType()) {
146262395Sbapt            if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface())
147262395Sbapt              SuperClassDecl = dyn_cast<ObjCInterfaceDecl>(IDecl);
148262395Sbapt          }
149262395Sbapt        }
150262395Sbapt
151262395Sbapt        // This handles the following case:
152262395Sbapt        //
153262395Sbapt        // typedef int SuperClass;
154262395Sbapt        // @interface MyClass : SuperClass {} @end
155262395Sbapt        //
156262395Sbapt        if (!SuperClassDecl) {
157262395Sbapt          Diag(SuperLoc, diag::err_redefinition_different_kind) << SuperName;
158262395Sbapt          Diag(PrevDecl->getLocation(), diag::note_previous_definition);
159262395Sbapt        }
160262395Sbapt      }
161262395Sbapt
162262395Sbapt      if (!dyn_cast_or_null<TypedefDecl>(PrevDecl)) {
163262395Sbapt        if (!SuperClassDecl)
164262395Sbapt          Diag(SuperLoc, diag::err_undef_superclass)
165262395Sbapt            << SuperName << ClassName << SourceRange(AtInterfaceLoc, ClassLoc);
166262395Sbapt        else if (SuperClassDecl->isForwardDecl())
167262395Sbapt          Diag(SuperLoc, diag::err_undef_superclass)
168262395Sbapt            << SuperClassDecl->getDeclName() << ClassName
169262395Sbapt            << SourceRange(AtInterfaceLoc, ClassLoc);
170262395Sbapt      }
171262395Sbapt      IDecl->setSuperClass(SuperClassDecl);
172262395Sbapt      IDecl->setSuperClassLoc(SuperLoc);
173262395Sbapt      IDecl->setLocEnd(SuperLoc);
174262395Sbapt    }
175262395Sbapt  } else { // we have a root class.
176262395Sbapt    IDecl->setLocEnd(ClassLoc);
177262395Sbapt  }
178262395Sbapt
179262395Sbapt  /// Check then save referenced protocols.
180262395Sbapt  if (NumProtoRefs) {
181262395Sbapt    IDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
182262395Sbapt                           ProtoLocs, Context);
183262395Sbapt    IDecl->setLocEnd(EndProtoLoc);
184262395Sbapt  }
185262395Sbapt
186262395Sbapt  CheckObjCDeclScope(IDecl);
187262395Sbapt  return DeclPtrTy::make(IDecl);
188262395Sbapt}
189262395Sbapt
190262395Sbapt/// ActOnCompatiblityAlias - this action is called after complete parsing of
191262395Sbapt/// @compatibility_alias declaration. It sets up the alias relationships.
192262395SbaptSema::DeclPtrTy Sema::ActOnCompatiblityAlias(SourceLocation AtLoc,
193262395Sbapt                                             IdentifierInfo *AliasName,
194262395Sbapt                                             SourceLocation AliasLocation,
195262395Sbapt                                             IdentifierInfo *ClassName,
196262395Sbapt                                             SourceLocation ClassLocation) {
197262395Sbapt  // Look for previous declaration of alias name
198262395Sbapt  NamedDecl *ADecl = LookupSingleName(TUScope, AliasName, AliasLocation,
199262395Sbapt                                      LookupOrdinaryName, ForRedeclaration);
200262395Sbapt  if (ADecl) {
201262395Sbapt    if (isa<ObjCCompatibleAliasDecl>(ADecl))
202262395Sbapt      Diag(AliasLocation, diag::warn_previous_alias_decl);
203262395Sbapt    else
204262395Sbapt      Diag(AliasLocation, diag::err_conflicting_aliasing_type) << AliasName;
205262395Sbapt    Diag(ADecl->getLocation(), diag::note_previous_declaration);
206262395Sbapt    return DeclPtrTy();
207262395Sbapt  }
208262395Sbapt  // Check for class declaration
209262395Sbapt  NamedDecl *CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
210262395Sbapt                                       LookupOrdinaryName, ForRedeclaration);
211262395Sbapt  if (const TypedefDecl *TDecl = dyn_cast_or_null<TypedefDecl>(CDeclU)) {
212262395Sbapt    QualType T = TDecl->getUnderlyingType();
213262395Sbapt    if (T->isObjCObjectType()) {
214262395Sbapt      if (NamedDecl *IDecl = T->getAs<ObjCObjectType>()->getInterface()) {
215262395Sbapt        ClassName = IDecl->getIdentifier();
216262395Sbapt        CDeclU = LookupSingleName(TUScope, ClassName, ClassLocation,
217262395Sbapt                                  LookupOrdinaryName, ForRedeclaration);
218262395Sbapt      }
219262395Sbapt    }
220262395Sbapt  }
221262395Sbapt  ObjCInterfaceDecl *CDecl = dyn_cast_or_null<ObjCInterfaceDecl>(CDeclU);
222262395Sbapt  if (CDecl == 0) {
223262395Sbapt    Diag(ClassLocation, diag::warn_undef_interface) << ClassName;
224262395Sbapt    if (CDeclU)
225262395Sbapt      Diag(CDeclU->getLocation(), diag::note_previous_declaration);
226262395Sbapt    return DeclPtrTy();
227262395Sbapt  }
228262395Sbapt
229262395Sbapt  // Everything checked out, instantiate a new alias declaration AST.
230262395Sbapt  ObjCCompatibleAliasDecl *AliasDecl =
231262395Sbapt    ObjCCompatibleAliasDecl::Create(Context, CurContext, AtLoc, AliasName, CDecl);
232262395Sbapt
233262395Sbapt  if (!CheckObjCDeclScope(AliasDecl))
234262395Sbapt    PushOnScopeChains(AliasDecl, TUScope);
235262395Sbapt
236262395Sbapt  return DeclPtrTy::make(AliasDecl);
237262395Sbapt}
238262395Sbapt
239262395Sbaptvoid Sema::CheckForwardProtocolDeclarationForCircularDependency(
240262395Sbapt  IdentifierInfo *PName,
241262395Sbapt  SourceLocation &Ploc, SourceLocation PrevLoc,
242262395Sbapt  const ObjCList<ObjCProtocolDecl> &PList) {
243262395Sbapt  for (ObjCList<ObjCProtocolDecl>::iterator I = PList.begin(),
244262395Sbapt       E = PList.end(); I != E; ++I) {
245262395Sbapt
246262395Sbapt    if (ObjCProtocolDecl *PDecl = LookupProtocol((*I)->getIdentifier(),
247262395Sbapt                                                 Ploc)) {
248262395Sbapt      if (PDecl->getIdentifier() == PName) {
249262395Sbapt        Diag(Ploc, diag::err_protocol_has_circular_dependency);
250262395Sbapt        Diag(PrevLoc, diag::note_previous_definition);
251262395Sbapt      }
252262395Sbapt      CheckForwardProtocolDeclarationForCircularDependency(PName, Ploc,
253262395Sbapt        PDecl->getLocation(), PDecl->getReferencedProtocols());
254262395Sbapt    }
255262395Sbapt  }
256262395Sbapt}
257262395Sbapt
258262395SbaptSema::DeclPtrTy
259262395SbaptSema::ActOnStartProtocolInterface(SourceLocation AtProtoInterfaceLoc,
260262395Sbapt                                  IdentifierInfo *ProtocolName,
261262395Sbapt                                  SourceLocation ProtocolLoc,
262262395Sbapt                                  const DeclPtrTy *ProtoRefs,
263262395Sbapt                                  unsigned NumProtoRefs,
264262395Sbapt                                  const SourceLocation *ProtoLocs,
265262395Sbapt                                  SourceLocation EndProtoLoc,
266262395Sbapt                                  AttributeList *AttrList) {
267262395Sbapt  // FIXME: Deal with AttrList.
268262395Sbapt  assert(ProtocolName && "Missing protocol identifier");
269262395Sbapt  ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolName, ProtocolLoc);
270262395Sbapt  if (PDecl) {
271262395Sbapt    // Protocol already seen. Better be a forward protocol declaration
272262395Sbapt    if (!PDecl->isForwardDecl()) {
273262395Sbapt      Diag(ProtocolLoc, diag::warn_duplicate_protocol_def) << ProtocolName;
274262395Sbapt      Diag(PDecl->getLocation(), diag::note_previous_definition);
275262395Sbapt      // Just return the protocol we already had.
276262395Sbapt      // FIXME: don't leak the objects passed in!
277262395Sbapt      return DeclPtrTy::make(PDecl);
278262395Sbapt    }
279262395Sbapt    ObjCList<ObjCProtocolDecl> PList;
280262395Sbapt    PList.set((ObjCProtocolDecl *const*)ProtoRefs, NumProtoRefs, Context);
281262395Sbapt    CheckForwardProtocolDeclarationForCircularDependency(
282262395Sbapt      ProtocolName, ProtocolLoc, PDecl->getLocation(), PList);
283262395Sbapt    PList.Destroy(Context);
284262395Sbapt
285262395Sbapt    // Make sure the cached decl gets a valid start location.
286262395Sbapt    PDecl->setLocation(AtProtoInterfaceLoc);
287262395Sbapt    PDecl->setForwardDecl(false);
288262395Sbapt  } else {
289262395Sbapt    PDecl = ObjCProtocolDecl::Create(Context, CurContext,
290262395Sbapt                                     AtProtoInterfaceLoc,ProtocolName);
291262395Sbapt    PushOnScopeChains(PDecl, TUScope);
292262395Sbapt    PDecl->setForwardDecl(false);
293262395Sbapt  }
294262395Sbapt  if (AttrList)
295262395Sbapt    ProcessDeclAttributeList(TUScope, PDecl, AttrList);
296262395Sbapt  if (NumProtoRefs) {
297262395Sbapt    /// Check then save referenced protocols.
298262395Sbapt    PDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
299262395Sbapt                           ProtoLocs, Context);
300262395Sbapt    PDecl->setLocEnd(EndProtoLoc);
301262395Sbapt  }
302262395Sbapt
303262395Sbapt  CheckObjCDeclScope(PDecl);
304262395Sbapt  return DeclPtrTy::make(PDecl);
305262395Sbapt}
306262395Sbapt
307262395Sbapt/// FindProtocolDeclaration - This routine looks up protocols and
308262395Sbapt/// issues an error if they are not declared. It returns list of
309262395Sbapt/// protocol declarations in its 'Protocols' argument.
310262395Sbaptvoid
311262395SbaptSema::FindProtocolDeclaration(bool WarnOnDeclarations,
312262395Sbapt                              const IdentifierLocPair *ProtocolId,
313262395Sbapt                              unsigned NumProtocols,
314262395Sbapt                              llvm::SmallVectorImpl<DeclPtrTy> &Protocols) {
315262395Sbapt  for (unsigned i = 0; i != NumProtocols; ++i) {
316262395Sbapt    ObjCProtocolDecl *PDecl = LookupProtocol(ProtocolId[i].first,
317262395Sbapt                                             ProtocolId[i].second);
318262395Sbapt    if (!PDecl) {
319262395Sbapt      LookupResult R(*this, ProtocolId[i].first, ProtocolId[i].second,
320262395Sbapt                     LookupObjCProtocolName);
321262395Sbapt      if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
322262395Sbapt          (PDecl = R.getAsSingle<ObjCProtocolDecl>())) {
323262395Sbapt        Diag(ProtocolId[i].second, diag::err_undeclared_protocol_suggest)
324262395Sbapt          << ProtocolId[i].first << R.getLookupName();
325262395Sbapt        Diag(PDecl->getLocation(), diag::note_previous_decl)
326262395Sbapt          << PDecl->getDeclName();
327262395Sbapt      }
328262395Sbapt    }
329262395Sbapt
330262395Sbapt    if (!PDecl) {
331262395Sbapt      Diag(ProtocolId[i].second, diag::err_undeclared_protocol)
332262395Sbapt        << ProtocolId[i].first;
333262395Sbapt      continue;
334262395Sbapt    }
335262395Sbapt
336262395Sbapt    (void)DiagnoseUseOfDecl(PDecl, ProtocolId[i].second);
337262395Sbapt
338262395Sbapt    // If this is a forward declaration and we are supposed to warn in this
339262395Sbapt    // case, do it.
340262395Sbapt    if (WarnOnDeclarations && PDecl->isForwardDecl())
341262395Sbapt      Diag(ProtocolId[i].second, diag::warn_undef_protocolref)
342262395Sbapt        << ProtocolId[i].first;
343262395Sbapt    Protocols.push_back(DeclPtrTy::make(PDecl));
344262395Sbapt  }
345262395Sbapt}
346262395Sbapt
347262395Sbapt/// DiagnoseClassExtensionDupMethods - Check for duplicate declaration of
348262395Sbapt/// a class method in its extension.
349262395Sbapt///
350262395Sbaptvoid Sema::DiagnoseClassExtensionDupMethods(ObjCCategoryDecl *CAT,
351262395Sbapt                                            ObjCInterfaceDecl *ID) {
352262395Sbapt  if (!ID)
353262395Sbapt    return;  // Possibly due to previous error
354262395Sbapt
355262395Sbapt  llvm::DenseMap<Selector, const ObjCMethodDecl*> MethodMap;
356262395Sbapt  for (ObjCInterfaceDecl::method_iterator i = ID->meth_begin(),
357262395Sbapt       e =  ID->meth_end(); i != e; ++i) {
358262395Sbapt    ObjCMethodDecl *MD = *i;
359262395Sbapt    MethodMap[MD->getSelector()] = MD;
360262395Sbapt  }
361262395Sbapt
362262395Sbapt  if (MethodMap.empty())
363262395Sbapt    return;
364262395Sbapt  for (ObjCCategoryDecl::method_iterator i = CAT->meth_begin(),
365262395Sbapt       e =  CAT->meth_end(); i != e; ++i) {
366262395Sbapt    ObjCMethodDecl *Method = *i;
367262395Sbapt    const ObjCMethodDecl *&PrevMethod = MethodMap[Method->getSelector()];
368262395Sbapt    if (PrevMethod && !MatchTwoMethodDeclarations(Method, PrevMethod)) {
369262395Sbapt      Diag(Method->getLocation(), diag::err_duplicate_method_decl)
370262395Sbapt            << Method->getDeclName();
371262395Sbapt      Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
372262395Sbapt    }
373262395Sbapt  }
374262395Sbapt}
375262395Sbapt
376262395Sbapt/// ActOnForwardProtocolDeclaration - Handle @protocol foo;
377262395SbaptAction::DeclPtrTy
378262395SbaptSema::ActOnForwardProtocolDeclaration(SourceLocation AtProtocolLoc,
379262395Sbapt                                      const IdentifierLocPair *IdentList,
380262395Sbapt                                      unsigned NumElts,
381262395Sbapt                                      AttributeList *attrList) {
382262395Sbapt  llvm::SmallVector<ObjCProtocolDecl*, 32> Protocols;
383262395Sbapt  llvm::SmallVector<SourceLocation, 8> ProtoLocs;
384262395Sbapt
385262395Sbapt  for (unsigned i = 0; i != NumElts; ++i) {
386262395Sbapt    IdentifierInfo *Ident = IdentList[i].first;
387262395Sbapt    ObjCProtocolDecl *PDecl = LookupProtocol(Ident, IdentList[i].second);
388262395Sbapt    if (PDecl == 0) { // Not already seen?
389262395Sbapt      PDecl = ObjCProtocolDecl::Create(Context, CurContext,
390262395Sbapt                                       IdentList[i].second, Ident);
391262395Sbapt      PushOnScopeChains(PDecl, TUScope);
392262395Sbapt    }
393262395Sbapt    if (attrList)
394262395Sbapt      ProcessDeclAttributeList(TUScope, PDecl, attrList);
395262395Sbapt    Protocols.push_back(PDecl);
396262395Sbapt    ProtoLocs.push_back(IdentList[i].second);
397262395Sbapt  }
398262395Sbapt
399262395Sbapt  ObjCForwardProtocolDecl *PDecl =
400262395Sbapt    ObjCForwardProtocolDecl::Create(Context, CurContext, AtProtocolLoc,
401262395Sbapt                                    Protocols.data(), Protocols.size(),
402262395Sbapt                                    ProtoLocs.data());
403262395Sbapt  CurContext->addDecl(PDecl);
404262395Sbapt  CheckObjCDeclScope(PDecl);
405262395Sbapt  return DeclPtrTy::make(PDecl);
406262395Sbapt}
407262395Sbapt
408262395SbaptSema::DeclPtrTy Sema::
409262395SbaptActOnStartCategoryInterface(SourceLocation AtInterfaceLoc,
410262395Sbapt                            IdentifierInfo *ClassName, SourceLocation ClassLoc,
411262395Sbapt                            IdentifierInfo *CategoryName,
412262395Sbapt                            SourceLocation CategoryLoc,
413262395Sbapt                            const DeclPtrTy *ProtoRefs,
414262395Sbapt                            unsigned NumProtoRefs,
415262395Sbapt                            const SourceLocation *ProtoLocs,
416262395Sbapt                            SourceLocation EndProtoLoc) {
417262395Sbapt  ObjCCategoryDecl *CDecl = 0;
418262395Sbapt  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
419262395Sbapt
420262395Sbapt  /// Check that class of this category is already completely declared.
421262395Sbapt  if (!IDecl || IDecl->isForwardDecl()) {
422262395Sbapt    // Create an invalid ObjCCategoryDecl to serve as context for
423262395Sbapt    // the enclosing method declarations.  We mark the decl invalid
424262395Sbapt    // to make it clear that this isn't a valid AST.
425262395Sbapt    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
426262395Sbapt                                     ClassLoc, CategoryLoc, CategoryName);
427262395Sbapt    CDecl->setInvalidDecl();
428262395Sbapt    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
429262395Sbapt    return DeclPtrTy::make(CDecl);
430262395Sbapt  }
431262395Sbapt
432262395Sbapt  if (!CategoryName) {
433262395Sbapt    // Class extensions require a special treatment. Use an existing one.
434262395Sbapt    // Note that 'getClassExtension()' can return NULL.
435262395Sbapt    CDecl = IDecl->getClassExtension();
436262395Sbapt    if (IDecl->getImplementation()) {
437262395Sbapt      Diag(ClassLoc, diag::err_class_extension_after_impl) << ClassName;
438262395Sbapt      Diag(IDecl->getImplementation()->getLocation(),
439262395Sbapt           diag::note_implementation_declared);
440262395Sbapt    }
441262395Sbapt  }
442262395Sbapt
443262395Sbapt  if (!CDecl) {
444262395Sbapt    CDecl = ObjCCategoryDecl::Create(Context, CurContext, AtInterfaceLoc,
445262395Sbapt                                     ClassLoc, CategoryLoc, CategoryName);
446262395Sbapt    // FIXME: PushOnScopeChains?
447262395Sbapt    CurContext->addDecl(CDecl);
448262395Sbapt
449262395Sbapt    CDecl->setClassInterface(IDecl);
450262395Sbapt    // Insert first use of class extension to the list of class's categories.
451262395Sbapt    if (!CategoryName)
452262395Sbapt      CDecl->insertNextClassCategory();
453262395Sbapt  }
454262395Sbapt
455262395Sbapt  // If the interface is deprecated, warn about it.
456262395Sbapt  (void)DiagnoseUseOfDecl(IDecl, ClassLoc);
457262395Sbapt
458262395Sbapt  if (CategoryName) {
459262395Sbapt    /// Check for duplicate interface declaration for this category
460262395Sbapt    ObjCCategoryDecl *CDeclChain;
461262395Sbapt    for (CDeclChain = IDecl->getCategoryList(); CDeclChain;
462262395Sbapt         CDeclChain = CDeclChain->getNextClassCategory()) {
463262395Sbapt      if (CDeclChain->getIdentifier() == CategoryName) {
464262395Sbapt        // Class extensions can be declared multiple times.
465262395Sbapt        Diag(CategoryLoc, diag::warn_dup_category_def)
466262395Sbapt          << ClassName << CategoryName;
467262395Sbapt        Diag(CDeclChain->getLocation(), diag::note_previous_definition);
468262395Sbapt        break;
469262395Sbapt      }
470262395Sbapt    }
471262395Sbapt    if (!CDeclChain)
472262395Sbapt      CDecl->insertNextClassCategory();
473262395Sbapt  }
474262395Sbapt
475262395Sbapt  if (NumProtoRefs) {
476262395Sbapt    CDecl->setProtocolList((ObjCProtocolDecl**)ProtoRefs, NumProtoRefs,
477262395Sbapt                           ProtoLocs, Context);
478262395Sbapt    // Protocols in the class extension belong to the class.
479262395Sbapt    if (CDecl->IsClassExtension())
480262395Sbapt     IDecl->mergeClassExtensionProtocolList((ObjCProtocolDecl**)ProtoRefs,
481262395Sbapt                                            NumProtoRefs, ProtoLocs,
482262395Sbapt                                            Context);
483262395Sbapt  }
484262395Sbapt
485262395Sbapt  CheckObjCDeclScope(CDecl);
486262395Sbapt  return DeclPtrTy::make(CDecl);
487262395Sbapt}
488262395Sbapt
489262395Sbapt/// ActOnStartCategoryImplementation - Perform semantic checks on the
490262395Sbapt/// category implementation declaration and build an ObjCCategoryImplDecl
491262395Sbapt/// object.
492262395SbaptSema::DeclPtrTy Sema::ActOnStartCategoryImplementation(
493262395Sbapt                      SourceLocation AtCatImplLoc,
494262395Sbapt                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
495262395Sbapt                      IdentifierInfo *CatName, SourceLocation CatLoc) {
496262395Sbapt  ObjCInterfaceDecl *IDecl = getObjCInterfaceDecl(ClassName, ClassLoc, true);
497262395Sbapt  ObjCCategoryDecl *CatIDecl = 0;
498262395Sbapt  if (IDecl) {
499262395Sbapt    CatIDecl = IDecl->FindCategoryDeclaration(CatName);
500262395Sbapt    if (!CatIDecl) {
501262395Sbapt      // Category @implementation with no corresponding @interface.
502262395Sbapt      // Create and install one.
503262395Sbapt      CatIDecl = ObjCCategoryDecl::Create(Context, CurContext, SourceLocation(),
504262395Sbapt                                          SourceLocation(), SourceLocation(),
505262395Sbapt                                          CatName);
506262395Sbapt      CatIDecl->setClassInterface(IDecl);
507262395Sbapt      CatIDecl->insertNextClassCategory();
508262395Sbapt    }
509262395Sbapt  }
510262395Sbapt
511262395Sbapt  ObjCCategoryImplDecl *CDecl =
512262395Sbapt    ObjCCategoryImplDecl::Create(Context, CurContext, AtCatImplLoc, CatName,
513262395Sbapt                                 IDecl);
514262395Sbapt  /// Check that class of this category is already completely declared.
515262395Sbapt  if (!IDecl || IDecl->isForwardDecl())
516262395Sbapt    Diag(ClassLoc, diag::err_undef_interface) << ClassName;
517262395Sbapt
518262395Sbapt  // FIXME: PushOnScopeChains?
519262395Sbapt  CurContext->addDecl(CDecl);
520262395Sbapt
521262395Sbapt  /// Check that CatName, category name, is not used in another implementation.
522262395Sbapt  if (CatIDecl) {
523262395Sbapt    if (CatIDecl->getImplementation()) {
524262395Sbapt      Diag(ClassLoc, diag::err_dup_implementation_category) << ClassName
525262395Sbapt        << CatName;
526262395Sbapt      Diag(CatIDecl->getImplementation()->getLocation(),
527262395Sbapt           diag::note_previous_definition);
528262395Sbapt    } else
529262395Sbapt      CatIDecl->setImplementation(CDecl);
530262395Sbapt  }
531262395Sbapt
532262395Sbapt  CheckObjCDeclScope(CDecl);
533262395Sbapt  return DeclPtrTy::make(CDecl);
534262395Sbapt}
535262395Sbapt
536262395SbaptSema::DeclPtrTy Sema::ActOnStartClassImplementation(
537262395Sbapt                      SourceLocation AtClassImplLoc,
538262395Sbapt                      IdentifierInfo *ClassName, SourceLocation ClassLoc,
539262395Sbapt                      IdentifierInfo *SuperClassname,
540262395Sbapt                      SourceLocation SuperClassLoc) {
541262395Sbapt  ObjCInterfaceDecl* IDecl = 0;
542262395Sbapt  // Check for another declaration kind with the same name.
543262395Sbapt  NamedDecl *PrevDecl
544262395Sbapt    = LookupSingleName(TUScope, ClassName, ClassLoc, LookupOrdinaryName,
545262395Sbapt                       ForRedeclaration);
546262395Sbapt  if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
547262395Sbapt    Diag(ClassLoc, diag::err_redefinition_different_kind) << ClassName;
548262395Sbapt    Diag(PrevDecl->getLocation(), diag::note_previous_definition);
549262395Sbapt  } else if ((IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl))) {
550262395Sbapt    // If this is a forward declaration of an interface, warn.
551262395Sbapt    if (IDecl->isForwardDecl()) {
552262395Sbapt      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
553262395Sbapt      IDecl = 0;
554262395Sbapt    }
555262395Sbapt  } else {
556262395Sbapt    // We did not find anything with the name ClassName; try to correct for
557262395Sbapt    // typos in the class name.
558262395Sbapt    LookupResult R(*this, ClassName, ClassLoc, LookupOrdinaryName);
559262395Sbapt    if (CorrectTypo(R, TUScope, 0, 0, false, CTC_NoKeywords) &&
560262395Sbapt        (IDecl = R.getAsSingle<ObjCInterfaceDecl>())) {
561262395Sbapt      // Suggest the (potentially) correct interface name. However, put the
562262395Sbapt      // fix-it hint itself in a separate note, since changing the name in
563262395Sbapt      // the warning would make the fix-it change semantics.However, don't
564262395Sbapt      // provide a code-modification hint or use the typo name for recovery,
565262395Sbapt      // because this is just a warning. The program may actually be correct.
566262395Sbapt      Diag(ClassLoc, diag::warn_undef_interface_suggest)
567262395Sbapt        << ClassName << R.getLookupName();
568262395Sbapt      Diag(IDecl->getLocation(), diag::note_previous_decl)
569262395Sbapt        << R.getLookupName()
570262395Sbapt        << FixItHint::CreateReplacement(ClassLoc,
571262395Sbapt                                        R.getLookupName().getAsString());
572262395Sbapt      IDecl = 0;
573262395Sbapt    } else {
574262395Sbapt      Diag(ClassLoc, diag::warn_undef_interface) << ClassName;
575262395Sbapt    }
576262395Sbapt  }
577262395Sbapt
578262395Sbapt  // Check that super class name is valid class name
579262395Sbapt  ObjCInterfaceDecl* SDecl = 0;
580262395Sbapt  if (SuperClassname) {
581262395Sbapt    // Check if a different kind of symbol declared in this scope.
582262395Sbapt    PrevDecl = LookupSingleName(TUScope, SuperClassname, SuperClassLoc,
583262395Sbapt                                LookupOrdinaryName);
584262395Sbapt    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
585262395Sbapt      Diag(SuperClassLoc, diag::err_redefinition_different_kind)
586262395Sbapt        << SuperClassname;
587262395Sbapt      Diag(PrevDecl->getLocation(), diag::note_previous_definition);
588262395Sbapt    } else {
589262395Sbapt      SDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
590262395Sbapt      if (!SDecl)
591262395Sbapt        Diag(SuperClassLoc, diag::err_undef_superclass)
592262395Sbapt          << SuperClassname << ClassName;
593262395Sbapt      else if (IDecl && IDecl->getSuperClass() != SDecl) {
594262395Sbapt        // This implementation and its interface do not have the same
595262395Sbapt        // super class.
596262395Sbapt        Diag(SuperClassLoc, diag::err_conflicting_super_class)
597262395Sbapt          << SDecl->getDeclName();
598262395Sbapt        Diag(SDecl->getLocation(), diag::note_previous_definition);
599262395Sbapt      }
600262395Sbapt    }
601262395Sbapt  }
602262395Sbapt
603262395Sbapt  if (!IDecl) {
604262395Sbapt    // Legacy case of @implementation with no corresponding @interface.
605262395Sbapt    // Build, chain & install the interface decl into the identifier.
606262395Sbapt
607262395Sbapt    // FIXME: Do we support attributes on the @implementation? If so we should
608262395Sbapt    // copy them over.
609262395Sbapt    IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassImplLoc,
610262395Sbapt                                      ClassName, ClassLoc, false, true);
611262395Sbapt    IDecl->setSuperClass(SDecl);
612262395Sbapt    IDecl->setLocEnd(ClassLoc);
613262395Sbapt
614262395Sbapt    PushOnScopeChains(IDecl, TUScope);
615262395Sbapt  } else {
616262395Sbapt    // Mark the interface as being completed, even if it was just as
617262395Sbapt    //   @class ....;
618262395Sbapt    // declaration; the user cannot reopen it.
619262395Sbapt    IDecl->setForwardDecl(false);
620262395Sbapt  }
621262395Sbapt
622262395Sbapt  ObjCImplementationDecl* IMPDecl =
623262395Sbapt    ObjCImplementationDecl::Create(Context, CurContext, AtClassImplLoc,
624262395Sbapt                                   IDecl, SDecl);
625262395Sbapt
626262395Sbapt  if (CheckObjCDeclScope(IMPDecl))
627262395Sbapt    return DeclPtrTy::make(IMPDecl);
628262395Sbapt
629262395Sbapt  // Check that there is no duplicate implementation of this class.
630262395Sbapt  if (IDecl->getImplementation()) {
631262395Sbapt    // FIXME: Don't leak everything!
632262395Sbapt    Diag(ClassLoc, diag::err_dup_implementation_class) << ClassName;
633262395Sbapt    Diag(IDecl->getImplementation()->getLocation(),
634262395Sbapt         diag::note_previous_definition);
635262395Sbapt  } else { // add it to the list.
636262395Sbapt    IDecl->setImplementation(IMPDecl);
637262395Sbapt    PushOnScopeChains(IMPDecl, TUScope);
638262395Sbapt  }
639262395Sbapt  return DeclPtrTy::make(IMPDecl);
640262395Sbapt}
641262395Sbapt
642262395Sbaptvoid Sema::CheckImplementationIvars(ObjCImplementationDecl *ImpDecl,
643262395Sbapt                                    ObjCIvarDecl **ivars, unsigned numIvars,
644262395Sbapt                                    SourceLocation RBrace) {
645262395Sbapt  assert(ImpDecl && "missing implementation decl");
646262395Sbapt  ObjCInterfaceDecl* IDecl = ImpDecl->getClassInterface();
647262395Sbapt  if (!IDecl)
648262395Sbapt    return;
649262395Sbapt  /// Check case of non-existing @interface decl.
650262395Sbapt  /// (legacy objective-c @implementation decl without an @interface decl).
651262395Sbapt  /// Add implementations's ivar to the synthesize class's ivar list.
652262395Sbapt  if (IDecl->isImplicitInterfaceDecl()) {
653262395Sbapt    IDecl->setLocEnd(RBrace);
654262395Sbapt    // Add ivar's to class's DeclContext.
655262395Sbapt    for (unsigned i = 0, e = numIvars; i != e; ++i) {
656262395Sbapt      ivars[i]->setLexicalDeclContext(ImpDecl);
657262395Sbapt      IDecl->makeDeclVisibleInContext(ivars[i], false);
658262395Sbapt      ImpDecl->addDecl(ivars[i]);
659262395Sbapt    }
660262395Sbapt
661262395Sbapt    return;
662262395Sbapt  }
663262395Sbapt  // If implementation has empty ivar list, just return.
664262395Sbapt  if (numIvars == 0)
665262395Sbapt    return;
666262395Sbapt
667262395Sbapt  assert(ivars && "missing @implementation ivars");
668262395Sbapt  if (LangOpts.ObjCNonFragileABI2) {
669262395Sbapt    if (ImpDecl->getSuperClass())
670262395Sbapt      Diag(ImpDecl->getLocation(), diag::warn_on_superclass_use);
671262395Sbapt    for (unsigned i = 0; i < numIvars; i++) {
672262395Sbapt      ObjCIvarDecl* ImplIvar = ivars[i];
673262395Sbapt      if (const ObjCIvarDecl *ClsIvar =
674262395Sbapt            IDecl->getIvarDecl(ImplIvar->getIdentifier())) {
675262395Sbapt        Diag(ImplIvar->getLocation(), diag::err_duplicate_ivar_declaration);
676262395Sbapt        Diag(ClsIvar->getLocation(), diag::note_previous_definition);
677262395Sbapt        continue;
678262395Sbapt      }
679262395Sbapt      // Instance ivar to Implementation's DeclContext.
680262395Sbapt      ImplIvar->setLexicalDeclContext(ImpDecl);
681262395Sbapt      IDecl->makeDeclVisibleInContext(ImplIvar, false);
682262395Sbapt      ImpDecl->addDecl(ImplIvar);
683262395Sbapt    }
684262395Sbapt    return;
685262395Sbapt  }
686262395Sbapt  // Check interface's Ivar list against those in the implementation.
687262395Sbapt  // names and types must match.
688262395Sbapt  //
689262395Sbapt  unsigned j = 0;
690262395Sbapt  ObjCInterfaceDecl::ivar_iterator
691262395Sbapt    IVI = IDecl->ivar_begin(), IVE = IDecl->ivar_end();
692262395Sbapt  for (; numIvars > 0 && IVI != IVE; ++IVI) {
693262395Sbapt    ObjCIvarDecl* ImplIvar = ivars[j++];
694262395Sbapt    ObjCIvarDecl* ClsIvar = *IVI;
695262395Sbapt    assert (ImplIvar && "missing implementation ivar");
696262395Sbapt    assert (ClsIvar && "missing class ivar");
697262395Sbapt
698262395Sbapt    // First, make sure the types match.
699262395Sbapt    if (Context.getCanonicalType(ImplIvar->getType()) !=
700262395Sbapt        Context.getCanonicalType(ClsIvar->getType())) {
701262395Sbapt      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_type)
702262395Sbapt        << ImplIvar->getIdentifier()
703262395Sbapt        << ImplIvar->getType() << ClsIvar->getType();
704262395Sbapt      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
705262395Sbapt    } else if (ImplIvar->isBitField() && ClsIvar->isBitField()) {
706262395Sbapt      Expr *ImplBitWidth = ImplIvar->getBitWidth();
707262395Sbapt      Expr *ClsBitWidth = ClsIvar->getBitWidth();
708262395Sbapt      if (ImplBitWidth->EvaluateAsInt(Context).getZExtValue() !=
709262395Sbapt          ClsBitWidth->EvaluateAsInt(Context).getZExtValue()) {
710262395Sbapt        Diag(ImplBitWidth->getLocStart(), diag::err_conflicting_ivar_bitwidth)
711262395Sbapt          << ImplIvar->getIdentifier();
712262395Sbapt        Diag(ClsBitWidth->getLocStart(), diag::note_previous_definition);
713262395Sbapt      }
714262395Sbapt    }
715262395Sbapt    // Make sure the names are identical.
716262395Sbapt    if (ImplIvar->getIdentifier() != ClsIvar->getIdentifier()) {
717262395Sbapt      Diag(ImplIvar->getLocation(), diag::err_conflicting_ivar_name)
718262395Sbapt        << ImplIvar->getIdentifier() << ClsIvar->getIdentifier();
719262395Sbapt      Diag(ClsIvar->getLocation(), diag::note_previous_definition);
720262395Sbapt    }
721262395Sbapt    --numIvars;
722262395Sbapt  }
723262395Sbapt
724262395Sbapt  if (numIvars > 0)
725262395Sbapt    Diag(ivars[j]->getLocation(), diag::err_inconsistant_ivar_count);
726262395Sbapt  else if (IVI != IVE)
727262395Sbapt    Diag((*IVI)->getLocation(), diag::err_inconsistant_ivar_count);
728262395Sbapt}
729262395Sbapt
730262395Sbaptvoid Sema::WarnUndefinedMethod(SourceLocation ImpLoc, ObjCMethodDecl *method,
731262395Sbapt                               bool &IncompleteImpl, unsigned DiagID) {
732262395Sbapt  if (!IncompleteImpl) {
733262395Sbapt    Diag(ImpLoc, diag::warn_incomplete_impl);
734262395Sbapt    IncompleteImpl = true;
735262395Sbapt  }
736262395Sbapt  Diag(method->getLocation(), DiagID)
737262395Sbapt    << method->getDeclName();
738262395Sbapt}
739262395Sbapt
740262395Sbaptvoid Sema::WarnConflictingTypedMethods(ObjCMethodDecl *ImpMethodDecl,
741262395Sbapt                                       ObjCMethodDecl *IntfMethodDecl) {
742262395Sbapt  if (!Context.typesAreCompatible(IntfMethodDecl->getResultType(),
743262395Sbapt                                  ImpMethodDecl->getResultType()) &&
744262395Sbapt      !Context.QualifiedIdConformsQualifiedId(IntfMethodDecl->getResultType(),
745262395Sbapt                                              ImpMethodDecl->getResultType())) {
746262395Sbapt    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_ret_types)
747262395Sbapt      << ImpMethodDecl->getDeclName() << IntfMethodDecl->getResultType()
748262395Sbapt      << ImpMethodDecl->getResultType();
749262395Sbapt    Diag(IntfMethodDecl->getLocation(), diag::note_previous_definition);
750262395Sbapt  }
751262395Sbapt
752262395Sbapt  for (ObjCMethodDecl::param_iterator IM = ImpMethodDecl->param_begin(),
753262395Sbapt       IF = IntfMethodDecl->param_begin(), EM = ImpMethodDecl->param_end();
754262395Sbapt       IM != EM; ++IM, ++IF) {
755262395Sbapt    QualType ParmDeclTy = (*IF)->getType().getUnqualifiedType();
756262395Sbapt    QualType ParmImpTy = (*IM)->getType().getUnqualifiedType();
757262395Sbapt    if (Context.typesAreCompatible(ParmDeclTy, ParmImpTy) ||
758        Context.QualifiedIdConformsQualifiedId(ParmDeclTy, ParmImpTy))
759      continue;
760
761    Diag((*IM)->getLocation(), diag::warn_conflicting_param_types)
762      << ImpMethodDecl->getDeclName() << (*IF)->getType()
763      << (*IM)->getType();
764    Diag((*IF)->getLocation(), diag::note_previous_definition);
765  }
766  if (ImpMethodDecl->isVariadic() != IntfMethodDecl->isVariadic()) {
767    Diag(ImpMethodDecl->getLocation(), diag::warn_conflicting_variadic);
768    Diag(IntfMethodDecl->getLocation(), diag::note_previous_declaration);
769  }
770}
771
772/// FIXME: Type hierarchies in Objective-C can be deep. We could most likely
773/// improve the efficiency of selector lookups and type checking by associating
774/// with each protocol / interface / category the flattened instance tables. If
775/// we used an immutable set to keep the table then it wouldn't add significant
776/// memory cost and it would be handy for lookups.
777
778/// CheckProtocolMethodDefs - This routine checks unimplemented methods
779/// Declared in protocol, and those referenced by it.
780void Sema::CheckProtocolMethodDefs(SourceLocation ImpLoc,
781                                   ObjCProtocolDecl *PDecl,
782                                   bool& IncompleteImpl,
783                                   const llvm::DenseSet<Selector> &InsMap,
784                                   const llvm::DenseSet<Selector> &ClsMap,
785                                   ObjCContainerDecl *CDecl) {
786  ObjCInterfaceDecl *IDecl;
787  if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl))
788    IDecl = C->getClassInterface();
789  else
790    IDecl = dyn_cast<ObjCInterfaceDecl>(CDecl);
791  assert (IDecl && "CheckProtocolMethodDefs - IDecl is null");
792
793  ObjCInterfaceDecl *Super = IDecl->getSuperClass();
794  ObjCInterfaceDecl *NSIDecl = 0;
795  if (getLangOptions().NeXTRuntime) {
796    // check to see if class implements forwardInvocation method and objects
797    // of this class are derived from 'NSProxy' so that to forward requests
798    // from one object to another.
799    // Under such conditions, which means that every method possible is
800    // implemented in the class, we should not issue "Method definition not
801    // found" warnings.
802    // FIXME: Use a general GetUnarySelector method for this.
803    IdentifierInfo* II = &Context.Idents.get("forwardInvocation");
804    Selector fISelector = Context.Selectors.getSelector(1, &II);
805    if (InsMap.count(fISelector))
806      // Is IDecl derived from 'NSProxy'? If so, no instance methods
807      // need be implemented in the implementation.
808      NSIDecl = IDecl->lookupInheritedClass(&Context.Idents.get("NSProxy"));
809  }
810
811  // If a method lookup fails locally we still need to look and see if
812  // the method was implemented by a base class or an inherited
813  // protocol. This lookup is slow, but occurs rarely in correct code
814  // and otherwise would terminate in a warning.
815
816  // check unimplemented instance methods.
817  if (!NSIDecl)
818    for (ObjCProtocolDecl::instmeth_iterator I = PDecl->instmeth_begin(),
819         E = PDecl->instmeth_end(); I != E; ++I) {
820      ObjCMethodDecl *method = *I;
821      if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
822          !method->isSynthesized() && !InsMap.count(method->getSelector()) &&
823          (!Super ||
824           !Super->lookupInstanceMethod(method->getSelector()))) {
825            // Ugly, but necessary. Method declared in protcol might have
826            // have been synthesized due to a property declared in the class which
827            // uses the protocol.
828            ObjCMethodDecl *MethodInClass =
829            IDecl->lookupInstanceMethod(method->getSelector());
830            if (!MethodInClass || !MethodInClass->isSynthesized()) {
831              unsigned DIAG = diag::warn_unimplemented_protocol_method;
832              if (Diags.getDiagnosticLevel(DIAG) != Diagnostic::Ignored) {
833                WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
834                Diag(CDecl->getLocation(), diag::note_required_for_protocol_at)
835                  << PDecl->getDeclName();
836              }
837            }
838          }
839    }
840  // check unimplemented class methods
841  for (ObjCProtocolDecl::classmeth_iterator
842         I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
843       I != E; ++I) {
844    ObjCMethodDecl *method = *I;
845    if (method->getImplementationControl() != ObjCMethodDecl::Optional &&
846        !ClsMap.count(method->getSelector()) &&
847        (!Super || !Super->lookupClassMethod(method->getSelector()))) {
848      unsigned DIAG = diag::warn_unimplemented_protocol_method;
849      if (Diags.getDiagnosticLevel(DIAG) != Diagnostic::Ignored) {
850        WarnUndefinedMethod(ImpLoc, method, IncompleteImpl, DIAG);
851        Diag(IDecl->getLocation(), diag::note_required_for_protocol_at) <<
852          PDecl->getDeclName();
853      }
854    }
855  }
856  // Check on this protocols's referenced protocols, recursively.
857  for (ObjCProtocolDecl::protocol_iterator PI = PDecl->protocol_begin(),
858       E = PDecl->protocol_end(); PI != E; ++PI)
859    CheckProtocolMethodDefs(ImpLoc, *PI, IncompleteImpl, InsMap, ClsMap, IDecl);
860}
861
862/// MatchAllMethodDeclarations - Check methods declaraed in interface or
863/// or protocol against those declared in their implementations.
864///
865void Sema::MatchAllMethodDeclarations(const llvm::DenseSet<Selector> &InsMap,
866                                      const llvm::DenseSet<Selector> &ClsMap,
867                                      llvm::DenseSet<Selector> &InsMapSeen,
868                                      llvm::DenseSet<Selector> &ClsMapSeen,
869                                      ObjCImplDecl* IMPDecl,
870                                      ObjCContainerDecl* CDecl,
871                                      bool &IncompleteImpl,
872                                      bool ImmediateClass) {
873  // Check and see if instance methods in class interface have been
874  // implemented in the implementation class. If so, their types match.
875  for (ObjCInterfaceDecl::instmeth_iterator I = CDecl->instmeth_begin(),
876       E = CDecl->instmeth_end(); I != E; ++I) {
877    if (InsMapSeen.count((*I)->getSelector()))
878        continue;
879    InsMapSeen.insert((*I)->getSelector());
880    if (!(*I)->isSynthesized() &&
881        !InsMap.count((*I)->getSelector())) {
882      if (ImmediateClass)
883        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
884                            diag::note_undef_method_impl);
885      continue;
886    } else {
887      ObjCMethodDecl *ImpMethodDecl =
888      IMPDecl->getInstanceMethod((*I)->getSelector());
889      ObjCMethodDecl *IntfMethodDecl =
890      CDecl->getInstanceMethod((*I)->getSelector());
891      assert(IntfMethodDecl &&
892             "IntfMethodDecl is null in ImplMethodsVsClassMethods");
893      // ImpMethodDecl may be null as in a @dynamic property.
894      if (ImpMethodDecl)
895        WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
896    }
897  }
898
899  // Check and see if class methods in class interface have been
900  // implemented in the implementation class. If so, their types match.
901   for (ObjCInterfaceDecl::classmeth_iterator
902       I = CDecl->classmeth_begin(), E = CDecl->classmeth_end(); I != E; ++I) {
903     if (ClsMapSeen.count((*I)->getSelector()))
904       continue;
905     ClsMapSeen.insert((*I)->getSelector());
906    if (!ClsMap.count((*I)->getSelector())) {
907      if (ImmediateClass)
908        WarnUndefinedMethod(IMPDecl->getLocation(), *I, IncompleteImpl,
909                            diag::note_undef_method_impl);
910    } else {
911      ObjCMethodDecl *ImpMethodDecl =
912        IMPDecl->getClassMethod((*I)->getSelector());
913      ObjCMethodDecl *IntfMethodDecl =
914        CDecl->getClassMethod((*I)->getSelector());
915      WarnConflictingTypedMethods(ImpMethodDecl, IntfMethodDecl);
916    }
917  }
918  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
919    // Check for any implementation of a methods declared in protocol.
920    for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
921         E = I->protocol_end(); PI != E; ++PI)
922      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
923                                 IMPDecl,
924                                 (*PI), IncompleteImpl, false);
925    if (I->getSuperClass())
926      MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
927                                 IMPDecl,
928                                 I->getSuperClass(), IncompleteImpl, false);
929  }
930}
931
932void Sema::ImplMethodsVsClassMethods(Scope *S, ObjCImplDecl* IMPDecl,
933                                     ObjCContainerDecl* CDecl,
934                                     bool IncompleteImpl) {
935  llvm::DenseSet<Selector> InsMap;
936  // Check and see if instance methods in class interface have been
937  // implemented in the implementation class.
938  for (ObjCImplementationDecl::instmeth_iterator
939         I = IMPDecl->instmeth_begin(), E = IMPDecl->instmeth_end(); I!=E; ++I)
940    InsMap.insert((*I)->getSelector());
941
942  // Check and see if properties declared in the interface have either 1)
943  // an implementation or 2) there is a @synthesize/@dynamic implementation
944  // of the property in the @implementation.
945  if (isa<ObjCInterfaceDecl>(CDecl) && !LangOpts.ObjCNonFragileABI2)
946    DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
947
948  llvm::DenseSet<Selector> ClsMap;
949  for (ObjCImplementationDecl::classmeth_iterator
950       I = IMPDecl->classmeth_begin(),
951       E = IMPDecl->classmeth_end(); I != E; ++I)
952    ClsMap.insert((*I)->getSelector());
953
954  // Check for type conflict of methods declared in a class/protocol and
955  // its implementation; if any.
956  llvm::DenseSet<Selector> InsMapSeen, ClsMapSeen;
957  MatchAllMethodDeclarations(InsMap, ClsMap, InsMapSeen, ClsMapSeen,
958                             IMPDecl, CDecl,
959                             IncompleteImpl, true);
960
961  // Check the protocol list for unimplemented methods in the @implementation
962  // class.
963  // Check and see if class methods in class interface have been
964  // implemented in the implementation class.
965
966  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl> (CDecl)) {
967    for (ObjCInterfaceDecl::protocol_iterator PI = I->protocol_begin(),
968         E = I->protocol_end(); PI != E; ++PI)
969      CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
970                              InsMap, ClsMap, I);
971    // Check class extensions (unnamed categories)
972    for (ObjCCategoryDecl *Categories = I->getCategoryList();
973         Categories; Categories = Categories->getNextClassCategory()) {
974      if (Categories->IsClassExtension()) {
975        ImplMethodsVsClassMethods(S, IMPDecl, Categories, IncompleteImpl);
976        break;
977      }
978    }
979  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(CDecl)) {
980    // For extended class, unimplemented methods in its protocols will
981    // be reported in the primary class.
982    if (!C->IsClassExtension()) {
983      for (ObjCCategoryDecl::protocol_iterator PI = C->protocol_begin(),
984           E = C->protocol_end(); PI != E; ++PI)
985        CheckProtocolMethodDefs(IMPDecl->getLocation(), *PI, IncompleteImpl,
986                                InsMap, ClsMap, CDecl);
987      // Report unimplemented properties in the category as well.
988      // When reporting on missing setter/getters, do not report when
989      // setter/getter is implemented in category's primary class
990      // implementation.
991      if (ObjCInterfaceDecl *ID = C->getClassInterface())
992        if (ObjCImplDecl *IMP = ID->getImplementation()) {
993          for (ObjCImplementationDecl::instmeth_iterator
994               I = IMP->instmeth_begin(), E = IMP->instmeth_end(); I!=E; ++I)
995            InsMap.insert((*I)->getSelector());
996        }
997      DiagnoseUnimplementedProperties(S, IMPDecl, CDecl, InsMap);
998    }
999  } else
1000    assert(false && "invalid ObjCContainerDecl type.");
1001}
1002
1003/// ActOnForwardClassDeclaration -
1004Action::DeclPtrTy
1005Sema::ActOnForwardClassDeclaration(SourceLocation AtClassLoc,
1006                                   IdentifierInfo **IdentList,
1007                                   SourceLocation *IdentLocs,
1008                                   unsigned NumElts) {
1009  llvm::SmallVector<ObjCInterfaceDecl*, 32> Interfaces;
1010
1011  for (unsigned i = 0; i != NumElts; ++i) {
1012    // Check for another declaration kind with the same name.
1013    NamedDecl *PrevDecl
1014      = LookupSingleName(TUScope, IdentList[i], IdentLocs[i],
1015                         LookupOrdinaryName, ForRedeclaration);
1016    if (PrevDecl && PrevDecl->isTemplateParameter()) {
1017      // Maybe we will complain about the shadowed template parameter.
1018      DiagnoseTemplateParameterShadow(AtClassLoc, PrevDecl);
1019      // Just pretend that we didn't see the previous declaration.
1020      PrevDecl = 0;
1021    }
1022
1023    if (PrevDecl && !isa<ObjCInterfaceDecl>(PrevDecl)) {
1024      // GCC apparently allows the following idiom:
1025      //
1026      // typedef NSObject < XCElementTogglerP > XCElementToggler;
1027      // @class XCElementToggler;
1028      //
1029      // FIXME: Make an extension?
1030      TypedefDecl *TDD = dyn_cast<TypedefDecl>(PrevDecl);
1031      if (!TDD || !TDD->getUnderlyingType()->isObjCObjectType()) {
1032        Diag(AtClassLoc, diag::err_redefinition_different_kind) << IdentList[i];
1033        Diag(PrevDecl->getLocation(), diag::note_previous_definition);
1034      } else {
1035        // a forward class declaration matching a typedef name of a class refers
1036        // to the underlying class.
1037        if (const ObjCObjectType *OI =
1038              TDD->getUnderlyingType()->getAs<ObjCObjectType>())
1039          PrevDecl = OI->getInterface();
1040      }
1041    }
1042    ObjCInterfaceDecl *IDecl = dyn_cast_or_null<ObjCInterfaceDecl>(PrevDecl);
1043    if (!IDecl) {  // Not already seen?  Make a forward decl.
1044      IDecl = ObjCInterfaceDecl::Create(Context, CurContext, AtClassLoc,
1045                                        IdentList[i], IdentLocs[i], true);
1046
1047      // Push the ObjCInterfaceDecl on the scope chain but do *not* add it to
1048      // the current DeclContext.  This prevents clients that walk DeclContext
1049      // from seeing the imaginary ObjCInterfaceDecl until it is actually
1050      // declared later (if at all).  We also take care to explicitly make
1051      // sure this declaration is visible for name lookup.
1052      PushOnScopeChains(IDecl, TUScope, false);
1053      CurContext->makeDeclVisibleInContext(IDecl, true);
1054    }
1055
1056    Interfaces.push_back(IDecl);
1057  }
1058
1059  assert(Interfaces.size() == NumElts);
1060  ObjCClassDecl *CDecl = ObjCClassDecl::Create(Context, CurContext, AtClassLoc,
1061                                               Interfaces.data(), IdentLocs,
1062                                               Interfaces.size());
1063  CurContext->addDecl(CDecl);
1064  CheckObjCDeclScope(CDecl);
1065  return DeclPtrTy::make(CDecl);
1066}
1067
1068
1069/// MatchTwoMethodDeclarations - Checks that two methods have matching type and
1070/// returns true, or false, accordingly.
1071/// TODO: Handle protocol list; such as id<p1,p2> in type comparisons
1072bool Sema::MatchTwoMethodDeclarations(const ObjCMethodDecl *Method,
1073                                      const ObjCMethodDecl *PrevMethod,
1074                                      bool matchBasedOnSizeAndAlignment) {
1075  QualType T1 = Context.getCanonicalType(Method->getResultType());
1076  QualType T2 = Context.getCanonicalType(PrevMethod->getResultType());
1077
1078  if (T1 != T2) {
1079    // The result types are different.
1080    if (!matchBasedOnSizeAndAlignment)
1081      return false;
1082    // Incomplete types don't have a size and alignment.
1083    if (T1->isIncompleteType() || T2->isIncompleteType())
1084      return false;
1085    // Check is based on size and alignment.
1086    if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1087      return false;
1088  }
1089
1090  ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1091       E = Method->param_end();
1092  ObjCMethodDecl::param_iterator PrevI = PrevMethod->param_begin();
1093
1094  for (; ParamI != E; ++ParamI, ++PrevI) {
1095    assert(PrevI != PrevMethod->param_end() && "Param mismatch");
1096    T1 = Context.getCanonicalType((*ParamI)->getType());
1097    T2 = Context.getCanonicalType((*PrevI)->getType());
1098    if (T1 != T2) {
1099      // The result types are different.
1100      if (!matchBasedOnSizeAndAlignment)
1101        return false;
1102      // Incomplete types don't have a size and alignment.
1103      if (T1->isIncompleteType() || T2->isIncompleteType())
1104        return false;
1105      // Check is based on size and alignment.
1106      if (Context.getTypeInfo(T1) != Context.getTypeInfo(T2))
1107        return false;
1108    }
1109  }
1110  return true;
1111}
1112
1113/// \brief Read the contents of the instance and factory method pools
1114/// for a given selector from external storage.
1115///
1116/// This routine should only be called once, when neither the instance
1117/// nor the factory method pool has an entry for this selector.
1118Sema::MethodPool::iterator Sema::ReadMethodPool(Selector Sel,
1119                                                bool isInstance) {
1120  assert(ExternalSource && "We need an external AST source");
1121  assert(InstanceMethodPool.find(Sel) == InstanceMethodPool.end() &&
1122         "Selector data already loaded into the instance method pool");
1123  assert(FactoryMethodPool.find(Sel) == FactoryMethodPool.end() &&
1124         "Selector data already loaded into the factory method pool");
1125
1126  // Read the method list from the external source.
1127  std::pair<ObjCMethodList, ObjCMethodList> Methods
1128    = ExternalSource->ReadMethodPool(Sel);
1129
1130  if (isInstance) {
1131    if (Methods.second.Method)
1132      FactoryMethodPool[Sel] = Methods.second;
1133    return InstanceMethodPool.insert(std::make_pair(Sel, Methods.first)).first;
1134  }
1135
1136  if (Methods.first.Method)
1137    InstanceMethodPool[Sel] = Methods.first;
1138
1139  return FactoryMethodPool.insert(std::make_pair(Sel, Methods.second)).first;
1140}
1141
1142void Sema::AddInstanceMethodToGlobalPool(ObjCMethodDecl *Method) {
1143  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1144    = InstanceMethodPool.find(Method->getSelector());
1145  if (Pos == InstanceMethodPool.end()) {
1146    if (ExternalSource && !FactoryMethodPool.count(Method->getSelector()))
1147      Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/true);
1148    else
1149      Pos = InstanceMethodPool.insert(std::make_pair(Method->getSelector(),
1150                                                     ObjCMethodList())).first;
1151  }
1152
1153  ObjCMethodList &Entry = Pos->second;
1154  if (Entry.Method == 0) {
1155    // Haven't seen a method with this selector name yet - add it.
1156    Entry.Method = Method;
1157    Entry.Next = 0;
1158    return;
1159  }
1160
1161  // We've seen a method with this name, see if we have already seen this type
1162  // signature.
1163  for (ObjCMethodList *List = &Entry; List; List = List->Next)
1164    if (MatchTwoMethodDeclarations(Method, List->Method))
1165      return;
1166
1167  // We have a new signature for an existing method - add it.
1168  // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1169  ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1170  Entry.Next = new (Mem) ObjCMethodList(Method, Entry.Next);
1171}
1172
1173// FIXME: Finish implementing -Wno-strict-selector-match.
1174ObjCMethodDecl *Sema::LookupInstanceMethodInGlobalPool(Selector Sel,
1175                                                       SourceRange R,
1176                                                       bool warn) {
1177  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1178    = InstanceMethodPool.find(Sel);
1179  if (Pos == InstanceMethodPool.end()) {
1180    if (ExternalSource && !FactoryMethodPool.count(Sel))
1181      Pos = ReadMethodPool(Sel, /*isInstance=*/true);
1182    else
1183      return 0;
1184  }
1185
1186  ObjCMethodList &MethList = Pos->second;
1187  bool issueWarning = false;
1188
1189  if (MethList.Method && MethList.Next) {
1190    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1191      // This checks if the methods differ by size & alignment.
1192      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1193        issueWarning = warn;
1194  }
1195  if (issueWarning && (MethList.Method && MethList.Next)) {
1196    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1197    Diag(MethList.Method->getLocStart(), diag::note_using)
1198      << MethList.Method->getSourceRange();
1199    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1200      Diag(Next->Method->getLocStart(), diag::note_also_found)
1201        << Next->Method->getSourceRange();
1202  }
1203  return MethList.Method;
1204}
1205
1206void Sema::AddFactoryMethodToGlobalPool(ObjCMethodDecl *Method) {
1207  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1208    = FactoryMethodPool.find(Method->getSelector());
1209  if (Pos == FactoryMethodPool.end()) {
1210    if (ExternalSource && !InstanceMethodPool.count(Method->getSelector()))
1211      Pos = ReadMethodPool(Method->getSelector(), /*isInstance=*/false);
1212    else
1213      Pos = FactoryMethodPool.insert(std::make_pair(Method->getSelector(),
1214                                                    ObjCMethodList())).first;
1215  }
1216
1217  ObjCMethodList &FirstMethod = Pos->second;
1218  if (!FirstMethod.Method) {
1219    // Haven't seen a method with this selector name yet - add it.
1220    FirstMethod.Method = Method;
1221    FirstMethod.Next = 0;
1222  } else {
1223    // We've seen a method with this name, now check the type signature(s).
1224    bool match = MatchTwoMethodDeclarations(Method, FirstMethod.Method);
1225
1226    for (ObjCMethodList *Next = FirstMethod.Next; !match && Next;
1227         Next = Next->Next)
1228      match = MatchTwoMethodDeclarations(Method, Next->Method);
1229
1230    if (!match) {
1231      // We have a new signature for an existing method - add it.
1232      // This is extremely rare. Only 1% of Cocoa selectors are "overloaded".
1233      ObjCMethodList *Mem = BumpAlloc.Allocate<ObjCMethodList>();
1234      ObjCMethodList *OMI = new (Mem) ObjCMethodList(Method, FirstMethod.Next);
1235      FirstMethod.Next = OMI;
1236    }
1237  }
1238}
1239
1240ObjCMethodDecl *Sema::LookupFactoryMethodInGlobalPool(Selector Sel,
1241                                                      SourceRange R) {
1242  llvm::DenseMap<Selector, ObjCMethodList>::iterator Pos
1243    = FactoryMethodPool.find(Sel);
1244  if (Pos == FactoryMethodPool.end()) {
1245    if (ExternalSource && !InstanceMethodPool.count(Sel))
1246      Pos = ReadMethodPool(Sel, /*isInstance=*/false);
1247    else
1248      return 0;
1249  }
1250
1251  ObjCMethodList &MethList = Pos->second;
1252  bool issueWarning = false;
1253
1254  if (MethList.Method && MethList.Next) {
1255    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1256      // This checks if the methods differ by size & alignment.
1257      if (!MatchTwoMethodDeclarations(MethList.Method, Next->Method, true))
1258        issueWarning = true;
1259  }
1260  if (issueWarning && (MethList.Method && MethList.Next)) {
1261    Diag(R.getBegin(), diag::warn_multiple_method_decl) << Sel << R;
1262    Diag(MethList.Method->getLocStart(), diag::note_using)
1263      << MethList.Method->getSourceRange();
1264    for (ObjCMethodList *Next = MethList.Next; Next; Next = Next->Next)
1265      Diag(Next->Method->getLocStart(), diag::note_also_found)
1266        << Next->Method->getSourceRange();
1267  }
1268  return MethList.Method;
1269}
1270
1271/// CompareMethodParamsInBaseAndSuper - This routine compares methods with
1272/// identical selector names in current and its super classes and issues
1273/// a warning if any of their argument types are incompatible.
1274void Sema::CompareMethodParamsInBaseAndSuper(Decl *ClassDecl,
1275                                             ObjCMethodDecl *Method,
1276                                             bool IsInstance)  {
1277  ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(ClassDecl);
1278  if (ID == 0) return;
1279
1280  while (ObjCInterfaceDecl *SD = ID->getSuperClass()) {
1281    ObjCMethodDecl *SuperMethodDecl =
1282        SD->lookupMethod(Method->getSelector(), IsInstance);
1283    if (SuperMethodDecl == 0) {
1284      ID = SD;
1285      continue;
1286    }
1287    ObjCMethodDecl::param_iterator ParamI = Method->param_begin(),
1288      E = Method->param_end();
1289    ObjCMethodDecl::param_iterator PrevI = SuperMethodDecl->param_begin();
1290    for (; ParamI != E; ++ParamI, ++PrevI) {
1291      // Number of parameters are the same and is guaranteed by selector match.
1292      assert(PrevI != SuperMethodDecl->param_end() && "Param mismatch");
1293      QualType T1 = Context.getCanonicalType((*ParamI)->getType());
1294      QualType T2 = Context.getCanonicalType((*PrevI)->getType());
1295      // If type of arguement of method in this class does not match its
1296      // respective argument type in the super class method, issue warning;
1297      if (!Context.typesAreCompatible(T1, T2)) {
1298        Diag((*ParamI)->getLocation(), diag::ext_typecheck_base_super)
1299          << T1 << T2;
1300        Diag(SuperMethodDecl->getLocation(), diag::note_previous_declaration);
1301        return;
1302      }
1303    }
1304    ID = SD;
1305  }
1306}
1307
1308/// DiagnoseDuplicateIvars -
1309/// Check for duplicate ivars in the entire class at the start of
1310/// @implementation. This becomes necesssary because class extension can
1311/// add ivars to a class in random order which will not be known until
1312/// class's @implementation is seen.
1313void Sema::DiagnoseDuplicateIvars(ObjCInterfaceDecl *ID,
1314                                  ObjCInterfaceDecl *SID) {
1315  for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
1316       IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
1317    ObjCIvarDecl* Ivar = (*IVI);
1318    if (Ivar->isInvalidDecl())
1319      continue;
1320    if (IdentifierInfo *II = Ivar->getIdentifier()) {
1321      ObjCIvarDecl* prevIvar = SID->lookupInstanceVariable(II);
1322      if (prevIvar) {
1323        Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
1324        Diag(prevIvar->getLocation(), diag::note_previous_declaration);
1325        Ivar->setInvalidDecl();
1326      }
1327    }
1328  }
1329}
1330
1331// Note: For class/category implemenations, allMethods/allProperties is
1332// always null.
1333void Sema::ActOnAtEnd(Scope *S, SourceRange AtEnd,
1334                      DeclPtrTy classDecl,
1335                      DeclPtrTy *allMethods, unsigned allNum,
1336                      DeclPtrTy *allProperties, unsigned pNum,
1337                      DeclGroupPtrTy *allTUVars, unsigned tuvNum) {
1338  Decl *ClassDecl = classDecl.getAs<Decl>();
1339
1340  // FIXME: If we don't have a ClassDecl, we have an error. We should consider
1341  // always passing in a decl. If the decl has an error, isInvalidDecl()
1342  // should be true.
1343  if (!ClassDecl)
1344    return;
1345
1346  bool isInterfaceDeclKind =
1347        isa<ObjCInterfaceDecl>(ClassDecl) || isa<ObjCCategoryDecl>(ClassDecl)
1348         || isa<ObjCProtocolDecl>(ClassDecl);
1349  bool checkIdenticalMethods = isa<ObjCImplementationDecl>(ClassDecl);
1350
1351  if (!isInterfaceDeclKind && AtEnd.isInvalid()) {
1352    // FIXME: This is wrong.  We shouldn't be pretending that there is
1353    //  an '@end' in the declaration.
1354    SourceLocation L = ClassDecl->getLocation();
1355    AtEnd.setBegin(L);
1356    AtEnd.setEnd(L);
1357    Diag(L, diag::warn_missing_atend);
1358  }
1359
1360  DeclContext *DC = dyn_cast<DeclContext>(ClassDecl);
1361
1362  // FIXME: Remove these and use the ObjCContainerDecl/DeclContext.
1363  llvm::DenseMap<Selector, const ObjCMethodDecl*> InsMap;
1364  llvm::DenseMap<Selector, const ObjCMethodDecl*> ClsMap;
1365
1366  for (unsigned i = 0; i < allNum; i++ ) {
1367    ObjCMethodDecl *Method =
1368      cast_or_null<ObjCMethodDecl>(allMethods[i].getAs<Decl>());
1369
1370    if (!Method) continue;  // Already issued a diagnostic.
1371    if (Method->isInstanceMethod()) {
1372      /// Check for instance method of the same name with incompatible types
1373      const ObjCMethodDecl *&PrevMethod = InsMap[Method->getSelector()];
1374      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1375                              : false;
1376      if ((isInterfaceDeclKind && PrevMethod && !match)
1377          || (checkIdenticalMethods && match)) {
1378          Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1379            << Method->getDeclName();
1380          Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1381      } else {
1382        DC->addDecl(Method);
1383        InsMap[Method->getSelector()] = Method;
1384        /// The following allows us to typecheck messages to "id".
1385        AddInstanceMethodToGlobalPool(Method);
1386        // verify that the instance method conforms to the same definition of
1387        // parent methods if it shadows one.
1388        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, true);
1389      }
1390    } else {
1391      /// Check for class method of the same name with incompatible types
1392      const ObjCMethodDecl *&PrevMethod = ClsMap[Method->getSelector()];
1393      bool match = PrevMethod ? MatchTwoMethodDeclarations(Method, PrevMethod)
1394                              : false;
1395      if ((isInterfaceDeclKind && PrevMethod && !match)
1396          || (checkIdenticalMethods && match)) {
1397        Diag(Method->getLocation(), diag::err_duplicate_method_decl)
1398          << Method->getDeclName();
1399        Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1400      } else {
1401        DC->addDecl(Method);
1402        ClsMap[Method->getSelector()] = Method;
1403        /// The following allows us to typecheck messages to "Class".
1404        AddFactoryMethodToGlobalPool(Method);
1405        // verify that the class method conforms to the same definition of
1406        // parent methods if it shadows one.
1407        CompareMethodParamsInBaseAndSuper(ClassDecl, Method, false);
1408      }
1409    }
1410  }
1411  if (ObjCInterfaceDecl *I = dyn_cast<ObjCInterfaceDecl>(ClassDecl)) {
1412    // Compares properties declared in this class to those of its
1413    // super class.
1414    ComparePropertiesInBaseAndSuper(I);
1415    CompareProperties(I, DeclPtrTy::make(I));
1416  } else if (ObjCCategoryDecl *C = dyn_cast<ObjCCategoryDecl>(ClassDecl)) {
1417    // Categories are used to extend the class by declaring new methods.
1418    // By the same token, they are also used to add new properties. No
1419    // need to compare the added property to those in the class.
1420
1421    // Compare protocol properties with those in category
1422    CompareProperties(C, DeclPtrTy::make(C));
1423    if (C->IsClassExtension())
1424      DiagnoseClassExtensionDupMethods(C, C->getClassInterface());
1425  }
1426  if (ObjCContainerDecl *CDecl = dyn_cast<ObjCContainerDecl>(ClassDecl)) {
1427    if (CDecl->getIdentifier())
1428      // ProcessPropertyDecl is responsible for diagnosing conflicts with any
1429      // user-defined setter/getter. It also synthesizes setter/getter methods
1430      // and adds them to the DeclContext and global method pools.
1431      for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
1432                                            E = CDecl->prop_end();
1433           I != E; ++I)
1434        ProcessPropertyDecl(*I, CDecl);
1435    CDecl->setAtEndRange(AtEnd);
1436  }
1437  if (ObjCImplementationDecl *IC=dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1438    IC->setAtEndRange(AtEnd);
1439    if (ObjCInterfaceDecl* IDecl = IC->getClassInterface()) {
1440      if (LangOpts.ObjCNonFragileABI2)
1441        DefaultSynthesizeProperties(S, IC, IDecl);
1442      ImplMethodsVsClassMethods(S, IC, IDecl);
1443      AtomicPropertySetterGetterRules(IC, IDecl);
1444      if (LangOpts.ObjCNonFragileABI2)
1445        while (IDecl->getSuperClass()) {
1446          DiagnoseDuplicateIvars(IDecl, IDecl->getSuperClass());
1447          IDecl = IDecl->getSuperClass();
1448        }
1449    }
1450    SetIvarInitializers(IC);
1451  } else if (ObjCCategoryImplDecl* CatImplClass =
1452                                   dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1453    CatImplClass->setAtEndRange(AtEnd);
1454
1455    // Find category interface decl and then check that all methods declared
1456    // in this interface are implemented in the category @implementation.
1457    if (ObjCInterfaceDecl* IDecl = CatImplClass->getClassInterface()) {
1458      for (ObjCCategoryDecl *Categories = IDecl->getCategoryList();
1459           Categories; Categories = Categories->getNextClassCategory()) {
1460        if (Categories->getIdentifier() == CatImplClass->getIdentifier()) {
1461          ImplMethodsVsClassMethods(S, CatImplClass, Categories);
1462          break;
1463        }
1464      }
1465    }
1466  }
1467  if (isInterfaceDeclKind) {
1468    // Reject invalid vardecls.
1469    for (unsigned i = 0; i != tuvNum; i++) {
1470      DeclGroupRef DG = allTUVars[i].getAsVal<DeclGroupRef>();
1471      for (DeclGroupRef::iterator I = DG.begin(), E = DG.end(); I != E; ++I)
1472        if (VarDecl *VDecl = dyn_cast<VarDecl>(*I)) {
1473          if (!VDecl->hasExternalStorage())
1474            Diag(VDecl->getLocation(), diag::err_objc_var_decl_inclass);
1475        }
1476    }
1477  }
1478}
1479
1480
1481/// CvtQTToAstBitMask - utility routine to produce an AST bitmask for
1482/// objective-c's type qualifier from the parser version of the same info.
1483static Decl::ObjCDeclQualifier
1484CvtQTToAstBitMask(ObjCDeclSpec::ObjCDeclQualifier PQTVal) {
1485  Decl::ObjCDeclQualifier ret = Decl::OBJC_TQ_None;
1486  if (PQTVal & ObjCDeclSpec::DQ_In)
1487    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_In);
1488  if (PQTVal & ObjCDeclSpec::DQ_Inout)
1489    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Inout);
1490  if (PQTVal & ObjCDeclSpec::DQ_Out)
1491    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Out);
1492  if (PQTVal & ObjCDeclSpec::DQ_Bycopy)
1493    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Bycopy);
1494  if (PQTVal & ObjCDeclSpec::DQ_Byref)
1495    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Byref);
1496  if (PQTVal & ObjCDeclSpec::DQ_Oneway)
1497    ret = (Decl::ObjCDeclQualifier)(ret | Decl::OBJC_TQ_Oneway);
1498
1499  return ret;
1500}
1501
1502static inline
1503bool containsInvalidMethodImplAttribute(const AttributeList *A) {
1504  // The 'ibaction' attribute is allowed on method definitions because of
1505  // how the IBAction macro is used on both method declarations and definitions.
1506  // If the method definitions contains any other attributes, return true.
1507  while (A && A->getKind() == AttributeList::AT_IBAction)
1508    A = A->getNext();
1509  return A != NULL;
1510}
1511
1512Sema::DeclPtrTy Sema::ActOnMethodDeclaration(
1513    SourceLocation MethodLoc, SourceLocation EndLoc,
1514    tok::TokenKind MethodType, DeclPtrTy classDecl,
1515    ObjCDeclSpec &ReturnQT, TypeTy *ReturnType,
1516    Selector Sel,
1517    // optional arguments. The number of types/arguments is obtained
1518    // from the Sel.getNumArgs().
1519    ObjCArgInfo *ArgInfo,
1520    DeclaratorChunk::ParamInfo *CParamInfo, unsigned CNumArgs, // c-style args
1521    AttributeList *AttrList, tok::ObjCKeywordKind MethodDeclKind,
1522    bool isVariadic) {
1523  Decl *ClassDecl = classDecl.getAs<Decl>();
1524
1525  // Make sure we can establish a context for the method.
1526  if (!ClassDecl) {
1527    Diag(MethodLoc, diag::error_missing_method_context);
1528    getLabelMap().clear();
1529    return DeclPtrTy();
1530  }
1531  QualType resultDeclType;
1532
1533  TypeSourceInfo *ResultTInfo = 0;
1534  if (ReturnType) {
1535    resultDeclType = GetTypeFromParser(ReturnType, &ResultTInfo);
1536
1537    // Methods cannot return interface types. All ObjC objects are
1538    // passed by reference.
1539    if (resultDeclType->isObjCObjectType()) {
1540      Diag(MethodLoc, diag::err_object_cannot_be_passed_returned_by_value)
1541        << 0 << resultDeclType;
1542      return DeclPtrTy();
1543    }
1544  } else // get the type for "id".
1545    resultDeclType = Context.getObjCIdType();
1546
1547  ObjCMethodDecl* ObjCMethod =
1548    ObjCMethodDecl::Create(Context, MethodLoc, EndLoc, Sel, resultDeclType,
1549                           ResultTInfo,
1550                           cast<DeclContext>(ClassDecl),
1551                           MethodType == tok::minus, isVariadic,
1552                           false,
1553                           MethodDeclKind == tok::objc_optional ?
1554                           ObjCMethodDecl::Optional :
1555                           ObjCMethodDecl::Required);
1556
1557  llvm::SmallVector<ParmVarDecl*, 16> Params;
1558
1559  for (unsigned i = 0, e = Sel.getNumArgs(); i != e; ++i) {
1560    QualType ArgType;
1561    TypeSourceInfo *DI;
1562
1563    if (ArgInfo[i].Type == 0) {
1564      ArgType = Context.getObjCIdType();
1565      DI = 0;
1566    } else {
1567      ArgType = GetTypeFromParser(ArgInfo[i].Type, &DI);
1568      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1569      ArgType = adjustParameterType(ArgType);
1570    }
1571
1572    ParmVarDecl* Param
1573      = ParmVarDecl::Create(Context, ObjCMethod, ArgInfo[i].NameLoc,
1574                            ArgInfo[i].Name, ArgType, DI,
1575                            VarDecl::None, VarDecl::None, 0);
1576
1577    if (ArgType->isObjCObjectType()) {
1578      Diag(ArgInfo[i].NameLoc,
1579           diag::err_object_cannot_be_passed_returned_by_value)
1580        << 1 << ArgType;
1581      Param->setInvalidDecl();
1582    }
1583
1584    Param->setObjCDeclQualifier(
1585      CvtQTToAstBitMask(ArgInfo[i].DeclSpec.getObjCDeclQualifier()));
1586
1587    // Apply the attributes to the parameter.
1588    ProcessDeclAttributeList(TUScope, Param, ArgInfo[i].ArgAttrs);
1589
1590    Params.push_back(Param);
1591  }
1592
1593  for (unsigned i = 0, e = CNumArgs; i != e; ++i) {
1594    ParmVarDecl *Param = CParamInfo[i].Param.getAs<ParmVarDecl>();
1595    QualType ArgType = Param->getType();
1596    if (ArgType.isNull())
1597      ArgType = Context.getObjCIdType();
1598    else
1599      // Perform the default array/function conversions (C99 6.7.5.3p[7,8]).
1600      ArgType = adjustParameterType(ArgType);
1601    if (ArgType->isObjCObjectType()) {
1602      Diag(Param->getLocation(),
1603           diag::err_object_cannot_be_passed_returned_by_value)
1604      << 1 << ArgType;
1605      Param->setInvalidDecl();
1606    }
1607    Param->setDeclContext(ObjCMethod);
1608    IdResolver.RemoveDecl(Param);
1609    Params.push_back(Param);
1610  }
1611
1612  ObjCMethod->setMethodParams(Context, Params.data(), Params.size(),
1613                              Sel.getNumArgs());
1614  ObjCMethod->setObjCDeclQualifier(
1615    CvtQTToAstBitMask(ReturnQT.getObjCDeclQualifier()));
1616  const ObjCMethodDecl *PrevMethod = 0;
1617
1618  if (AttrList)
1619    ProcessDeclAttributeList(TUScope, ObjCMethod, AttrList);
1620
1621  const ObjCMethodDecl *InterfaceMD = 0;
1622
1623  // For implementations (which can be very "coarse grain"), we add the
1624  // method now. This allows the AST to implement lookup methods that work
1625  // incrementally (without waiting until we parse the @end). It also allows
1626  // us to flag multiple declaration errors as they occur.
1627  if (ObjCImplementationDecl *ImpDecl =
1628        dyn_cast<ObjCImplementationDecl>(ClassDecl)) {
1629    if (MethodType == tok::minus) {
1630      PrevMethod = ImpDecl->getInstanceMethod(Sel);
1631      ImpDecl->addInstanceMethod(ObjCMethod);
1632    } else {
1633      PrevMethod = ImpDecl->getClassMethod(Sel);
1634      ImpDecl->addClassMethod(ObjCMethod);
1635    }
1636    InterfaceMD = ImpDecl->getClassInterface()->getMethod(Sel,
1637                                                   MethodType == tok::minus);
1638    if (containsInvalidMethodImplAttribute(AttrList))
1639      Diag(EndLoc, diag::warn_attribute_method_def);
1640  } else if (ObjCCategoryImplDecl *CatImpDecl =
1641             dyn_cast<ObjCCategoryImplDecl>(ClassDecl)) {
1642    if (MethodType == tok::minus) {
1643      PrevMethod = CatImpDecl->getInstanceMethod(Sel);
1644      CatImpDecl->addInstanceMethod(ObjCMethod);
1645    } else {
1646      PrevMethod = CatImpDecl->getClassMethod(Sel);
1647      CatImpDecl->addClassMethod(ObjCMethod);
1648    }
1649    if (containsInvalidMethodImplAttribute(AttrList))
1650      Diag(EndLoc, diag::warn_attribute_method_def);
1651  }
1652  if (PrevMethod) {
1653    // You can never have two method definitions with the same name.
1654    Diag(ObjCMethod->getLocation(), diag::err_duplicate_method_decl)
1655      << ObjCMethod->getDeclName();
1656    Diag(PrevMethod->getLocation(), diag::note_previous_declaration);
1657  }
1658
1659  // If the interface declared this method, and it was deprecated there,
1660  // mark it deprecated here.
1661  if (InterfaceMD && InterfaceMD->hasAttr<DeprecatedAttr>())
1662    ObjCMethod->addAttr(::new (Context) DeprecatedAttr());
1663
1664  return DeclPtrTy::make(ObjCMethod);
1665}
1666
1667bool Sema::CheckObjCDeclScope(Decl *D) {
1668  if (isa<TranslationUnitDecl>(CurContext->getLookupContext()))
1669    return false;
1670
1671  Diag(D->getLocation(), diag::err_objc_decls_may_only_appear_in_global_scope);
1672  D->setInvalidDecl();
1673
1674  return true;
1675}
1676
1677/// Called whenever @defs(ClassName) is encountered in the source.  Inserts the
1678/// instance variables of ClassName into Decls.
1679void Sema::ActOnDefs(Scope *S, DeclPtrTy TagD, SourceLocation DeclStart,
1680                     IdentifierInfo *ClassName,
1681                     llvm::SmallVectorImpl<DeclPtrTy> &Decls) {
1682  // Check that ClassName is a valid class
1683  ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName, DeclStart);
1684  if (!Class) {
1685    Diag(DeclStart, diag::err_undef_interface) << ClassName;
1686    return;
1687  }
1688  if (LangOpts.ObjCNonFragileABI) {
1689    Diag(DeclStart, diag::err_atdef_nonfragile_interface);
1690    return;
1691  }
1692
1693  // Collect the instance variables
1694  llvm::SmallVector<FieldDecl*, 32> RecFields;
1695  Context.CollectObjCIvars(Class, RecFields);
1696  // For each ivar, create a fresh ObjCAtDefsFieldDecl.
1697  for (unsigned i = 0; i < RecFields.size(); i++) {
1698    FieldDecl* ID = RecFields[i];
1699    RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>());
1700    Decl *FD = ObjCAtDefsFieldDecl::Create(Context, Record, ID->getLocation(),
1701                                           ID->getIdentifier(), ID->getType(),
1702                                           ID->getBitWidth());
1703    Decls.push_back(Sema::DeclPtrTy::make(FD));
1704  }
1705
1706  // Introduce all of these fields into the appropriate scope.
1707  for (llvm::SmallVectorImpl<DeclPtrTy>::iterator D = Decls.begin();
1708       D != Decls.end(); ++D) {
1709    FieldDecl *FD = cast<FieldDecl>(D->getAs<Decl>());
1710    if (getLangOptions().CPlusPlus)
1711      PushOnScopeChains(cast<FieldDecl>(FD), S);
1712    else if (RecordDecl *Record = dyn_cast<RecordDecl>(TagD.getAs<Decl>()))
1713      Record->addDecl(FD);
1714  }
1715}
1716
1717/// \brief Build a type-check a new Objective-C exception variable declaration.
1718VarDecl *Sema::BuildObjCExceptionDecl(TypeSourceInfo *TInfo,
1719                                      QualType T,
1720                                      IdentifierInfo *Name,
1721                                      SourceLocation NameLoc,
1722                                      bool Invalid) {
1723  // ISO/IEC TR 18037 S6.7.3: "The type of an object with automatic storage
1724  // duration shall not be qualified by an address-space qualifier."
1725  // Since all parameters have automatic store duration, they can not have
1726  // an address space.
1727  if (T.getAddressSpace() != 0) {
1728    Diag(NameLoc, diag::err_arg_with_address_space);
1729    Invalid = true;
1730  }
1731
1732  // An @catch parameter must be an unqualified object pointer type;
1733  // FIXME: Recover from "NSObject foo" by inserting the * in "NSObject *foo"?
1734  if (Invalid) {
1735    // Don't do any further checking.
1736  } else if (T->isDependentType()) {
1737    // Okay: we don't know what this type will instantiate to.
1738  } else if (!T->isObjCObjectPointerType()) {
1739    Invalid = true;
1740    Diag(NameLoc ,diag::err_catch_param_not_objc_type);
1741  } else if (T->isObjCQualifiedIdType()) {
1742    Invalid = true;
1743    Diag(NameLoc, diag::err_illegal_qualifiers_on_catch_parm);
1744  }
1745
1746  VarDecl *New = VarDecl::Create(Context, CurContext, NameLoc, Name, T, TInfo,
1747                                 VarDecl::None, VarDecl::None);
1748  New->setExceptionVariable(true);
1749
1750  if (Invalid)
1751    New->setInvalidDecl();
1752  return New;
1753}
1754
1755Sema::DeclPtrTy Sema::ActOnObjCExceptionDecl(Scope *S, Declarator &D) {
1756  const DeclSpec &DS = D.getDeclSpec();
1757
1758  // We allow the "register" storage class on exception variables because
1759  // GCC did, but we drop it completely. Any other storage class is an error.
1760  if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1761    Diag(DS.getStorageClassSpecLoc(), diag::warn_register_objc_catch_parm)
1762      << FixItHint::CreateRemoval(SourceRange(DS.getStorageClassSpecLoc()));
1763  } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
1764    Diag(DS.getStorageClassSpecLoc(), diag::err_storage_spec_on_catch_parm)
1765      << DS.getStorageClassSpec();
1766  }
1767  if (D.getDeclSpec().isThreadSpecified())
1768    Diag(D.getDeclSpec().getThreadSpecLoc(), diag::err_invalid_thread);
1769  D.getMutableDeclSpec().ClearStorageClassSpecs();
1770
1771  DiagnoseFunctionSpecifiers(D);
1772
1773  // Check that there are no default arguments inside the type of this
1774  // exception object (C++ only).
1775  if (getLangOptions().CPlusPlus)
1776    CheckExtraCXXDefaultArguments(D);
1777
1778  TypeSourceInfo *TInfo = 0;
1779  TagDecl *OwnedDecl = 0;
1780  QualType ExceptionType = GetTypeForDeclarator(D, S, &TInfo, &OwnedDecl);
1781
1782  if (getLangOptions().CPlusPlus && OwnedDecl && OwnedDecl->isDefinition()) {
1783    // Objective-C++: Types shall not be defined in exception types.
1784    Diag(OwnedDecl->getLocation(), diag::err_type_defined_in_param_type)
1785      << Context.getTypeDeclType(OwnedDecl);
1786  }
1787
1788  VarDecl *New = BuildObjCExceptionDecl(TInfo, ExceptionType, D.getIdentifier(),
1789                                        D.getIdentifierLoc(),
1790                                        D.isInvalidType());
1791
1792  // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
1793  if (D.getCXXScopeSpec().isSet()) {
1794    Diag(D.getIdentifierLoc(), diag::err_qualified_objc_catch_parm)
1795      << D.getCXXScopeSpec().getRange();
1796    New->setInvalidDecl();
1797  }
1798
1799  // Add the parameter declaration into this scope.
1800  S->AddDecl(DeclPtrTy::make(New));
1801  if (D.getIdentifier())
1802    IdResolver.AddDecl(New);
1803
1804  ProcessDeclAttributes(S, New, D);
1805
1806  if (New->hasAttr<BlocksAttr>())
1807    Diag(New->getLocation(), diag::err_block_on_nonlocal);
1808  return DeclPtrTy::make(New);
1809}
1810
1811/// CollectIvarsToConstructOrDestruct - Collect those ivars which require
1812/// initialization.
1813void Sema::CollectIvarsToConstructOrDestruct(const ObjCInterfaceDecl *OI,
1814                                llvm::SmallVectorImpl<ObjCIvarDecl*> &Ivars) {
1815  for (ObjCInterfaceDecl::ivar_iterator I = OI->ivar_begin(),
1816       E = OI->ivar_end(); I != E; ++I) {
1817    ObjCIvarDecl *Iv = (*I);
1818    QualType QT = Context.getBaseElementType(Iv->getType());
1819    if (QT->isRecordType())
1820      Ivars.push_back(*I);
1821  }
1822
1823  // Find ivars to construct/destruct in class extension.
1824  if (const ObjCCategoryDecl *CDecl = OI->getClassExtension()) {
1825    for (ObjCCategoryDecl::ivar_iterator I = CDecl->ivar_begin(),
1826         E = CDecl->ivar_end(); I != E; ++I) {
1827      ObjCIvarDecl *Iv = (*I);
1828      QualType QT = Context.getBaseElementType(Iv->getType());
1829      if (QT->isRecordType())
1830        Ivars.push_back(*I);
1831    }
1832  }
1833
1834  // Also add any ivar defined in this class's implementation.  This
1835  // includes synthesized ivars.
1836  if (ObjCImplementationDecl *ImplDecl = OI->getImplementation()) {
1837    for (ObjCImplementationDecl::ivar_iterator I = ImplDecl->ivar_begin(),
1838         E = ImplDecl->ivar_end(); I != E; ++I) {
1839      ObjCIvarDecl *Iv = (*I);
1840      QualType QT = Context.getBaseElementType(Iv->getType());
1841      if (QT->isRecordType())
1842        Ivars.push_back(*I);
1843    }
1844  }
1845}
1846
1847void ObjCImplementationDecl::setIvarInitializers(ASTContext &C,
1848                                    CXXBaseOrMemberInitializer ** initializers,
1849                                                 unsigned numInitializers) {
1850  if (numInitializers > 0) {
1851    NumIvarInitializers = numInitializers;
1852    CXXBaseOrMemberInitializer **ivarInitializers =
1853    new (C) CXXBaseOrMemberInitializer*[NumIvarInitializers];
1854    memcpy(ivarInitializers, initializers,
1855           numInitializers * sizeof(CXXBaseOrMemberInitializer*));
1856    IvarInitializers = ivarInitializers;
1857  }
1858}
1859
1860