blob: 483b79a0984b6cb2632a4f06e342c032e1f698c3 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregoraaba5e32009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000020#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000021#include "clang/Parse/DeclSpec.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Reid Spencer5f016e22007-07-11 17:01:13 +000031using namespace clang;
32
Chris Lattner21ff9c92009-03-05 01:25:28 +000033/// getDeclName - Return a pretty name for the specified decl if possible, or
34/// an empty string if not. This is used for pretty crash reporting.
35std::string Sema::getDeclName(DeclTy *d) {
36 Decl *D = static_cast<Decl *>(d);
37 if (NamedDecl *DN = dyn_cast_or_null<NamedDecl>(D))
38 return DN->getQualifiedNameAsString();
39 return "";
40}
41
Douglas Gregord6efafa2009-02-04 19:16:12 +000042/// \brief If the identifier refers to a type name within this scope,
43/// return the declaration of that type.
44///
45/// This routine performs ordinary name lookup of the identifier II
46/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000047/// determine whether the name refers to a type. If so, returns an
48/// opaque pointer (actually a QualType) corresponding to that
49/// type. Otherwise, returns NULL.
Douglas Gregord6efafa2009-02-04 19:16:12 +000050///
51/// If name lookup results in an ambiguity, this routine will complain
52/// and then return NULL.
Douglas Gregor1a51b4a2009-02-09 15:09:02 +000053Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregorb696ea32009-02-04 17:00:24 +000054 Scope *S, const CXXScopeSpec *SS) {
Chris Lattner22bd9052009-02-16 22:07:16 +000055 NamedDecl *IIDecl = 0;
Douglas Gregor3e41d602009-02-13 23:20:09 +000056 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName,
57 false, false);
Douglas Gregor7176fff2009-01-15 00:26:24 +000058 switch (Result.getKind()) {
Chris Lattner22bd9052009-02-16 22:07:16 +000059 case LookupResult::NotFound:
60 case LookupResult::FoundOverloaded:
61 return 0;
Douglas Gregorb696ea32009-02-04 17:00:24 +000062
Chris Lattner22bd9052009-02-16 22:07:16 +000063 case LookupResult::AmbiguousBaseSubobjectTypes:
64 case LookupResult::AmbiguousBaseSubobjects:
65 case LookupResult::AmbiguousReference:
66 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
67 return 0;
Douglas Gregorb696ea32009-02-04 17:00:24 +000068
Chris Lattner22bd9052009-02-16 22:07:16 +000069 case LookupResult::Found:
70 IIDecl = Result.getAsDecl();
71 break;
Douglas Gregor7176fff2009-01-15 00:26:24 +000072 }
73
Steve Naroffa5189032009-01-29 18:09:31 +000074 if (IIDecl) {
Douglas Gregore4e5b052009-03-19 00:18:19 +000075 QualType T;
76
Chris Lattner22bd9052009-02-16 22:07:16 +000077 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000078 // Check whether we can use this type
79 (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
Chris Lattner22bd9052009-02-16 22:07:16 +000080
Douglas Gregore4e5b052009-03-19 00:18:19 +000081 T = Context.getTypeDeclType(TD);
82 } else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl)) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +000083 // Check whether we can use this interface.
84 (void)DiagnoseUseOfDecl(IIDecl, NameLoc);
Chris Lattner22bd9052009-02-16 22:07:16 +000085
Douglas Gregore4e5b052009-03-19 00:18:19 +000086 T = Context.getObjCInterfaceType(IDecl);
87 } else
88 return 0;
89
Douglas Gregore6258932009-03-19 00:39:20 +000090 if (SS)
91 T = getQualifiedNameType(*SS, T);
Chris Lattner22bd9052009-02-16 22:07:16 +000092
Douglas Gregore4e5b052009-03-19 00:18:19 +000093 return T.getAsOpaquePtr();
Steve Naroffa5189032009-01-29 18:09:31 +000094 }
Douglas Gregore4e5b052009-03-19 00:18:19 +000095
Steve Naroff3536b442007-09-06 21:24:23 +000096 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000097}
98
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000099DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000100 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000101 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000102 if (MD->isOutOfLineDefinition())
103 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000104
Chris Lattner76a642f2009-02-15 22:43:40 +0000105 // A C++ inline method is parsed *after* the topmost class it was declared
106 // in is fully parsed (it's "complete").
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000107 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000108 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000109 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
110 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000111 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000112 DC = RD;
113
114 // Return the declaration context of the topmost class the inline method is
115 // declared in.
116 return DC;
117 }
118
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +0000119 if (isa<ObjCMethodDecl>(DC))
120 return Context.getTranslationUnitDecl();
121
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +0000122 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000123}
124
Douglas Gregor44b43212008-12-11 16:49:14 +0000125void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000126 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000127 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000128 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000129 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000130}
131
Chris Lattnerb048c982008-04-06 04:47:34 +0000132void Sema::PopDeclContext() {
133 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000134
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000135 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000136}
137
Douglas Gregorf9201e02009-02-11 23:02:49 +0000138/// \brief Determine whether we allow overloading of the function
139/// PrevDecl with another declaration.
140///
141/// This routine determines whether overloading is possible, not
142/// whether some new function is actually an overload. It will return
143/// true in C++ (where we can always provide overloads) or, as an
144/// extension, in C when the previous function is already an
145/// overloaded function declaration or has the "overloadable"
146/// attribute.
147static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
148 if (Context.getLangOptions().CPlusPlus)
149 return true;
150
151 if (isa<OverloadedFunctionDecl>(PrevDecl))
152 return true;
153
154 return PrevDecl->getAttr<OverloadableAttr>() != 0;
155}
156
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000157/// Add this decl to the scope shadowed decl chains.
158void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000159 // Move up the scope chain until we find the nearest enclosing
160 // non-transparent context. The declaration will be introduced into this
161 // scope.
162 while (S->getEntity() &&
163 ((DeclContext *)S->getEntity())->isTransparentContext())
164 S = S->getParent();
165
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000166 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000167
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000168 // Add scoped declarations into their context, so that they can be
169 // found later. Declarations without a context won't be inserted
170 // into any context.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000171 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000172
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173 // C++ [basic.scope]p4:
174 // -- exactly one declaration shall declare a class name or
175 // enumeration name that is not a typedef name and the other
176 // declarations shall all refer to the same object or
177 // enumerator, or all refer to functions and function templates;
178 // in this case the class name or enumeration name is hidden.
179 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
180 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000181 if (CurContext->getLookupContext()
182 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000183 // We're pushing the tag into the current context, which might
184 // require some reshuffling in the identifier resolver.
185 IdentifierResolver::iterator
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000186 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000187 IEnd = IdResolver.end();
188 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
189 NamedDecl *PrevDecl = *I;
190 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
191 PrevDecl = *I, ++I) {
192 if (TD->declarationReplaces(*I)) {
193 // This is a redeclaration. Remove it from the chain and
194 // break out, so that we'll add in the shadowed
195 // declaration.
196 S->RemoveDecl(*I);
197 if (PrevDecl == *I) {
198 IdResolver.RemoveDecl(*I);
199 IdResolver.AddDecl(TD);
200 return;
201 } else {
202 IdResolver.RemoveDecl(*I);
203 break;
204 }
205 }
206 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000207
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000208 // There is already a declaration with the same name in the same
209 // scope, which is not a tag declaration. It must be found
210 // before we find the new declaration, so insert the new
211 // declaration at the end of the chain.
212 IdResolver.AddShadowedDecl(TD, PrevDecl);
213
214 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000215 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000216 }
Douglas Gregorf9201e02009-02-11 23:02:49 +0000217 } else if (isa<FunctionDecl>(D) &&
218 AllowOverloadingOfFunction(D, Context)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000219 // We are pushing the name of a function, which might be an
220 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000221 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000222 IdentifierResolver::iterator Redecl
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000223 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000224 IdResolver.end(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000225 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000226 FD));
Douglas Gregor04495c82009-02-24 01:23:02 +0000227 if (Redecl != IdResolver.end() && S->isDeclScope(*Redecl)) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000228 // There is already a declaration of a function on our
229 // IdResolver chain. Replace it with this declaration.
230 S->RemoveDecl(*Redecl);
231 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000232 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000233 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000234
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000235 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000236}
237
Steve Naroffb216c882007-10-09 22:01:59 +0000238void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000239 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000240 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
241 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000242
Reid Spencer5f016e22007-07-11 17:01:13 +0000243 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
244 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000245 Decl *TmpD = static_cast<Decl*>(*I);
246 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000247
Douglas Gregor44b43212008-12-11 16:49:14 +0000248 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
249 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000250
Douglas Gregor44b43212008-12-11 16:49:14 +0000251 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000252
Douglas Gregor44b43212008-12-11 16:49:14 +0000253 // Remove this name from our lexical scope.
254 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000255 }
256}
257
Steve Naroffe8043c32008-04-01 23:04:06 +0000258/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
259/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000260ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000261 // The third "scope" argument is 0 since we aren't enabling lazy built-in
262 // creation from this context.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000263 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000264
Steve Naroffb327ce02008-04-02 14:35:35 +0000265 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000266}
267
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000268/// getNonFieldDeclScope - Retrieves the innermost scope, starting
269/// from S, where a non-field would be declared. This routine copes
270/// with the difference between C and C++ scoping rules in structs and
271/// unions. For example, the following code is well-formed in C but
272/// ill-formed in C++:
273/// @code
274/// struct S6 {
275/// enum { BAR } e;
276/// };
277///
278/// void test_S6() {
279/// struct S6 a;
280/// a.e = BAR;
281/// }
282/// @endcode
283/// For the declaration of BAR, this routine will return a different
284/// scope. The scope S will be the scope of the unnamed enumeration
285/// within S6. In C++, this routine will return the scope associated
286/// with S6, because the enumeration's scope is a transparent
287/// context but structures can contain non-field names. In C, this
288/// routine will return the translation unit scope, since the
289/// enumeration's scope is a transparent context and structures cannot
290/// contain non-field names.
291Scope *Sema::getNonFieldDeclScope(Scope *S) {
292 while (((S->getFlags() & Scope::DeclScope) == 0) ||
293 (S->getEntity() &&
294 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
295 (S->isClassScope() && !getLangOptions().CPlusPlus))
296 S = S->getParent();
297 return S;
298}
299
Chris Lattner95e2c712008-05-05 22:18:14 +0000300void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000301 if (!Context.getBuiltinVaListType().isNull())
302 return;
303
304 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000305 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroff733002f2007-10-18 22:17:45 +0000306 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000307 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
308}
309
Douglas Gregor3e41d602009-02-13 23:20:09 +0000310/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
311/// file scope. lazily create a decl for it. ForRedeclaration is true
312/// if we're creating this built-in in anticipation of redeclaring the
313/// built-in.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000314NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregor3e41d602009-02-13 23:20:09 +0000315 Scope *S, bool ForRedeclaration,
316 SourceLocation Loc) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 Builtin::ID BID = (Builtin::ID)bid;
318
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000319 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000320 InitBuiltinVaListType();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000321
Douglas Gregor370ab3f2009-02-14 01:52:53 +0000322 Builtin::Context::GetBuiltinTypeError Error;
323 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context, Error);
324 switch (Error) {
325 case Builtin::Context::GE_None:
326 // Okay
327 break;
328
329 case Builtin::Context::GE_Missing_FILE:
330 if (ForRedeclaration)
331 Diag(Loc, diag::err_implicit_decl_requires_stdio)
332 << Context.BuiltinInfo.GetName(BID);
333 return 0;
334 }
Douglas Gregor3e41d602009-02-13 23:20:09 +0000335
336 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
337 Diag(Loc, diag::ext_implicit_lib_function_decl)
338 << Context.BuiltinInfo.GetName(BID)
339 << R;
Douglas Gregorb1152d82009-02-16 21:58:21 +0000340 if (Context.BuiltinInfo.getHeaderName(BID) &&
Douglas Gregor3e41d602009-02-13 23:20:09 +0000341 Diags.getDiagnosticMapping(diag::ext_implicit_lib_function_decl)
342 != diag::MAP_IGNORE)
343 Diag(Loc, diag::note_please_include_header)
344 << Context.BuiltinInfo.getHeaderName(BID)
345 << Context.BuiltinInfo.GetName(BID);
346 }
347
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000348 FunctionDecl *New = FunctionDecl::Create(Context,
349 Context.getTranslationUnitDecl(),
Douglas Gregor3e41d602009-02-13 23:20:09 +0000350 Loc, II, R,
Douglas Gregor2224f842009-02-25 16:33:18 +0000351 FunctionDecl::Extern, false,
352 /*hasPrototype=*/true);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000353 New->setImplicit();
354
Chris Lattner95e2c712008-05-05 22:18:14 +0000355 // Create Decl objects for each parameter, adding them to the
356 // FunctionDecl.
Douglas Gregor72564e72009-02-26 23:50:07 +0000357 if (FunctionProtoType *FT = dyn_cast<FunctionProtoType>(R)) {
Chris Lattner95e2c712008-05-05 22:18:14 +0000358 llvm::SmallVector<ParmVarDecl*, 16> Params;
359 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
360 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000361 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000362 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000363 }
364
Douglas Gregor3c385e52009-02-14 18:57:46 +0000365 AddKnownFunctionAttributes(New);
Chris Lattner95e2c712008-05-05 22:18:14 +0000366
Chris Lattner7f925cc2008-04-11 07:00:53 +0000367 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000368 // FIXME: This is hideous. We need to teach PushOnScopeChains to
369 // relate Scopes to DeclContexts, and probably eliminate CurContext
370 // entirely, but we're not there yet.
371 DeclContext *SavedContext = CurContext;
372 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000373 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000374 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 return New;
376}
377
Sebastian Redlc42e1182008-11-11 11:37:55 +0000378/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
379/// everything from the standard library is defined.
380NamespaceDecl *Sema::GetStdNamespace() {
381 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000382 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000383 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregor4c921ae2009-01-30 01:04:22 +0000384 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000385 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
386 }
387 return StdNamespace;
388}
389
Douglas Gregorcda9c672009-02-16 17:45:42 +0000390/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
391/// same name and scope as a previous declaration 'Old'. Figure out
392/// how to resolve this situation, merging decls or emitting
393/// diagnostics as appropriate. Returns true if there was an error,
394/// false otherwise.
Reid Spencer5f016e22007-07-11 17:01:13 +0000395///
Douglas Gregorcda9c672009-02-16 17:45:42 +0000396bool Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000397 bool objc_types = false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000398 // Allow multiple definitions for ObjC built-in typedefs.
399 // FIXME: Verify the underlying types are equivalent!
400 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000401 const IdentifierInfo *TypeID = New->getIdentifier();
402 switch (TypeID->getLength()) {
403 default: break;
404 case 2:
405 if (!TypeID->isStr("id"))
406 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000407 Context.setObjCIdType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000408 objc_types = true;
409 break;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000410 case 5:
411 if (!TypeID->isStr("Class"))
412 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000413 Context.setObjCClassType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000414 objc_types = true;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000415 return false;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000416 case 3:
417 if (!TypeID->isStr("SEL"))
418 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000419 Context.setObjCSelType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000420 objc_types = true;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000421 return false;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000422 case 8:
423 if (!TypeID->isStr("Protocol"))
424 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000425 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000426 objc_types = true;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000427 return false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000428 }
429 // Fall through - the typedef name was not a builtin type.
430 }
Douglas Gregor66973122009-01-28 17:15:10 +0000431 // Verify the old decl was also a type.
432 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000433 if (!Old) {
Douglas Gregor66973122009-01-28 17:15:10 +0000434 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000435 << New->getDeclName();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000436 if (!objc_types)
437 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000438 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000439 }
Douglas Gregor66973122009-01-28 17:15:10 +0000440
441 // Determine the "old" type we'll use for checking and diagnostics.
442 QualType OldType;
443 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
444 OldType = OldTypedef->getUnderlyingType();
445 else
446 OldType = Context.getTypeDeclType(Old);
447
Chris Lattner99cb9972008-07-25 18:44:27 +0000448 // If the typedef types are not identical, reject them in all languages and
449 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000450
451 if (OldType != New->getUnderlyingType() &&
452 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000453 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000454 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000455 << New->getUnderlyingType() << OldType;
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000456 if (!objc_types)
457 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000458 return true;
Chris Lattner99cb9972008-07-25 18:44:27 +0000459 }
Douglas Gregorcda9c672009-02-16 17:45:42 +0000460 if (objc_types) return false;
461 if (getLangOptions().Microsoft) return false;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000462
Douglas Gregorbbe27432008-11-21 16:29:06 +0000463 // C++ [dcl.typedef]p2:
464 // In a given non-class scope, a typedef specifier can be used to
465 // redefine the name of any type declared in that scope to refer
466 // to the type to which it already refers.
467 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
Douglas Gregorcda9c672009-02-16 17:45:42 +0000468 return false;
Douglas Gregorbbe27432008-11-21 16:29:06 +0000469
470 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000471 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
472 // *either* declaration is in a system header. The code below implements
473 // this adhoc compatibility rule. FIXME: The following code will not
474 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000475 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
476 SourceManager &SrcMgr = Context.getSourceManager();
477 if (SrcMgr.isInSystemHeader(Old->getLocation()))
Douglas Gregorcda9c672009-02-16 17:45:42 +0000478 return false;
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000479 if (SrcMgr.isInSystemHeader(New->getLocation()))
Douglas Gregorcda9c672009-02-16 17:45:42 +0000480 return false;
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000481 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000482
Chris Lattner08631c52008-11-23 21:45:46 +0000483 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000484 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000485 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000486}
487
Chris Lattner6b6b5372008-06-26 18:38:35 +0000488/// DeclhasAttr - returns true if decl Declaration already has the target
489/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000490static bool DeclHasAttr(const Decl *decl, const Attr *target) {
491 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
492 if (attr->getKind() == target->getKind())
493 return true;
494
495 return false;
496}
497
498/// MergeAttributes - append attributes from the Old decl to the New one.
Chris Lattnercc581472009-03-04 06:05:19 +0000499static void MergeAttributes(Decl *New, Decl *Old, ASTContext &C) {
500 Attr *attr = const_cast<Attr*>(Old->getAttrs());
Chris Lattnerddee4232008-03-03 03:28:21 +0000501
Chris Lattnerddee4232008-03-03 03:28:21 +0000502 while (attr) {
Chris Lattnercc581472009-03-04 06:05:19 +0000503 Attr *tmp = attr;
Douglas Gregorae170942009-02-13 00:26:38 +0000504 attr = attr->getNext();
Chris Lattnerddee4232008-03-03 03:28:21 +0000505
Douglas Gregorae170942009-02-13 00:26:38 +0000506 if (!DeclHasAttr(New, tmp) && tmp->isMerged()) {
507 tmp->setInherited(true);
508 New->addAttr(tmp);
Chris Lattnerddee4232008-03-03 03:28:21 +0000509 } else {
Douglas Gregorae170942009-02-13 00:26:38 +0000510 tmp->setNext(0);
Chris Lattnercc581472009-03-04 06:05:19 +0000511 tmp->Destroy(C);
Chris Lattnerddee4232008-03-03 03:28:21 +0000512 }
513 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000514
515 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000516}
517
Douglas Gregorc8376562009-03-06 22:43:54 +0000518/// Used in MergeFunctionDecl to keep track of function parameters in
519/// C.
520struct GNUCompatibleParamWarning {
521 ParmVarDecl *OldParm;
522 ParmVarDecl *NewParm;
523 QualType PromotedType;
524};
525
Chris Lattner04421082008-04-08 04:40:51 +0000526/// MergeFunctionDecl - We just parsed a function 'New' from
527/// declarator D which has the same name and scope as a previous
528/// declaration 'Old'. Figure out how to resolve this situation,
529/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000530///
531/// In C++, New and Old must be declarations that are not
532/// overloaded. Use IsOverload to determine whether New and Old are
533/// overloaded, and to select the Old declaration that New should be
534/// merged with.
Douglas Gregorcda9c672009-02-16 17:45:42 +0000535///
536/// Returns true if there was an error, false otherwise.
537bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000538 assert(!isa<OverloadedFunctionDecl>(OldD) &&
539 "Cannot merge with an overloaded function declaration");
540
Reid Spencer5f016e22007-07-11 17:01:13 +0000541 // Verify the old decl was also a function.
542 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
543 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000544 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000545 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000546 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000547 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000548 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000549
550 // Determine whether the previous declaration was a definition,
551 // implicit declaration, or a declaration.
552 diag::kind PrevDiag;
553 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000554 PrevDiag = diag::note_previous_definition;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000555 else if (Old->isImplicit())
556 PrevDiag = diag::note_previous_implicit_declaration;
557 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000558 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000559
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000560 QualType OldQType = Context.getCanonicalType(Old->getType());
561 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000562
Douglas Gregor04495c82009-02-24 01:23:02 +0000563 if (!isa<CXXMethodDecl>(New) && !isa<CXXMethodDecl>(Old) &&
564 New->getStorageClass() == FunctionDecl::Static &&
565 Old->getStorageClass() != FunctionDecl::Static) {
566 Diag(New->getLocation(), diag::err_static_non_static)
567 << New;
568 Diag(Old->getLocation(), PrevDiag);
569 return true;
570 }
571
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000572 if (getLangOptions().CPlusPlus) {
573 // (C++98 13.1p2):
574 // Certain function declarations cannot be overloaded:
575 // -- Function declarations that differ only in the return type
576 // cannot be overloaded.
577 QualType OldReturnType
578 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
579 QualType NewReturnType
580 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
581 if (OldReturnType != NewReturnType) {
582 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000583 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000584 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000585 }
586
587 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
588 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
Douglas Gregor656de632009-03-11 23:52:16 +0000589 if (OldMethod && NewMethod &&
590 OldMethod->getLexicalDeclContext() ==
591 NewMethod->getLexicalDeclContext()) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000592 // -- Member function declarations with the same name and the
593 // same parameter types cannot be overloaded if any of them
594 // is a static member function declaration.
595 if (OldMethod->isStatic() || NewMethod->isStatic()) {
596 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Douglas Gregor3e41d602009-02-13 23:20:09 +0000597 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000598 return true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000599 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000600
601 // C++ [class.mem]p1:
602 // [...] A member shall not be declared twice in the
603 // member-specification, except that a nested class or member
604 // class template can be declared and then later defined.
Douglas Gregor656de632009-03-11 23:52:16 +0000605 unsigned NewDiag;
606 if (isa<CXXConstructorDecl>(OldMethod))
607 NewDiag = diag::err_constructor_redeclared;
608 else if (isa<CXXDestructorDecl>(NewMethod))
609 NewDiag = diag::err_destructor_redeclared;
610 else if (isa<CXXConversionDecl>(NewMethod))
611 NewDiag = diag::err_conv_function_redeclared;
612 else
613 NewDiag = diag::err_member_redeclared;
614
615 Diag(New->getLocation(), NewDiag);
616 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000617 }
618
619 // (C++98 8.3.5p3):
620 // All declarations for a function shall agree exactly in both the
621 // return type and the parameter-type-list.
Douglas Gregor04495c82009-02-24 01:23:02 +0000622 if (OldQType == NewQType)
623 return MergeCompatibleFunctionDecls(New, Old);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000624
625 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000626 }
Chris Lattner04421082008-04-08 04:40:51 +0000627
628 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000629 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000630 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000631 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorc8376562009-03-06 22:43:54 +0000632 const FunctionType *OldFuncType = OldQType->getAsFunctionType();
Douglas Gregor68719812009-02-16 18:20:44 +0000633 const FunctionType *NewFuncType = NewQType->getAsFunctionType();
Douglas Gregor72564e72009-02-26 23:50:07 +0000634 const FunctionProtoType *OldProto = 0;
635 if (isa<FunctionNoProtoType>(NewFuncType) &&
Douglas Gregorc8376562009-03-06 22:43:54 +0000636 (OldProto = dyn_cast<FunctionProtoType>(OldFuncType))) {
Douglas Gregor68719812009-02-16 18:20:44 +0000637 // The old declaration provided a function prototype, but the
638 // new declaration does not. Merge in the prototype.
639 llvm::SmallVector<QualType, 16> ParamTypes(OldProto->arg_type_begin(),
640 OldProto->arg_type_end());
641 NewQType = Context.getFunctionType(NewFuncType->getResultType(),
642 &ParamTypes[0], ParamTypes.size(),
643 OldProto->isVariadic(),
644 OldProto->getTypeQuals());
645 New->setType(NewQType);
646 New->setInheritedPrototype();
Douglas Gregor450da982009-02-16 20:58:07 +0000647
648 // Synthesize a parameter for each argument type.
649 llvm::SmallVector<ParmVarDecl*, 16> Params;
Douglas Gregor72564e72009-02-26 23:50:07 +0000650 for (FunctionProtoType::arg_type_iterator
Douglas Gregor450da982009-02-16 20:58:07 +0000651 ParamType = OldProto->arg_type_begin(),
652 ParamEnd = OldProto->arg_type_end();
653 ParamType != ParamEnd; ++ParamType) {
654 ParmVarDecl *Param = ParmVarDecl::Create(Context, New,
655 SourceLocation(), 0,
656 *ParamType, VarDecl::None,
657 0);
658 Param->setImplicit();
659 Params.push_back(Param);
660 }
661
662 New->setParams(Context, &Params[0], Params.size());
Douglas Gregorc8376562009-03-06 22:43:54 +0000663 }
Douglas Gregor68719812009-02-16 18:20:44 +0000664
Douglas Gregor04495c82009-02-24 01:23:02 +0000665 return MergeCompatibleFunctionDecls(New, Old);
Chris Lattner04421082008-04-08 04:40:51 +0000666 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000667
Douglas Gregorc8376562009-03-06 22:43:54 +0000668 // GNU C permits a K&R definition to follow a prototype declaration
669 // if the declared types of the parameters in the K&R definition
670 // match the types in the prototype declaration, even when the
671 // promoted types of the parameters from the K&R definition differ
672 // from the types in the prototype. GCC then keeps the types from
673 // the prototype.
674 if (!getLangOptions().CPlusPlus &&
675 !getLangOptions().NoExtensions &&
676 Old->hasPrototype() && !New->hasPrototype() &&
677 New->getType()->getAsFunctionProtoType() &&
678 Old->getNumParams() == New->getNumParams()) {
679 llvm::SmallVector<QualType, 16> ArgTypes;
680 llvm::SmallVector<GNUCompatibleParamWarning, 16> Warnings;
681 const FunctionProtoType *OldProto
682 = Old->getType()->getAsFunctionProtoType();
683 const FunctionProtoType *NewProto
684 = New->getType()->getAsFunctionProtoType();
685
686 // Determine whether this is the GNU C extension.
687 bool GNUCompatible =
688 Context.typesAreCompatible(OldProto->getResultType(),
689 NewProto->getResultType()) &&
690 (OldProto->isVariadic() == NewProto->isVariadic());
691 for (unsigned Idx = 0, End = Old->getNumParams();
692 GNUCompatible && Idx != End; ++Idx) {
693 ParmVarDecl *OldParm = Old->getParamDecl(Idx);
694 ParmVarDecl *NewParm = New->getParamDecl(Idx);
695 if (Context.typesAreCompatible(OldParm->getType(),
696 NewProto->getArgType(Idx))) {
697 ArgTypes.push_back(NewParm->getType());
698 } else if (Context.typesAreCompatible(OldParm->getType(),
699 NewParm->getType())) {
700 GNUCompatibleParamWarning Warn
701 = { OldParm, NewParm, NewProto->getArgType(Idx) };
702 Warnings.push_back(Warn);
703 ArgTypes.push_back(NewParm->getType());
704 } else
705 GNUCompatible = false;
706 }
707
708 if (GNUCompatible) {
709 for (unsigned Warn = 0; Warn < Warnings.size(); ++Warn) {
710 Diag(Warnings[Warn].NewParm->getLocation(),
711 diag::ext_param_promoted_not_compatible_with_prototype)
712 << Warnings[Warn].PromotedType
713 << Warnings[Warn].OldParm->getType();
714 Diag(Warnings[Warn].OldParm->getLocation(),
715 diag::note_previous_declaration);
716 }
717
718 New->setType(Context.getFunctionType(NewProto->getResultType(),
719 &ArgTypes[0], ArgTypes.size(),
720 NewProto->isVariadic(),
721 NewProto->getTypeQuals()));
722 return MergeCompatibleFunctionDecls(New, Old);
723 }
724
725 // Fall through to diagnose conflicting types.
726 }
727
Steve Naroff837618c2008-01-16 15:01:34 +0000728 // A function that has already been declared has been redeclared or defined
729 // with a different type- show appropriate diagnostic
Douglas Gregorcda9c672009-02-16 17:45:42 +0000730 if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
731 // The user has declared a builtin function with an incompatible
732 // signature.
733 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
734 // The function the user is redeclaring is a library-defined
735 // function like 'malloc' or 'printf'. Warn about the
736 // redeclaration, then ignore it.
737 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
738 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
739 << Old << Old->getType();
Douglas Gregorc2b6a822009-02-18 22:00:45 +0000740 return true;
Douglas Gregorcda9c672009-02-16 17:45:42 +0000741 }
Steve Naroff837618c2008-01-16 15:01:34 +0000742
Douglas Gregorcda9c672009-02-16 17:45:42 +0000743 PrevDiag = diag::note_previous_builtin_declaration;
744 }
745
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000746 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregor3e41d602009-02-13 23:20:09 +0000747 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregorcda9c672009-02-16 17:45:42 +0000748 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000749}
750
Douglas Gregor04495c82009-02-24 01:23:02 +0000751/// \brief Completes the merge of two function declarations that are
752/// known to be compatible.
753///
754/// This routine handles the merging of attributes and other
755/// properties of function declarations form the old declaration to
756/// the new declaration, once we know that New is in fact a
757/// redeclaration of Old.
758///
759/// \returns false
760bool Sema::MergeCompatibleFunctionDecls(FunctionDecl *New, FunctionDecl *Old) {
761 // Merge the attributes
Chris Lattnercc581472009-03-04 06:05:19 +0000762 MergeAttributes(New, Old, Context);
Douglas Gregor04495c82009-02-24 01:23:02 +0000763
764 // Merge the storage class.
765 New->setStorageClass(Old->getStorageClass());
766
767 // FIXME: need to implement inline semantics
768
769 // Merge "pure" flag.
770 if (Old->isPure())
771 New->setPure();
772
773 // Merge the "deleted" flag.
774 if (Old->isDeleted())
775 New->setDeleted();
776
777 if (getLangOptions().CPlusPlus)
778 return MergeCXXFunctionDecl(New, Old);
779
780 return false;
781}
782
Reid Spencer5f016e22007-07-11 17:01:13 +0000783/// MergeVarDecl - We just parsed a variable 'New' which has the same name
784/// and scope as a previous declaration 'Old'. Figure out how to resolve this
785/// situation, merging decls or emitting diagnostics as appropriate.
786///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000787/// Tentative definition rules (C99 6.9.2p2) are checked by
788/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
789/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000790///
Douglas Gregorcda9c672009-02-16 17:45:42 +0000791bool Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000792 // Verify the old decl was also a variable.
793 VarDecl *Old = dyn_cast<VarDecl>(OldD);
794 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000795 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000796 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000797 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000798 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000800
Chris Lattnercc581472009-03-04 06:05:19 +0000801 MergeAttributes(New, Old, Context);
Chris Lattnerddee4232008-03-03 03:28:21 +0000802
Eli Friedman13ca96a2009-01-24 23:49:55 +0000803 // Merge the types
804 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
805 if (MergedT.isNull()) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000806 Diag(New->getLocation(), diag::err_redefinition_different_type)
807 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000808 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000809 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000810 }
Eli Friedman13ca96a2009-01-24 23:49:55 +0000811 New->setType(MergedT);
Douglas Gregor656de632009-03-11 23:52:16 +0000812
Steve Naroffb7b032e2008-01-30 00:44:01 +0000813 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
814 if (New->getStorageClass() == VarDecl::Static &&
815 (Old->getStorageClass() == VarDecl::None ||
816 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000817 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000818 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000819 return true;
Steve Naroffb7b032e2008-01-30 00:44:01 +0000820 }
821 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
822 if (New->getStorageClass() != VarDecl::Static &&
823 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000824 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000825 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000826 return true;
Steve Naroffb7b032e2008-01-30 00:44:01 +0000827 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000828 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
Douglas Gregor656de632009-03-11 23:52:16 +0000829 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl() &&
830 // Don't complain about out-of-line definitions of static members.
831 !(Old->getLexicalDeclContext()->isRecord() &&
832 !New->getLexicalDeclContext()->isRecord())) {
Chris Lattner08631c52008-11-23 21:45:46 +0000833 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000834 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregorcda9c672009-02-16 17:45:42 +0000835 return true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000836 }
Douglas Gregor275a3692009-03-10 23:43:53 +0000837
838 // Keep a chain of previous declarations.
839 New->setPreviousDeclaration(Old);
840
Douglas Gregorcda9c672009-02-16 17:45:42 +0000841 return false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000842}
843
Chris Lattner04421082008-04-08 04:40:51 +0000844/// CheckParmsForFunctionDef - Check that the parameters of the given
845/// function are appropriate for the definition of a function. This
846/// takes care of any checks that cannot be performed on the
847/// declaration itself, e.g., that the types of each of the function
848/// parameters are complete.
849bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
850 bool HasInvalidParm = false;
851 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
852 ParmVarDecl *Param = FD->getParamDecl(p);
853
854 // C99 6.7.5.3p4: the parameters in a parameter type list in a
855 // function declarator that is part of a function definition of
856 // that function shall not have incomplete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000857 if (!Param->isInvalidDecl() &&
Douglas Gregor86447ec2009-03-09 16:13:40 +0000858 RequireCompleteType(Param->getLocation(), Param->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000859 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +0000860 Param->setInvalidDecl();
861 HasInvalidParm = true;
862 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000863
864 // C99 6.9.1p5: If the declarator includes a parameter type list, the
865 // declaration of each parameter shall include an identifier.
Douglas Gregor450da982009-02-16 20:58:07 +0000866 if (Param->getIdentifier() == 0 &&
867 !Param->isImplicit() &&
868 !getLangOptions().CPlusPlus)
Chris Lattner777f07b2008-12-17 07:32:46 +0000869 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000870 }
871
872 return HasInvalidParm;
873}
874
Reid Spencer5f016e22007-07-11 17:01:13 +0000875/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
876/// no declarator (e.g. "struct foo;") is parsed.
877Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +0000878 TagDecl *Tag = 0;
879 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
880 DS.getTypeSpecType() == DeclSpec::TST_struct ||
881 DS.getTypeSpecType() == DeclSpec::TST_union ||
882 DS.getTypeSpecType() == DeclSpec::TST_enum)
883 Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
884
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000885 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
886 if (!Record->getDeclName() && Record->isDefinition() &&
Douglas Gregora71c1292009-03-06 23:06:59 +0000887 DS.getStorageClassSpec() != DeclSpec::SCS_typedef) {
888 if (getLangOptions().CPlusPlus ||
889 Record->getDeclContext()->isRecord())
890 return BuildAnonymousStructOrUnion(S, DS, Record);
891
892 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
893 << DS.getSourceRange();
894 }
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000895
896 // Microsoft allows unnamed struct/union fields. Don't complain
897 // about them.
898 // FIXME: Should we support Microsoft's extensions in this area?
899 if (Record->getDeclName() && getLangOptions().Microsoft)
900 return Tag;
901 }
902
Douglas Gregorddc29e12009-02-06 22:42:48 +0000903 if (!DS.isMissingDeclaratorOk() &&
904 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000905 // Warn about typedefs of enums without names, since this is an
906 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +0000907 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
908 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000909 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +0000910 << DS.getSourceRange();
911 return Tag;
912 }
913
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000914 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
915 << DS.getSourceRange();
916 return 0;
917 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000918
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000919 return Tag;
920}
921
922/// InjectAnonymousStructOrUnionMembers - Inject the members of the
923/// anonymous struct or union AnonRecord into the owning context Owner
924/// and scope S. This routine will be invoked just after we realize
925/// that an unnamed union or struct is actually an anonymous union or
926/// struct, e.g.,
927///
928/// @code
929/// union {
930/// int i;
931/// float f;
932/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
933/// // f into the surrounding scope.x
934/// @endcode
935///
936/// This routine is recursive, injecting the names of nested anonymous
937/// structs/unions into the owning context and scope as well.
938bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
939 RecordDecl *AnonRecord) {
940 bool Invalid = false;
941 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
942 FEnd = AnonRecord->field_end();
943 F != FEnd; ++F) {
944 if ((*F)->getDeclName()) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +0000945 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
946 LookupOrdinaryName, true);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000947 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
948 // C++ [class.union]p2:
949 // The names of the members of an anonymous union shall be
950 // distinct from the names of any other entity in the
951 // scope in which the anonymous union is declared.
952 unsigned diagKind
953 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
954 : diag::err_anonymous_struct_member_redecl;
955 Diag((*F)->getLocation(), diagKind)
956 << (*F)->getDeclName();
957 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
958 Invalid = true;
959 } else {
960 // C++ [class.union]p2:
961 // For the purpose of name lookup, after the anonymous union
962 // definition, the members of the anonymous union are
963 // considered to have been defined in the scope in which the
964 // anonymous union is declared.
Douglas Gregor40f4e692009-01-20 16:54:50 +0000965 Owner->makeDeclVisibleInContext(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000966 S->AddDecl(*F);
967 IdResolver.AddDecl(*F);
968 }
969 } else if (const RecordType *InnerRecordType
970 = (*F)->getType()->getAsRecordType()) {
971 RecordDecl *InnerRecord = InnerRecordType->getDecl();
972 if (InnerRecord->isAnonymousStructOrUnion())
973 Invalid = Invalid ||
974 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
975 }
976 }
977
978 return Invalid;
979}
980
981/// ActOnAnonymousStructOrUnion - Handle the declaration of an
982/// anonymous structure or union. Anonymous unions are a C++ feature
983/// (C++ [class.union]) and a GNU C extension; anonymous structures
984/// are a GNU C and GNU C++ extension.
985Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
986 RecordDecl *Record) {
987 DeclContext *Owner = Record->getDeclContext();
988
989 // Diagnose whether this anonymous struct/union is an extension.
990 if (Record->isUnion() && !getLangOptions().CPlusPlus)
991 Diag(Record->getLocation(), diag::ext_anonymous_union);
992 else if (!Record->isUnion())
993 Diag(Record->getLocation(), diag::ext_anonymous_struct);
994
995 // C and C++ require different kinds of checks for anonymous
996 // structs/unions.
997 bool Invalid = false;
998 if (getLangOptions().CPlusPlus) {
999 const char* PrevSpec = 0;
1000 // C++ [class.union]p3:
1001 // Anonymous unions declared in a named namespace or in the
1002 // global namespace shall be declared static.
1003 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
1004 (isa<TranslationUnitDecl>(Owner) ||
1005 (isa<NamespaceDecl>(Owner) &&
1006 cast<NamespaceDecl>(Owner)->getDeclName()))) {
1007 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
1008 Invalid = true;
1009
1010 // Recover by adding 'static'.
1011 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
1012 }
1013 // C++ [class.union]p3:
1014 // A storage class is not allowed in a declaration of an
1015 // anonymous union in a class scope.
1016 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
1017 isa<RecordDecl>(Owner)) {
1018 Diag(DS.getStorageClassSpecLoc(),
1019 diag::err_anonymous_union_with_storage_spec);
1020 Invalid = true;
1021
1022 // Recover by removing the storage specifier.
1023 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
1024 PrevSpec);
1025 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001026
1027 // C++ [class.union]p2:
1028 // The member-specification of an anonymous union shall only
1029 // define non-static data members. [Note: nested types and
1030 // functions cannot be declared within an anonymous union. ]
1031 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
1032 MemEnd = Record->decls_end();
1033 Mem != MemEnd; ++Mem) {
1034 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
1035 // C++ [class.union]p3:
1036 // An anonymous union shall not have private or protected
1037 // members (clause 11).
1038 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
1039 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
1040 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
1041 Invalid = true;
1042 }
1043 } else if ((*Mem)->isImplicit()) {
1044 // Any implicit members are fine.
Douglas Gregor1931b442009-02-03 00:34:39 +00001045 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
1046 // This is a type that showed up in an
1047 // elaborated-type-specifier inside the anonymous struct or
1048 // union, but which actually declares a type outside of the
1049 // anonymous struct or union. It's okay.
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001050 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
1051 if (!MemRecord->isAnonymousStructOrUnion() &&
1052 MemRecord->getDeclName()) {
1053 // This is a nested type declaration.
1054 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
1055 << (int)Record->isUnion();
1056 Invalid = true;
1057 }
1058 } else {
1059 // We have something that isn't a non-static data
1060 // member. Complain about it.
1061 unsigned DK = diag::err_anonymous_record_bad_member;
1062 if (isa<TypeDecl>(*Mem))
1063 DK = diag::err_anonymous_record_with_type;
1064 else if (isa<FunctionDecl>(*Mem))
1065 DK = diag::err_anonymous_record_with_function;
1066 else if (isa<VarDecl>(*Mem))
1067 DK = diag::err_anonymous_record_with_static;
1068 Diag((*Mem)->getLocation(), DK)
1069 << (int)Record->isUnion();
1070 Invalid = true;
1071 }
1072 }
Douglas Gregora71c1292009-03-06 23:06:59 +00001073 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001074
1075 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001076 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
1077 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001078 Invalid = true;
1079 }
1080
1081 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001082 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001083 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
1084 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
1085 /*IdentifierInfo=*/0,
1086 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001087 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001088 Anon->setAccess(AS_public);
1089 if (getLangOptions().CPlusPlus)
1090 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001091 } else {
1092 VarDecl::StorageClass SC;
1093 switch (DS.getStorageClassSpec()) {
1094 default: assert(0 && "Unknown storage class!");
1095 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1096 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1097 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1098 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1099 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1100 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1101 case DeclSpec::SCS_mutable:
1102 // mutable can only appear on non-static class members, so it's always
1103 // an error here
1104 Diag(Record->getLocation(), diag::err_mutable_nonmember);
1105 Invalid = true;
1106 SC = VarDecl::None;
1107 break;
1108 }
1109
1110 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
1111 /*IdentifierInfo=*/0,
1112 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001113 SC, DS.getSourceRange().getBegin());
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001114 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +00001115 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001116
1117 // Add the anonymous struct/union object to the current
1118 // context. We'll be referencing this object when we refer to one of
1119 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +00001120 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001121
1122 // Inject the members of the anonymous struct/union into the owning
1123 // context and into the identifier resolver chain for name lookup
1124 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00001125 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1126 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001127
1128 // Mark this as an anonymous struct/union type. Note that we do not
1129 // do this until after we have already checked and injected the
1130 // members of this anonymous struct/union type, because otherwise
1131 // the members could be injected twice: once by DeclContext when it
1132 // builds its lookup table, and once by
1133 // InjectAnonymousStructOrUnionMembers.
1134 Record->setAnonymousStructOrUnion(true);
1135
1136 if (Invalid)
1137 Anon->setInvalidDecl();
1138
1139 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +00001140}
1141
Steve Narofff0090632007-09-02 02:04:30 +00001142
Douglas Gregor10bd3682008-11-17 22:58:34 +00001143/// GetNameForDeclarator - Determine the full declaration name for the
1144/// given Declarator.
1145DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1146 switch (D.getKind()) {
1147 case Declarator::DK_Abstract:
1148 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1149 return DeclarationName();
1150
1151 case Declarator::DK_Normal:
1152 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1153 return DeclarationName(D.getIdentifier());
1154
1155 case Declarator::DK_Constructor: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001156 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001157 Ty = Context.getCanonicalType(Ty);
1158 return Context.DeclarationNames.getCXXConstructorName(Ty);
1159 }
1160
1161 case Declarator::DK_Destructor: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001162 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001163 Ty = Context.getCanonicalType(Ty);
1164 return Context.DeclarationNames.getCXXDestructorName(Ty);
1165 }
1166
1167 case Declarator::DK_Conversion: {
Douglas Gregor1a51b4a2009-02-09 15:09:02 +00001168 // FIXME: We'd like to keep the non-canonical type for diagnostics!
Douglas Gregor10bd3682008-11-17 22:58:34 +00001169 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1170 Ty = Context.getCanonicalType(Ty);
1171 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1172 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001173
1174 case Declarator::DK_Operator:
1175 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1176 return Context.DeclarationNames.getCXXOperatorName(
1177 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001178 }
1179
1180 assert(false && "Unknown name kind");
1181 return DeclarationName();
1182}
1183
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001184/// isNearlyMatchingFunction - Determine whether the C++ functions
1185/// Declaration and Definition are "nearly" matching. This heuristic
1186/// is used to improve diagnostics in the case where an out-of-line
1187/// function definition doesn't match any declaration within
1188/// the class or namespace.
1189static bool isNearlyMatchingFunction(ASTContext &Context,
1190 FunctionDecl *Declaration,
1191 FunctionDecl *Definition) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001192 if (Declaration->param_size() != Definition->param_size())
1193 return false;
1194 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1195 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1196 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1197
1198 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1199 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1200 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1201 return false;
1202 }
1203
1204 return true;
1205}
1206
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001207Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001208Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1209 bool IsFunctionDefinition) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001210 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001211 DeclarationName Name = GetNameForDeclarator(D);
1212
Chris Lattnere80a59c2007-07-25 00:24:17 +00001213 // All of these full declarators require an identifier. If it doesn't have
1214 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001215 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001216 if (!D.getInvalidType()) // Reject this if we think it is valid.
1217 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001218 diag::err_declarator_need_ident)
1219 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001220 return 0;
1221 }
1222
Chris Lattner31e05722007-08-26 06:24:45 +00001223 // The scope passed in may not be a decl scope. Zip up the scope tree until
1224 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001225 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregoraaba5e32009-02-04 19:02:06 +00001226 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001227 S = S->getParent();
1228
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001229 DeclContext *DC;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00001230 NamedDecl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001231 NamedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001232 bool InvalidDecl = false;
Douglas Gregorcda9c672009-02-16 17:45:42 +00001233
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001234 QualType R = GetTypeForDeclarator(D, S);
1235 if (R.isNull()) {
1236 InvalidDecl = true;
1237 R = Context.IntTy;
1238 }
1239
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001240 // See if this is a redefinition of a variable in the same scope.
Douglas Gregor9fa14a52009-03-06 19:06:37 +00001241 if (D.getCXXScopeSpec().isInvalid()) {
1242 DC = CurContext;
1243 PrevDecl = 0;
1244 InvalidDecl = true;
1245 } else if (!D.getCXXScopeSpec().isSet()) {
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001246 LookupNameKind NameKind = LookupOrdinaryName;
1247
1248 // If the declaration we're planning to build will be a function
1249 // or object with linkage, then look for another declaration with
1250 // linkage (C99 6.2.2p4-5 and C++ [basic.link]p6).
1251 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef)
1252 /* Do nothing*/;
1253 else if (R->isFunctionType()) {
1254 if (CurContext->isFunctionOrMethod())
1255 NameKind = LookupRedeclarationWithLinkage;
1256 } else if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_extern)
1257 NameKind = LookupRedeclarationWithLinkage;
1258
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001259 DC = CurContext;
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001260 PrevDecl = LookupName(S, Name, NameKind, true,
Douglas Gregor9add3172009-02-17 03:23:10 +00001261 D.getDeclSpec().getStorageClassSpec() !=
1262 DeclSpec::SCS_static,
Douglas Gregor3e41d602009-02-13 23:20:09 +00001263 D.getIdentifierLoc());
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001264 } else { // Something like "int foo::x;"
Douglas Gregore4e5b052009-03-19 00:18:19 +00001265 DC = computeDeclContext(D.getCXXScopeSpec());
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00001266 // FIXME: RequireCompleteDeclContext(D.getCXXScopeSpec()); ?
Douglas Gregor3e41d602009-02-13 23:20:09 +00001267 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001268
1269 // C++ 7.3.1.2p2:
1270 // Members (including explicit specializations of templates) of a named
1271 // namespace can also be defined outside that namespace by explicit
1272 // qualification of the name being defined, provided that the entity being
1273 // defined was already declared in the namespace and the definition appears
1274 // after the point of declaration in a namespace that encloses the
1275 // declarations namespace.
1276 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001277 // Note that we only check the context at this point. We don't yet
1278 // have enough information to make sure that PrevDecl is actually
1279 // the declaration we want to match. For example, given:
1280 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001281 // class X {
1282 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001283 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001284 // };
1285 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001286 // void X::f(int) { } // ill-formed
1287 //
1288 // In this case, PrevDecl will point to the overload set
1289 // containing the two f's declared in X, but neither of them
1290 // matches.
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001291
1292 // First check whether we named the global scope.
1293 if (isa<TranslationUnitDecl>(DC)) {
1294 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1295 << Name << D.getCXXScopeSpec().getRange();
1296 } else if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001297 // The qualifying scope doesn't enclose the original declaration.
1298 // Emit diagnostic based on current scope.
1299 SourceLocation L = D.getIdentifierLoc();
1300 SourceRange R = D.getCXXScopeSpec().getRange();
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001301 if (isa<FunctionDecl>(CurContext))
Chris Lattner011bb4e2008-11-23 20:28:15 +00001302 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001303 else
Chris Lattner011bb4e2008-11-23 20:28:15 +00001304 Diag(L, diag::err_invalid_declarator_scope)
Douglas Gregor4ce205f2009-02-06 17:46:57 +00001305 << Name << cast<NamedDecl>(DC) << R;
Douglas Gregor44b43212008-12-11 16:49:14 +00001306 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001307 }
1308 }
1309
Douglas Gregorf57172b2008-12-08 18:40:42 +00001310 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001311 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001312 InvalidDecl = InvalidDecl
1313 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001314 // Just pretend that we didn't see the previous declaration.
1315 PrevDecl = 0;
1316 }
1317
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001318 // In C++, the previous declaration we find might be a tag type
1319 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00001320 // tag type. Note that this does does not apply if we're declaring a
1321 // typedef (C++ [dcl.typedef]p4).
1322 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1323 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001324 PrevDecl = 0;
1325
Douglas Gregorcda9c672009-02-16 17:45:42 +00001326 bool Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +00001327 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001328 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001329 InvalidDecl, Redeclaration);
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001330 } else if (R->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001331 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001332 IsFunctionDefinition, InvalidDecl,
1333 Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00001334 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001335 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001336 InvalidDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +00001337 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001338
1339 if (New == 0)
1340 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001341
Douglas Gregorcda9c672009-02-16 17:45:42 +00001342 // If this has an identifier and is not an invalid redeclaration,
1343 // add it to the scope stack.
1344 if (Name && !(Redeclaration && InvalidDecl))
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001345 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001346 // If any semantic error occurred, mark the decl as invalid.
1347 if (D.getInvalidType() || InvalidDecl)
1348 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001349
1350 return New;
1351}
1352
Eli Friedman1ca48132009-02-21 00:44:51 +00001353/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
1354/// types into constant array types in certain situations which would otherwise
1355/// be errors (for GCC compatibility).
1356static QualType TryToFixInvalidVariablyModifiedType(QualType T,
1357 ASTContext &Context,
1358 bool &SizeIsNegative) {
1359 // This method tries to turn a variable array into a constant
1360 // array even when the size isn't an ICE. This is necessary
1361 // for compatibility with code that depends on gcc's buggy
1362 // constant expression folding, like struct {char x[(int)(char*)2];}
1363 SizeIsNegative = false;
1364
1365 if (const PointerType* PTy = dyn_cast<PointerType>(T)) {
1366 QualType Pointee = PTy->getPointeeType();
1367 QualType FixedType =
1368 TryToFixInvalidVariablyModifiedType(Pointee, Context, SizeIsNegative);
1369 if (FixedType.isNull()) return FixedType;
Eli Friedman61125c82009-02-21 00:58:02 +00001370 FixedType = Context.getPointerType(FixedType);
1371 FixedType.setCVRQualifiers(T.getCVRQualifiers());
1372 return FixedType;
Eli Friedman1ca48132009-02-21 00:44:51 +00001373 }
1374
1375 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
Eli Friedmanbc592e62009-02-26 03:58:54 +00001376 if (!VLATy)
1377 return QualType();
1378 // FIXME: We should probably handle this case
1379 if (VLATy->getElementType()->isVariablyModifiedType())
1380 return QualType();
Eli Friedman1ca48132009-02-21 00:44:51 +00001381
1382 Expr::EvalResult EvalResult;
1383 if (!VLATy->getSizeExpr() ||
Eli Friedmanbc592e62009-02-26 03:58:54 +00001384 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context) ||
1385 !EvalResult.Val.isInt())
Eli Friedman1ca48132009-02-21 00:44:51 +00001386 return QualType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00001387
Eli Friedman1ca48132009-02-21 00:44:51 +00001388 llvm::APSInt &Res = EvalResult.Val.getInt();
1389 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1390 return Context.getConstantArrayType(VLATy->getElementType(),
1391 Res, ArrayType::Normal, 0);
1392
1393 SizeIsNegative = true;
1394 return QualType();
1395}
1396
Douglas Gregor63935192009-03-02 00:19:53 +00001397/// \brief Register the given locally-scoped external C declaration so
1398/// that it can be found later for redeclarations
1399void
1400Sema::RegisterLocallyScopedExternCDecl(NamedDecl *ND, NamedDecl *PrevDecl,
1401 Scope *S) {
1402 assert(ND->getLexicalDeclContext()->isFunctionOrMethod() &&
1403 "Decl is not a locally-scoped decl!");
1404 // Note that we have a locally-scoped external with this name.
1405 LocallyScopedExternalDecls[ND->getDeclName()] = ND;
1406
1407 if (!PrevDecl)
1408 return;
1409
1410 // If there was a previous declaration of this variable, it may be
1411 // in our identifier chain. Update the identifier chain with the new
1412 // declaration.
1413 if (IdResolver.ReplaceDecl(PrevDecl, ND)) {
1414 // The previous declaration was found on the identifer resolver
1415 // chain, so remove it from its scope.
1416 while (S && !S->isDeclScope(PrevDecl))
1417 S = S->getParent();
1418
1419 if (S)
1420 S->RemoveDecl(PrevDecl);
1421 }
1422}
1423
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001424NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001425Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001426 QualType R, Decl* LastDeclarator,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001427 Decl* PrevDecl, bool& InvalidDecl,
1428 bool &Redeclaration) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001429 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1430 if (D.getCXXScopeSpec().isSet()) {
1431 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1432 << D.getCXXScopeSpec().getRange();
1433 InvalidDecl = true;
1434 // Pretend we didn't see the scope specifier.
1435 DC = 0;
1436 }
1437
Douglas Gregor021c3b32009-03-11 23:00:04 +00001438 if (getLangOptions().CPlusPlus) {
1439 // Check that there are no default arguments (C++ only).
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001440 CheckExtraCXXDefaultArguments(D);
1441
Douglas Gregor021c3b32009-03-11 23:00:04 +00001442 if (D.getDeclSpec().isVirtualSpecified())
1443 Diag(D.getDeclSpec().getVirtualSpecLoc(),
1444 diag::err_virtual_non_function);
1445 }
1446
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001447 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1448 if (!NewTD) return 0;
1449
1450 // Handle attributes prior to checking for duplicates in MergeVarDecl
1451 ProcessDeclAttributes(NewTD, D);
1452 // Merge the decl with the existing one if appropriate. If the decl is
1453 // in an outer scope, it isn't the same thing.
1454 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00001455 Redeclaration = true;
1456 if (MergeTypeDefDecl(NewTD, PrevDecl))
1457 InvalidDecl = true;
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001458 }
1459
1460 if (S->getFnParent() == 0) {
Eli Friedman1ca48132009-02-21 00:44:51 +00001461 QualType T = NewTD->getUnderlyingType();
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001462 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1463 // then it shall have block scope.
Eli Friedman1ca48132009-02-21 00:44:51 +00001464 if (T->isVariablyModifiedType()) {
1465 bool SizeIsNegative;
1466 QualType FixedTy =
1467 TryToFixInvalidVariablyModifiedType(T, Context, SizeIsNegative);
1468 if (!FixedTy.isNull()) {
1469 Diag(D.getIdentifierLoc(), diag::warn_illegal_constant_array_size);
1470 NewTD->setUnderlyingType(FixedTy);
1471 } else {
1472 if (SizeIsNegative)
1473 Diag(D.getIdentifierLoc(), diag::err_typecheck_negative_array_size);
1474 else if (T->isVariableArrayType())
1475 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1476 else
1477 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1478 InvalidDecl = true;
1479 }
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001480 }
1481 }
1482 return NewTD;
1483}
1484
Douglas Gregor8f301052009-02-24 19:23:27 +00001485/// \brief Determines whether the given declaration is an out-of-scope
1486/// previous declaration.
1487///
1488/// This routine should be invoked when name lookup has found a
1489/// previous declaration (PrevDecl) that is not in the scope where a
1490/// new declaration by the same name is being introduced. If the new
1491/// declaration occurs in a local scope, previous declarations with
1492/// linkage may still be considered previous declarations (C99
1493/// 6.2.2p4-5, C++ [basic.link]p6).
1494///
1495/// \param PrevDecl the previous declaration found by name
1496/// lookup
1497///
1498/// \param DC the context in which the new declaration is being
1499/// declared.
1500///
1501/// \returns true if PrevDecl is an out-of-scope previous declaration
1502/// for a new delcaration with the same name.
1503static bool
1504isOutOfScopePreviousDeclaration(NamedDecl *PrevDecl, DeclContext *DC,
1505 ASTContext &Context) {
1506 if (!PrevDecl)
1507 return 0;
1508
1509 // FIXME: PrevDecl could be an OverloadedFunctionDecl, in which
1510 // case we need to check each of the overloaded functions.
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001511 if (!PrevDecl->hasLinkage())
1512 return false;
Douglas Gregor8f301052009-02-24 19:23:27 +00001513
1514 if (Context.getLangOptions().CPlusPlus) {
1515 // C++ [basic.link]p6:
1516 // If there is a visible declaration of an entity with linkage
1517 // having the same name and type, ignoring entities declared
1518 // outside the innermost enclosing namespace scope, the block
1519 // scope declaration declares that same entity and receives the
1520 // linkage of the previous declaration.
1521 DeclContext *OuterContext = DC->getLookupContext();
1522 if (!OuterContext->isFunctionOrMethod())
1523 // This rule only applies to block-scope declarations.
1524 return false;
1525 else {
1526 DeclContext *PrevOuterContext = PrevDecl->getDeclContext();
1527 if (PrevOuterContext->isRecord())
1528 // We found a member function: ignore it.
1529 return false;
1530 else {
1531 // Find the innermost enclosing namespace for the new and
1532 // previous declarations.
1533 while (!OuterContext->isFileContext())
1534 OuterContext = OuterContext->getParent();
1535 while (!PrevOuterContext->isFileContext())
1536 PrevOuterContext = PrevOuterContext->getParent();
1537
1538 // The previous declaration is in a different namespace, so it
1539 // isn't the same function.
1540 if (OuterContext->getPrimaryContext() !=
1541 PrevOuterContext->getPrimaryContext())
1542 return false;
1543 }
1544 }
1545 }
1546
Douglas Gregor8f301052009-02-24 19:23:27 +00001547 return true;
1548}
1549
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001550NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001551Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001552 QualType R, Decl* LastDeclarator,
Douglas Gregor8f301052009-02-24 19:23:27 +00001553 NamedDecl* PrevDecl, bool& InvalidDecl,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001554 bool &Redeclaration) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001555 DeclarationName Name = GetNameForDeclarator(D);
1556
1557 // Check that there are no default arguments (C++ only).
1558 if (getLangOptions().CPlusPlus)
1559 CheckExtraCXXDefaultArguments(D);
1560
1561 if (R.getTypePtr()->isObjCInterfaceType()) {
Steve Naroffccef3712009-02-20 22:59:16 +00001562 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001563 InvalidDecl = true;
1564 }
1565
1566 VarDecl *NewVD;
1567 VarDecl::StorageClass SC;
1568 switch (D.getDeclSpec().getStorageClassSpec()) {
1569 default: assert(0 && "Unknown storage class!");
1570 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1571 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1572 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1573 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1574 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1575 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1576 case DeclSpec::SCS_mutable:
1577 // mutable can only appear on non-static class members, so it's always
1578 // an error here
1579 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1580 InvalidDecl = true;
1581 SC = VarDecl::None;
1582 break;
1583 }
1584
1585 IdentifierInfo *II = Name.getAsIdentifierInfo();
1586 if (!II) {
1587 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1588 << Name.getAsString();
1589 return 0;
1590 }
1591
Douglas Gregor021c3b32009-03-11 23:00:04 +00001592 if (D.getDeclSpec().isVirtualSpecified())
1593 Diag(D.getDeclSpec().getVirtualSpecLoc(),
1594 diag::err_virtual_non_function);
1595
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001596 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1597 if (!DC->isRecord() && S->getFnParent() == 0) {
1598 // C99 6.9p2: The storage-class specifiers auto and register shall not
1599 // appear in the declaration specifiers in an external declaration.
1600 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1601 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1602 InvalidDecl = true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001603 }
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001604 }
Douglas Gregor656de632009-03-11 23:52:16 +00001605 if (DC->isRecord() && !CurContext->isRecord()) {
1606 // This is an out-of-line definition of a static data member.
1607 if (SC == VarDecl::Static) {
1608 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1609 diag::err_static_out_of_line)
1610 << CodeModificationHint::CreateRemoval(
1611 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
1612 } else if (SC == VarDecl::None)
1613 SC = VarDecl::Static;
1614 }
Douglas Gregor2d2e9cf2009-03-11 20:22:50 +00001615 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1616 II, R, SC,
1617 // FIXME: Move to DeclGroup...
1618 D.getDeclSpec().getSourceRange().getBegin());
1619 NewVD->setThreadSpecified(ThreadSpecified);
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001620 NewVD->setNextDeclarator(LastDeclarator);
1621
Douglas Gregor656de632009-03-11 23:52:16 +00001622 // Set the lexical context. If the declarator has a C++ scope specifier, the
1623 // lexical context will be different from the semantic context.
1624 NewVD->setLexicalDeclContext(CurContext);
1625
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001626 // Handle attributes prior to checking for duplicates in MergeVarDecl
1627 ProcessDeclAttributes(NewVD, D);
1628
1629 // Handle GNU asm-label extension (encoded as an attribute).
1630 if (Expr *E = (Expr*) D.getAsmLabel()) {
1631 // The parser guarantees this is a string.
1632 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0b2b6e12009-03-04 06:34:08 +00001633 NewVD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
1634 SE->getByteLength())));
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001635 }
1636
1637 // Emit an error if an address space was applied to decl with local storage.
1638 // This includes arrays of objects with address space qualifiers, but not
1639 // automatic variables that point to other address spaces.
1640 // ISO/IEC TR 18037 S5.1.2
1641 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1642 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1643 InvalidDecl = true;
1644 }
Fariborz Jahanian7b5b3172009-02-21 19:44:02 +00001645
1646 if (NewVD->hasLocalStorage() && NewVD->getType().isObjCGCWeak()) {
1647 Diag(D.getIdentifierLoc(), diag::warn_attribute_weak_on_local);
1648 }
1649
Anders Carlsson1a7acfa2009-02-28 21:56:50 +00001650 bool isIllegalVLA = R->isVariableArrayType() && NewVD->hasGlobalStorage();
1651 bool isIllegalVM = R->isVariablyModifiedType() && NewVD->hasLinkage();
1652 if (isIllegalVLA || isIllegalVM) {
1653 bool SizeIsNegative;
1654 QualType FixedTy =
1655 TryToFixInvalidVariablyModifiedType(R, Context, SizeIsNegative);
1656 if (!FixedTy.isNull()) {
1657 Diag(NewVD->getLocation(), diag::warn_illegal_constant_array_size);
1658 NewVD->setType(FixedTy);
1659 } else if (R->isVariableArrayType()) {
1660 NewVD->setInvalidDecl();
1661
1662 const VariableArrayType *VAT = Context.getAsVariableArrayType(R);
1663 // FIXME: This won't give the correct result for
1664 // int a[10][n];
1665 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
1666
1667 if (NewVD->isFileVarDecl())
1668 Diag(NewVD->getLocation(), diag::err_vla_decl_in_file_scope)
1669 << SizeRange;
1670 else if (NewVD->getStorageClass() == VarDecl::Static)
1671 Diag(NewVD->getLocation(), diag::err_vla_decl_has_static_storage)
1672 << SizeRange;
1673 else
1674 Diag(NewVD->getLocation(), diag::err_vla_decl_has_extern_linkage)
1675 << SizeRange;
1676 } else {
1677 InvalidDecl = true;
1678
1679 if (NewVD->isFileVarDecl())
1680 Diag(NewVD->getLocation(), diag::err_vm_decl_in_file_scope);
1681 else
1682 Diag(NewVD->getLocation(), diag::err_vm_decl_has_extern_linkage);
1683 }
1684 }
1685
Douglas Gregor8f301052009-02-24 19:23:27 +00001686 // If name lookup finds a previous declaration that is not in the
1687 // same scope as the new declaration, this may still be an
1688 // acceptable redeclaration.
1689 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00001690 !(NewVD->hasLinkage() &&
Douglas Gregor8f301052009-02-24 19:23:27 +00001691 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
1692 PrevDecl = 0;
1693
Douglas Gregor63935192009-03-02 00:19:53 +00001694 if (!PrevDecl && NewVD->isExternC(Context)) {
1695 // Since we did not find anything by this name and we're declaring
1696 // an extern "C" variable, look for a non-visible extern "C"
1697 // declaration with the same name.
1698 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
1699 = LocallyScopedExternalDecls.find(Name);
1700 if (Pos != LocallyScopedExternalDecls.end())
1701 PrevDecl = Pos->second;
1702 }
1703
Douglas Gregor8f301052009-02-24 19:23:27 +00001704 // Merge the decl with the existing one if appropriate.
1705 if (PrevDecl) {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001706 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1707 // The user tried to define a non-static data member
1708 // out-of-line (C++ [dcl.meaning]p1).
1709 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1710 << D.getCXXScopeSpec().getRange();
1711 NewVD->Destroy(Context);
1712 return 0;
1713 }
1714
Douglas Gregorcda9c672009-02-16 17:45:42 +00001715 Redeclaration = true;
1716 if (MergeVarDecl(NewVD, PrevDecl))
1717 InvalidDecl = true;
Douglas Gregor656de632009-03-11 23:52:16 +00001718 } else if (D.getCXXScopeSpec().isSet()) {
1719 // No previous declaration in the qualifying scope.
1720 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1721 << Name << D.getCXXScopeSpec().getRange();
1722 InvalidDecl = true;
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001723 }
Douglas Gregor8f301052009-02-24 19:23:27 +00001724
Douglas Gregora03aca82009-03-10 21:58:27 +00001725 if (!InvalidDecl && R->isVoidType() && !NewVD->hasExternalStorage()) {
1726 Diag(NewVD->getLocation(), diag::err_typecheck_decl_incomplete_type)
1727 << R;
1728 InvalidDecl = true;
1729 }
1730
1731
Douglas Gregor63935192009-03-02 00:19:53 +00001732 // If this is a locally-scoped extern C variable, update the map of
1733 // such variables.
1734 if (CurContext->isFunctionOrMethod() && NewVD->isExternC(Context) &&
1735 !InvalidDecl)
1736 RegisterLocallyScopedExternCDecl(NewVD, PrevDecl, S);
Douglas Gregor8f301052009-02-24 19:23:27 +00001737
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001738 return NewVD;
1739}
1740
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001741NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001742Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001743 QualType R, Decl *LastDeclarator,
Douglas Gregor04495c82009-02-24 01:23:02 +00001744 NamedDecl* PrevDecl, bool IsFunctionDefinition,
Douglas Gregorcda9c672009-02-16 17:45:42 +00001745 bool& InvalidDecl, bool &Redeclaration) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001746 assert(R.getTypePtr()->isFunctionType());
1747
1748 DeclarationName Name = GetNameForDeclarator(D);
1749 FunctionDecl::StorageClass SC = FunctionDecl::None;
1750 switch (D.getDeclSpec().getStorageClassSpec()) {
1751 default: assert(0 && "Unknown storage class!");
1752 case DeclSpec::SCS_auto:
1753 case DeclSpec::SCS_register:
1754 case DeclSpec::SCS_mutable:
Douglas Gregor04495c82009-02-24 01:23:02 +00001755 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1756 diag::err_typecheck_sclass_func);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001757 InvalidDecl = true;
1758 break;
1759 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1760 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
Douglas Gregor04495c82009-02-24 01:23:02 +00001761 case DeclSpec::SCS_static: {
Douglas Gregor656de632009-03-11 23:52:16 +00001762 if (CurContext->getLookupContext()->isFunctionOrMethod()) {
Douglas Gregor04495c82009-02-24 01:23:02 +00001763 // C99 6.7.1p5:
1764 // The declaration of an identifier for a function that has
1765 // block scope shall have no explicit storage-class specifier
1766 // other than extern
1767 // See also (C++ [dcl.stc]p4).
1768 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1769 diag::err_static_block_func);
1770 SC = FunctionDecl::None;
1771 } else
1772 SC = FunctionDecl::Static;
1773 break;
1774 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001775 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1776 }
1777
1778 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor021c3b32009-03-11 23:00:04 +00001779 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001780 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1781
Douglas Gregor021c3b32009-03-11 23:00:04 +00001782 bool isVirtualOkay = false;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001783 FunctionDecl *NewFD;
1784 if (D.getKind() == Declarator::DK_Constructor) {
1785 // This is a C++ constructor declaration.
1786 assert(DC->isRecord() &&
1787 "Constructors can only be declared in a member context");
1788
1789 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1790
1791 // Create the new declaration
1792 NewFD = CXXConstructorDecl::Create(Context,
1793 cast<CXXRecordDecl>(DC),
1794 D.getIdentifierLoc(), Name, R,
1795 isExplicit, isInline,
1796 /*isImplicitlyDeclared=*/false);
1797
1798 if (InvalidDecl)
1799 NewFD->setInvalidDecl();
1800 } else if (D.getKind() == Declarator::DK_Destructor) {
1801 // This is a C++ destructor declaration.
1802 if (DC->isRecord()) {
1803 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1804
1805 NewFD = CXXDestructorDecl::Create(Context,
1806 cast<CXXRecordDecl>(DC),
1807 D.getIdentifierLoc(), Name, R,
1808 isInline,
1809 /*isImplicitlyDeclared=*/false);
1810
1811 if (InvalidDecl)
1812 NewFD->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00001813
1814 isVirtualOkay = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001815 } else {
1816 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1817
1818 // Create a FunctionDecl to satisfy the function definition parsing
1819 // code path.
1820 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001821 Name, R, SC, isInline,
Douglas Gregor2224f842009-02-25 16:33:18 +00001822 /*hasPrototype=*/true,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001823 // FIXME: Move to DeclGroup...
1824 D.getDeclSpec().getSourceRange().getBegin());
1825 InvalidDecl = true;
1826 NewFD->setInvalidDecl();
1827 }
1828 } else if (D.getKind() == Declarator::DK_Conversion) {
1829 if (!DC->isRecord()) {
1830 Diag(D.getIdentifierLoc(),
1831 diag::err_conv_function_not_member);
1832 return 0;
1833 } else {
1834 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1835
1836 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1837 D.getIdentifierLoc(), Name, R,
1838 isInline, isExplicit);
1839
1840 if (InvalidDecl)
1841 NewFD->setInvalidDecl();
Douglas Gregor021c3b32009-03-11 23:00:04 +00001842
1843 isVirtualOkay = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001844 }
1845 } else if (DC->isRecord()) {
1846 // This is a C++ method declaration.
1847 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1848 D.getIdentifierLoc(), Name, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001849 (SC == FunctionDecl::Static), isInline);
Douglas Gregor021c3b32009-03-11 23:00:04 +00001850
1851 isVirtualOkay = (SC != FunctionDecl::Static);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001852 } else {
Chris Lattner0d48bf92009-03-17 23:17:04 +00001853 bool HasPrototype =
1854 getLangOptions().CPlusPlus ||
1855 (D.getNumTypeObjects() && D.getTypeObject(0).Fun.hasPrototype);
1856
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001857 NewFD = FunctionDecl::Create(Context, DC,
1858 D.getIdentifierLoc(),
Chris Lattner0d48bf92009-03-17 23:17:04 +00001859 Name, R, SC, isInline, HasPrototype,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001860 // FIXME: Move to DeclGroup...
1861 D.getDeclSpec().getSourceRange().getBegin());
1862 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001863 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001864
1865 // Set the lexical context. If the declarator has a C++
1866 // scope specifier, the lexical context will be different
1867 // from the semantic context.
1868 NewFD->setLexicalDeclContext(CurContext);
1869
Douglas Gregor021c3b32009-03-11 23:00:04 +00001870 // C++ [dcl.fct.spec]p5:
1871 // The virtual specifier shall only be used in declarations of
1872 // nonstatic class member functions that appear within a
1873 // member-specification of a class declaration; see 10.3.
1874 //
1875 // FIXME: Checking the 'virtual' specifier is not sufficient. A
1876 // function is also virtual if it overrides an already virtual
1877 // function. This is important to do here because it's part of the
1878 // declaration.
1879 if (isVirtual && !InvalidDecl) {
1880 if (!isVirtualOkay) {
1881 Diag(D.getDeclSpec().getVirtualSpecLoc(),
1882 diag::err_virtual_non_function);
1883 } else if (!CurContext->isRecord()) {
1884 // 'virtual' was specified outside of the class.
1885 Diag(D.getDeclSpec().getVirtualSpecLoc(), diag::err_virtual_out_of_class)
1886 << CodeModificationHint::CreateRemoval(
1887 SourceRange(D.getDeclSpec().getVirtualSpecLoc()));
1888 } else {
1889 // Okay: Add virtual to the method.
1890 cast<CXXMethodDecl>(NewFD)->setVirtual();
1891 CXXRecordDecl *CurClass = cast<CXXRecordDecl>(DC);
1892 CurClass->setAggregate(false);
1893 CurClass->setPOD(false);
1894 CurClass->setPolymorphic(true);
1895 }
1896 }
1897
Douglas Gregor656de632009-03-11 23:52:16 +00001898 if (SC == FunctionDecl::Static && isa<CXXMethodDecl>(NewFD) &&
1899 !CurContext->isRecord()) {
1900 // C++ [class.static]p1:
1901 // A data or function member of a class may be declared static
1902 // in a class definition, in which case it is a static member of
1903 // the class.
1904
1905 // Complain about the 'static' specifier if it's on an out-of-line
1906 // member function definition.
1907 Diag(D.getDeclSpec().getStorageClassSpecLoc(),
1908 diag::err_static_out_of_line)
1909 << CodeModificationHint::CreateRemoval(
1910 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()));
1911 }
1912
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001913 // Handle GNU asm-label extension (encoded as an attribute).
1914 if (Expr *E = (Expr*) D.getAsmLabel()) {
1915 // The parser guarantees this is a string.
1916 StringLiteral *SE = cast<StringLiteral>(E);
Chris Lattner0b2b6e12009-03-04 06:34:08 +00001917 NewFD->addAttr(::new (Context) AsmLabelAttr(std::string(SE->getStrData(),
1918 SE->getByteLength())));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001919 }
1920
1921 // Copy the parameter declarations from the declarator D to
1922 // the function declaration NewFD, if they are available.
1923 if (D.getNumTypeObjects() > 0) {
1924 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1925
1926 // Create Decl objects for each parameter, adding them to the
1927 // FunctionDecl.
1928 llvm::SmallVector<ParmVarDecl*, 16> Params;
1929
1930 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1931 // function that takes no arguments, not a function that takes a
1932 // single void argument.
1933 // We let through "const void" here because Sema::GetTypeForDeclarator
1934 // already checks for that case.
1935 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1936 FTI.ArgInfo[0].Param &&
1937 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1938 // empty arg list, don't push any params.
1939 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1940
1941 // In C++, the empty parameter-type-list must be spelled "void"; a
1942 // typedef of void is not permitted.
1943 if (getLangOptions().CPlusPlus &&
1944 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1945 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1946 }
1947 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1948 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1949 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1950 }
1951
1952 NewFD->setParams(Context, &Params[0], Params.size());
1953 } else if (R->getAsTypedefType()) {
1954 // When we're declaring a function with a typedef, as in the
1955 // following example, we'll need to synthesize (unnamed)
1956 // parameters for use in the declaration.
1957 //
1958 // @code
1959 // typedef void fn(int);
1960 // fn f;
1961 // @endcode
Douglas Gregor72564e72009-02-26 23:50:07 +00001962 const FunctionProtoType *FT = R->getAsFunctionProtoType();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001963 if (!FT) {
1964 // This is a typedef of a function with no prototype, so we
1965 // don't need to do anything.
1966 } else if ((FT->getNumArgs() == 0) ||
1967 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1968 FT->getArgType(0)->isVoidType())) {
1969 // This is a zero-argument function. We don't need to do anything.
1970 } else {
1971 // Synthesize a parameter for each argument type.
1972 llvm::SmallVector<ParmVarDecl*, 16> Params;
Douglas Gregor72564e72009-02-26 23:50:07 +00001973 for (FunctionProtoType::arg_type_iterator ArgType = FT->arg_type_begin();
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001974 ArgType != FT->arg_type_end(); ++ArgType) {
Douglas Gregor450da982009-02-16 20:58:07 +00001975 ParmVarDecl *Param = ParmVarDecl::Create(Context, DC,
1976 SourceLocation(), 0,
1977 *ArgType, VarDecl::None,
1978 0);
1979 Param->setImplicit();
1980 Params.push_back(Param);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001981 }
1982
1983 NewFD->setParams(Context, &Params[0], Params.size());
1984 }
1985 }
1986
1987 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1988 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1989 else if (isa<CXXDestructorDecl>(NewFD)) {
1990 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1991 Record->setUserDeclaredDestructor(true);
1992 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1993 // user-defined destructor.
1994 Record->setPOD(false);
1995 } else if (CXXConversionDecl *Conversion =
1996 dyn_cast<CXXConversionDecl>(NewFD))
1997 ActOnConversionDeclarator(Conversion);
1998
1999 // Extra checking for C++ overloaded operators (C++ [over.oper]).
2000 if (NewFD->isOverloadedOperator() &&
2001 CheckOverloadedOperatorDeclaration(NewFD))
2002 NewFD->setInvalidDecl();
2003
Douglas Gregor8f301052009-02-24 19:23:27 +00002004 // If name lookup finds a previous declaration that is not in the
2005 // same scope as the new declaration, this may still be an
2006 // acceptable redeclaration.
2007 if (PrevDecl && !isDeclInScope(PrevDecl, DC, S) &&
Douglas Gregord6f7e9d2009-02-24 20:03:32 +00002008 !(NewFD->hasLinkage() &&
2009 isOutOfScopePreviousDeclaration(PrevDecl, DC, Context)))
Douglas Gregor8f301052009-02-24 19:23:27 +00002010 PrevDecl = 0;
Douglas Gregor04495c82009-02-24 01:23:02 +00002011
Douglas Gregor63935192009-03-02 00:19:53 +00002012 if (!PrevDecl && NewFD->isExternC(Context)) {
2013 // Since we did not find anything by this name and we're declaring
2014 // an extern "C" function, look for a non-visible extern "C"
2015 // declaration with the same name.
2016 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2017 = LocallyScopedExternalDecls.find(Name);
2018 if (Pos != LocallyScopedExternalDecls.end())
2019 PrevDecl = Pos->second;
2020 }
2021
Douglas Gregor04495c82009-02-24 01:23:02 +00002022 // Merge or overload the declaration with an existing declaration of
2023 // the same name, if appropriate.
Douglas Gregorf9201e02009-02-11 23:02:49 +00002024 bool OverloadableAttrRequired = false;
Douglas Gregor04495c82009-02-24 01:23:02 +00002025 if (PrevDecl) {
Douglas Gregorf9201e02009-02-11 23:02:49 +00002026 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002027 // a declaration that requires merging. If it's an overload,
2028 // there's no more work to do here; we'll just add the new
2029 // function to the scope.
2030 OverloadedFunctionDecl::function_iterator MatchedDecl;
Douglas Gregorae170942009-02-13 00:26:38 +00002031
2032 if (!getLangOptions().CPlusPlus &&
Douglas Gregorc6666f82009-02-18 06:34:51 +00002033 AllowOverloadingOfFunction(PrevDecl, Context)) {
Douglas Gregorae170942009-02-13 00:26:38 +00002034 OverloadableAttrRequired = true;
2035
Douglas Gregorc6666f82009-02-18 06:34:51 +00002036 // Functions marked "overloadable" must have a prototype (that
2037 // we can't get through declaration merging).
Douglas Gregor72564e72009-02-26 23:50:07 +00002038 if (!R->getAsFunctionProtoType()) {
Douglas Gregorc6666f82009-02-18 06:34:51 +00002039 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_no_prototype)
2040 << NewFD;
2041 InvalidDecl = true;
2042 Redeclaration = true;
2043
2044 // Turn this into a variadic function with no parameters.
2045 R = Context.getFunctionType(R->getAsFunctionType()->getResultType(),
2046 0, 0, true, 0);
2047 NewFD->setType(R);
2048 }
2049 }
2050
2051 if (PrevDecl &&
2052 (!AllowOverloadingOfFunction(PrevDecl, Context) ||
2053 !IsOverload(NewFD, PrevDecl, MatchedDecl))) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002054 Redeclaration = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002055 Decl *OldDecl = PrevDecl;
2056
2057 // If PrevDecl was an overloaded function, extract the
2058 // FunctionDecl that matched.
2059 if (isa<OverloadedFunctionDecl>(PrevDecl))
2060 OldDecl = *MatchedDecl;
2061
2062 // NewFD and PrevDecl represent declarations that need to be
2063 // merged.
Douglas Gregorcda9c672009-02-16 17:45:42 +00002064 if (MergeFunctionDecl(NewFD, OldDecl))
2065 InvalidDecl = true;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002066
Douglas Gregorcda9c672009-02-16 17:45:42 +00002067 if (!InvalidDecl) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002068 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
2069
2070 // An out-of-line member function declaration must also be a
2071 // definition (C++ [dcl.meaning]p1).
2072 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
2073 !InvalidDecl) {
2074 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2075 << D.getCXXScopeSpec().getRange();
2076 NewFD->setInvalidDecl();
2077 }
2078 }
2079 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002080 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002081
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002082 if (D.getCXXScopeSpec().isSet() &&
2083 (!PrevDecl || !Redeclaration)) {
2084 // The user tried to provide an out-of-line definition for a
2085 // function that is a member of a class or namespace, but there
2086 // was no such member function declared (C++ [class.mfct]p2,
2087 // C++ [namespace.memdef]p2). For example:
2088 //
2089 // class X {
2090 // void f() const;
2091 // };
2092 //
2093 // void X::f() { } // ill-formed
2094 //
2095 // Complain about this problem, and attempt to suggest close
2096 // matches (e.g., those that differ only in cv-qualifiers and
2097 // whether the parameter types are references).
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002098 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregor4b99bae2009-02-06 22:58:38 +00002099 << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002100 InvalidDecl = true;
2101
2102 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
2103 true);
2104 assert(!Prev.isAmbiguous() &&
2105 "Cannot have an ambiguity in previous-declaration lookup");
2106 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
2107 Func != FuncEnd; ++Func) {
2108 if (isa<FunctionDecl>(*Func) &&
2109 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
2110 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002111 }
Douglas Gregor4ce205f2009-02-06 17:46:57 +00002112
2113 PrevDecl = 0;
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002114 }
Douglas Gregord8635172009-02-02 21:35:47 +00002115
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002116 // Handle attributes. We need to have merged decls when handling attributes
2117 // (for example to check for conflicts, etc).
2118 ProcessDeclAttributes(NewFD, D);
Douglas Gregor3c385e52009-02-14 18:57:46 +00002119 AddKnownFunctionAttributes(NewFD);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002120
Douglas Gregorf9201e02009-02-11 23:02:49 +00002121 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
2122 // If a function name is overloadable in C, then every function
2123 // with that name must be marked "overloadable".
2124 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
Douglas Gregorae170942009-02-13 00:26:38 +00002125 << Redeclaration << NewFD;
Douglas Gregorf9201e02009-02-11 23:02:49 +00002126 if (PrevDecl)
2127 Diag(PrevDecl->getLocation(),
2128 diag::note_attribute_overloadable_prev_overload);
Chris Lattner0b2b6e12009-03-04 06:34:08 +00002129 NewFD->addAttr(::new (Context) OverloadableAttr());
Douglas Gregorf9201e02009-02-11 23:02:49 +00002130 }
2131
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002132 if (getLangOptions().CPlusPlus) {
Sebastian Redl00d50742009-02-08 14:56:26 +00002133 // In C++, check default arguments now that we have merged decls. Unless
2134 // the lexical context is the class, because in this case this is done
2135 // during delayed parsing anyway.
2136 if (!CurContext->isRecord())
2137 CheckCXXDefaultArguments(NewFD);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002138
2139 // An out-of-line member function declaration must also be a
2140 // definition (C++ [dcl.meaning]p1).
2141 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
2142 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
2143 << D.getCXXScopeSpec().getRange();
2144 InvalidDecl = true;
2145 }
2146 }
Douglas Gregor25d944a2009-02-24 04:26:15 +00002147
Douglas Gregor63935192009-03-02 00:19:53 +00002148 // If this is a locally-scoped extern C function, update the
2149 // map of such names.
2150 if (CurContext->isFunctionOrMethod() && NewFD->isExternC(Context)
2151 && !InvalidDecl)
2152 RegisterLocallyScopedExternCDecl(NewFD, PrevDecl, S);
Douglas Gregor25d944a2009-02-24 04:26:15 +00002153
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00002154 return NewFD;
2155}
2156
Eli Friedmanc594b322008-05-20 13:48:25 +00002157bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Eli Friedman3b8a36a2009-02-27 04:17:12 +00002158 // FIXME: Need strict checking. In C89, we need to check for
2159 // any assignment, increment, decrement, function-calls, or
2160 // commas outside of a sizeof. In C99, it's the same list,
2161 // except that the aforementioned are allowed in unevaluated
2162 // expressions. Everything else falls under the
2163 // "may accept other forms of constant expressions" exception.
2164 // (We never end up here for C++, so the constant expression
2165 // rules there don't matter.)
Chris Lattner111c2ee2009-02-24 21:54:33 +00002166 if (Init->isConstantInitializer(Context))
Eli Friedman578a9722009-02-22 06:45:27 +00002167 return false;
Eli Friedman21298282009-02-26 04:47:58 +00002168 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
2169 << Init->getSourceRange();
Eli Friedmanc594b322008-05-20 13:48:25 +00002170 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002171}
2172
Sebastian Redl798d1192008-12-13 16:23:55 +00002173void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002174 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2175}
2176
2177/// AddInitializerToDecl - Adds the initializer Init to the
2178/// declaration dcl. If DirectInit is true, this is C++ direct
2179/// initialization rather than copy initialization.
2180void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002181 Decl *RealDecl = static_cast<Decl *>(dcl);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002182 // If there is no declaration, there was an error parsing it. Just ignore
2183 // the initializer.
Eli Friedman3b8a36a2009-02-27 04:17:12 +00002184 if (RealDecl == 0)
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002185 return;
Steve Naroffbb204692007-09-12 14:07:44 +00002186
Douglas Gregor021c3b32009-03-11 23:00:04 +00002187 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(RealDecl)) {
2188 // With declarators parsed the way they are, the parser cannot
2189 // distinguish between a normal initializer and a pure-specifier.
2190 // Thus this grotesque test.
2191 IntegerLiteral *IL;
2192 Expr *Init = static_cast<Expr *>(init.get());
2193 if ((IL = dyn_cast<IntegerLiteral>(Init)) && IL->getValue() == 0 &&
2194 Context.getCanonicalType(IL->getType()) == Context.IntTy) {
2195 if (Method->isVirtual())
2196 Method->setPure();
2197 else {
2198 Diag(Method->getLocation(), diag::err_non_virtual_pure)
2199 << Method->getDeclName() << Init->getSourceRange();
2200 Method->setInvalidDecl();
2201 }
2202 } else {
2203 Diag(Method->getLocation(), diag::err_member_function_initialization)
2204 << Method->getDeclName() << Init->getSourceRange();
2205 Method->setInvalidDecl();
2206 }
2207 return;
2208 }
2209
Steve Naroff410e3e22007-09-12 20:13:48 +00002210 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2211 if (!VDecl) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00002212 if (getLangOptions().CPlusPlus &&
2213 RealDecl->getLexicalDeclContext()->isRecord() &&
2214 isa<NamedDecl>(RealDecl))
2215 Diag(RealDecl->getLocation(), diag::err_member_initialization)
2216 << cast<NamedDecl>(RealDecl)->getDeclName();
2217 else
2218 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002219 RealDecl->setInvalidDecl();
2220 return;
Eli Friedman3b8a36a2009-02-27 04:17:12 +00002221 }
2222
Douglas Gregor275a3692009-03-10 23:43:53 +00002223 const VarDecl *Def = 0;
2224 if (VDecl->getDefinition(Def)) {
2225 Diag(VDecl->getLocation(), diag::err_redefinition)
2226 << VDecl->getDeclName();
2227 Diag(Def->getLocation(), diag::note_previous_definition);
2228 VDecl->setInvalidDecl();
2229 return;
2230 }
2231
Eli Friedman3b8a36a2009-02-27 04:17:12 +00002232 // Take ownership of the expression, now that we're sure we have somewhere
2233 // to put it.
2234 Expr *Init = static_cast<Expr *>(init.release());
2235 assert(Init && "missing initializer");
2236
Steve Naroffbb204692007-09-12 14:07:44 +00002237 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002238 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002239 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002240 if (VDecl->isBlockVarDecl()) {
2241 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002242 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002243 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002244 VDecl->setInvalidDecl();
2245 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002246 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002247 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002248 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002249
2250 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00002251 // Don't check invalid declarations to avoid emitting useless diagnostics.
2252 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002253 if (SC == VarDecl::Static) // C99 6.7.8p4.
2254 CheckForConstantInitializer(Init, DclT);
2255 }
Steve Naroffbb204692007-09-12 14:07:44 +00002256 }
Douglas Gregor021c3b32009-03-11 23:00:04 +00002257 } else if (VDecl->isStaticDataMember() &&
2258 VDecl->getLexicalDeclContext()->isRecord()) {
2259 // This is an in-class initialization for a static data member, e.g.,
2260 //
2261 // struct S {
2262 // static const int value = 17;
2263 // };
2264
2265 // Attach the initializer
2266 VDecl->setInit(Init);
2267
2268 // C++ [class.mem]p4:
2269 // A member-declarator can contain a constant-initializer only
2270 // if it declares a static member (9.4) of const integral or
2271 // const enumeration type, see 9.4.2.
2272 QualType T = VDecl->getType();
2273 if (!T->isDependentType() &&
2274 (!Context.getCanonicalType(T).isConstQualified() ||
2275 !T->isIntegralType())) {
2276 Diag(VDecl->getLocation(), diag::err_member_initialization)
2277 << VDecl->getDeclName() << Init->getSourceRange();
2278 VDecl->setInvalidDecl();
2279 } else {
2280 // C++ [class.static.data]p4:
2281 // If a static data member is of const integral or const
2282 // enumeration type, its declaration in the class definition
2283 // can specify a constant-initializer which shall be an
2284 // integral constant expression (5.19).
2285 if (!Init->isTypeDependent() &&
2286 !Init->getType()->isIntegralType()) {
2287 // We have a non-dependent, non-integral or enumeration type.
2288 Diag(Init->getSourceRange().getBegin(),
2289 diag::err_in_class_initializer_non_integral_type)
2290 << Init->getType() << Init->getSourceRange();
2291 VDecl->setInvalidDecl();
2292 } else if (!Init->isTypeDependent() && !Init->isValueDependent()) {
2293 // Check whether the expression is a constant expression.
2294 llvm::APSInt Value;
2295 SourceLocation Loc;
2296 if (!Init->isIntegerConstantExpr(Value, Context, &Loc)) {
2297 Diag(Loc, diag::err_in_class_initializer_non_constant)
2298 << Init->getSourceRange();
2299 VDecl->setInvalidDecl();
2300 }
2301 }
2302 }
Steve Naroff248a7532008-04-15 22:42:06 +00002303 } else if (VDecl->isFileVarDecl()) {
2304 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002305 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002306 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002307 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002308 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002309 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002310
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002311 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
Eli Friedmanda153232009-02-20 01:34:21 +00002312 // Don't check invalid declarations to avoid emitting useless diagnostics.
2313 if (!getLangOptions().CPlusPlus && !VDecl->isInvalidDecl()) {
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002314 // C99 6.7.8p4. All file scoped initializers need to be constant.
2315 CheckForConstantInitializer(Init, DclT);
2316 }
Steve Naroffbb204692007-09-12 14:07:44 +00002317 }
2318 // If the type changed, it means we had an incomplete type that was
2319 // completed by the initializer. For example:
2320 // int ary[] = { 1, 3, 5 };
2321 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002322 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002323 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002324 Init->setType(DclT);
2325 }
Steve Naroffbb204692007-09-12 14:07:44 +00002326
2327 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002328 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002329 return;
2330}
2331
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002332void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2333 Decl *RealDecl = static_cast<Decl *>(dcl);
2334
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002335 // If there is no declaration, there was an error parsing it. Just ignore it.
2336 if (RealDecl == 0)
2337 return;
2338
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002339 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2340 QualType Type = Var->getType();
2341 // C++ [dcl.init.ref]p3:
2342 // The initializer can be omitted for a reference only in a
2343 // parameter declaration (8.3.5), in the declaration of a
2344 // function return type, in the declaration of a class member
2345 // within its class declaration (9.2), and where the extern
2346 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002347 if (Type->isReferenceType() &&
2348 Var->getStorageClass() != VarDecl::Extern &&
2349 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002350 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002351 << Var->getDeclName()
2352 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002353 Var->setInvalidDecl();
2354 return;
2355 }
2356
2357 // C++ [dcl.init]p9:
2358 //
2359 // If no initializer is specified for an object, and the object
2360 // is of (possibly cv-qualified) non-POD class type (or array
2361 // thereof), the object shall be default-initialized; if the
2362 // object is of const-qualified type, the underlying class type
2363 // shall have a user-declared default constructor.
2364 if (getLangOptions().CPlusPlus) {
2365 QualType InitType = Type;
2366 if (const ArrayType *Array = Context.getAsArrayType(Type))
2367 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002368 if (Var->getStorageClass() != VarDecl::Extern &&
2369 Var->getStorageClass() != VarDecl::PrivateExtern &&
2370 InitType->isRecordType()) {
Douglas Gregor2943aed2009-03-03 04:44:36 +00002371 const CXXConstructorDecl *Constructor = 0;
Douglas Gregor86447ec2009-03-09 16:13:40 +00002372 if (!RequireCompleteType(Var->getLocation(), InitType,
Douglas Gregor2943aed2009-03-03 04:44:36 +00002373 diag::err_invalid_incomplete_type_use))
2374 Constructor
2375 = PerformInitializationByConstructor(InitType, 0, 0,
2376 Var->getLocation(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002377 SourceRange(Var->getLocation(),
2378 Var->getLocation()),
Douglas Gregor2943aed2009-03-03 04:44:36 +00002379 Var->getDeclName(),
2380 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002381 if (!Constructor)
2382 Var->setInvalidDecl();
2383 }
2384 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002385
Douglas Gregor818ce482008-10-29 13:50:18 +00002386#if 0
2387 // FIXME: Temporarily disabled because we are not properly parsing
2388 // linkage specifications on declarations, e.g.,
2389 //
2390 // extern "C" const CGPoint CGPointerZero;
2391 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002392 // C++ [dcl.init]p9:
2393 //
2394 // If no initializer is specified for an object, and the
2395 // object is of (possibly cv-qualified) non-POD class type (or
2396 // array thereof), the object shall be default-initialized; if
2397 // the object is of const-qualified type, the underlying class
2398 // type shall have a user-declared default
2399 // constructor. Otherwise, if no initializer is specified for
2400 // an object, the object and its subobjects, if any, have an
2401 // indeterminate initial value; if the object or any of its
2402 // subobjects are of const-qualified type, the program is
2403 // ill-formed.
2404 //
2405 // This isn't technically an error in C, so we don't diagnose it.
2406 //
2407 // FIXME: Actually perform the POD/user-defined default
2408 // constructor check.
2409 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002410 Context.getCanonicalType(Type).isConstQualified() &&
2411 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002412 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2413 << Var->getName()
2414 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002415#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002416 }
2417}
2418
Reid Spencer5f016e22007-07-11 17:01:13 +00002419/// The declarators are chained together backwards, reverse the list.
2420Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2421 // Often we have single declarators, handle them quickly.
Argyrios Kyrtzidisd311f372009-02-17 20:23:54 +00002422 Decl *Group = static_cast<Decl*>(group);
2423 if (Group == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002424 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002425
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002426 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002427 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002428 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002429 else { // reverse the list.
2430 while (Group) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002431 Decl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002432 Group->setNextDeclarator(NewGroup);
2433 NewGroup = Group;
2434 Group = Next;
2435 }
2436 }
2437 // Perform semantic analysis that depends on having fully processed both
2438 // the declarator and initializer.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002439 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002440 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2441 if (!IDecl)
2442 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002443 QualType T = IDecl->getType();
Eli Friedmanbc592e62009-02-26 03:58:54 +00002444
Steve Naroffbb204692007-09-12 14:07:44 +00002445 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2446 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002447 if (IDecl->isBlockVarDecl() &&
2448 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002449 if (!IDecl->isInvalidDecl() &&
Douglas Gregor86447ec2009-03-09 16:13:40 +00002450 RequireCompleteType(IDecl->getLocation(), T,
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002451 diag::err_typecheck_decl_incomplete_type))
Steve Naroffbb204692007-09-12 14:07:44 +00002452 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002453 }
2454 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2455 // object that has file scope without an initializer, and without a
2456 // storage-class specifier or with the storage-class specifier "static",
2457 // constitutes a tentative definition. Note: A tentative definition with
2458 // external linkage is valid (C99 6.2.2p5).
Douglas Gregor275a3692009-03-10 23:43:53 +00002459 if (IDecl->isTentativeDefinition(Context)) {
Douglas Gregora03aca82009-03-10 21:58:27 +00002460 QualType CheckType = T;
2461 unsigned DiagID = diag::err_typecheck_decl_incomplete_type;
2462
2463 const IncompleteArrayType *ArrayT = Context.getAsIncompleteArrayType(T);
2464 if (ArrayT) {
2465 CheckType = ArrayT->getElementType();
2466 DiagID = diag::err_illegal_decl_array_incomplete_type;
2467 }
2468
2469 if (IDecl->isInvalidDecl()) {
2470 // Do nothing with invalid declarations
2471 } else if ((ArrayT || IDecl->getStorageClass() == VarDecl::Static) &&
2472 RequireCompleteType(IDecl->getLocation(), CheckType, DiagID)) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002473 // C99 6.9.2p3: If the declaration of an identifier for an object is
2474 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2475 // declared type shall not be an incomplete type.
Steve Naroffbb204692007-09-12 14:07:44 +00002476 IDecl->setInvalidDecl();
Douglas Gregora03aca82009-03-10 21:58:27 +00002477 }
Steve Naroffbb204692007-09-12 14:07:44 +00002478 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 }
2480 return NewGroup;
2481}
Steve Naroffe1223f72007-08-28 03:03:08 +00002482
Chris Lattner04421082008-04-08 04:40:51 +00002483/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2484/// to introduce parameters into function prototype scope.
2485Sema::DeclTy *
2486Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002487 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002488
Chris Lattner04421082008-04-08 04:40:51 +00002489 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002490 VarDecl::StorageClass StorageClass = VarDecl::None;
2491 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2492 StorageClass = VarDecl::Register;
2493 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002494 Diag(DS.getStorageClassSpecLoc(),
2495 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002496 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002497 }
2498 if (DS.isThreadSpecified()) {
2499 Diag(DS.getThreadSpecLoc(),
2500 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002501 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002502 }
2503
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002504 // Check that there are no default arguments inside the type of this
2505 // parameter (C++ only).
2506 if (getLangOptions().CPlusPlus)
2507 CheckExtraCXXDefaultArguments(D);
2508
Chris Lattner04421082008-04-08 04:40:51 +00002509 // In this context, we *do not* check D.getInvalidType(). If the declarator
2510 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2511 // though it will not reflect the user specified type.
2512 QualType parmDeclType = GetTypeForDeclarator(D, S);
2513
2514 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2515
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2517 // Can this happen for params? We already checked that they don't conflict
2518 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002519 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00002520 if (II) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00002521 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00002522 if (PrevDecl->isTemplateParameter()) {
2523 // Maybe we will complain about the shadowed template parameter.
2524 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2525 // Just pretend that we didn't see the previous declaration.
2526 PrevDecl = 0;
2527 } else if (S->isDeclScope(PrevDecl)) {
2528 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002529
Chris Lattnercf79b012009-01-21 02:38:50 +00002530 // Recover by removing the name
2531 II = 0;
2532 D.SetIdentifier(0, D.getIdentifierLoc());
2533 }
Chris Lattner04421082008-04-08 04:40:51 +00002534 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002536
2537 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2538 // Doing the promotion here has a win and a loss. The win is the type for
2539 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2540 // code generator). The loss is the orginal type isn't preserved. For example:
2541 //
2542 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2543 // int blockvardecl[5];
2544 // sizeof(parmvardecl); // size == 4
2545 // sizeof(blockvardecl); // size == 20
2546 // }
2547 //
2548 // For expressions, all implicit conversions are captured using the
2549 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2550 //
2551 // FIXME: If a source translation tool needs to see the original type, then
2552 // we need to consider storing both types (in ParmVarDecl)...
2553 //
Chris Lattnere6327742008-04-02 05:18:44 +00002554 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002555 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002556 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002557 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002558 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002559
Chris Lattner04421082008-04-08 04:40:51 +00002560 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2561 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002562 parmDeclType, StorageClass,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002563 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002564
Chris Lattner04421082008-04-08 04:40:51 +00002565 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002566 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002567
Douglas Gregor584049d2008-12-15 23:53:10 +00002568 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2569 if (D.getCXXScopeSpec().isSet()) {
2570 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2571 << D.getCXXScopeSpec().getRange();
2572 New->setInvalidDecl();
2573 }
Steve Naroffccef3712009-02-20 22:59:16 +00002574 // Parameter declarators cannot be interface types. All ObjC objects are
2575 // passed by reference.
2576 if (parmDeclType->isObjCInterfaceType()) {
2577 Diag(D.getIdentifierLoc(), diag::err_object_cannot_be_by_value)
2578 << "passed";
2579 New->setInvalidDecl();
2580 }
Douglas Gregor584049d2008-12-15 23:53:10 +00002581
Douglas Gregor44b43212008-12-11 16:49:14 +00002582 // Add the parameter declaration into this scope.
2583 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002584 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002585 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002586
Chris Lattner3ff30c82008-06-29 00:02:00 +00002587 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002588 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002589
Reid Spencer5f016e22007-07-11 17:01:13 +00002590}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002591
Douglas Gregorbe109b32009-01-23 16:23:13 +00002592void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2594 "Not a function declarator!");
2595 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002596
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2598 // for a K&R function.
2599 if (!FTI.hasPrototype) {
2600 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002601 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002602 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2603 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002604 // Implicitly declare the argument as type 'int' for lack of a better
2605 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002606 DeclSpec DS;
2607 const char* PrevSpec; // unused
2608 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2609 PrevSpec);
2610 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2611 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00002612 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 }
2614 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00002615 }
2616}
2617
2618Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2619 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2620 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2621 "Not a function declarator!");
2622 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2623
2624 if (FTI.hasPrototype) {
Chris Lattner04421082008-04-08 04:40:51 +00002625 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002626 }
2627
Douglas Gregor584049d2008-12-15 23:53:10 +00002628 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002629
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002630 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002631 ActOnDeclarator(ParentScope, D, 0,
2632 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002633}
2634
2635Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2636 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002637 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002638
2639 // See if this is a redefinition.
2640 const FunctionDecl *Definition;
2641 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002642 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002643 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002644 }
2645
Douglas Gregorcda9c672009-02-16 17:45:42 +00002646 // Builtin functions cannot be defined.
2647 if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
Douglas Gregor655753a2009-02-17 16:03:01 +00002648 if (!Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
Douglas Gregorcda9c672009-02-16 17:45:42 +00002649 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
Douglas Gregor655753a2009-02-17 16:03:01 +00002650 FD->setInvalidDecl();
2651 }
Douglas Gregorcda9c672009-02-16 17:45:42 +00002652 }
2653
Eli Friedman7f0f5dc2009-03-04 07:30:59 +00002654 // The return type of a function definition must be complete
2655 // (C99 6.9.1p3)
2656 if (FD->getResultType()->isIncompleteType() &&
2657 !FD->getResultType()->isVoidType()) {
2658 Diag(FD->getLocation(), diag::err_func_def_incomplete_result) << FD;
2659 FD->setInvalidDecl();
2660 }
2661
Douglas Gregor44b43212008-12-11 16:49:14 +00002662 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002663
Chris Lattner04421082008-04-08 04:40:51 +00002664 // Check the validity of our function parameters
2665 CheckParmsForFunctionDef(FD);
2666
2667 // Introduce our parameters into the function scope
2668 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2669 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002670 Param->setOwningFunction(FD);
2671
Chris Lattner04421082008-04-08 04:40:51 +00002672 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002673 if (Param->getIdentifier())
2674 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 }
Chris Lattner04421082008-04-08 04:40:51 +00002676
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002677 // Checking attributes of current function definition
2678 // dllimport attribute.
2679 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2680 // dllimport attribute cannot be applied to definition.
2681 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2682 Diag(FD->getLocation(),
2683 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2684 << "dllimport";
2685 FD->setInvalidDecl();
2686 return FD;
2687 } else {
2688 // If a symbol previously declared dllimport is later defined, the
2689 // attribute is ignored in subsequent references, and a warning is
2690 // emitted.
2691 Diag(FD->getLocation(),
2692 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2693 << FD->getNameAsCString() << "dllimport";
2694 }
2695 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002696 return FD;
2697}
2698
Eli Friedman8f17b662009-02-28 05:41:13 +00002699static bool StatementCreatesScope(Stmt* S) {
2700 bool result = false;
2701 if (DeclStmt* DS = dyn_cast<DeclStmt>(S)) {
2702 for (DeclStmt::decl_iterator i = DS->decl_begin();
2703 i != DS->decl_end(); ++i) {
2704 if (VarDecl* D = dyn_cast<VarDecl>(*i)) {
2705 result |= D->getType()->isVariablyModifiedType();
Eli Friedman709fa152009-02-28 06:22:14 +00002706 result |= !!D->getAttr<CleanupAttr>();
2707 } else if (TypedefDecl* D = dyn_cast<TypedefDecl>(*i)) {
2708 result |= D->getUnderlyingType()->isVariablyModifiedType();
Eli Friedman8f17b662009-02-28 05:41:13 +00002709 }
2710 }
2711 }
2712
2713 return result;
2714}
2715
2716void Sema::RecursiveCalcLabelScopes(llvm::DenseMap<Stmt*, void*>& LabelScopeMap,
2717 llvm::DenseMap<void*, Stmt*>& PopScopeMap,
2718 std::vector<void*>& ScopeStack,
2719 Stmt* CurStmt,
2720 Stmt* ParentCompoundStmt) {
2721 for (Stmt::child_iterator i = CurStmt->child_begin();
2722 i != CurStmt->child_end(); ++i) {
2723 if (!*i) continue;
2724 if (StatementCreatesScope(*i)) {
2725 ScopeStack.push_back(*i);
2726 PopScopeMap[*i] = ParentCompoundStmt;
2727 } else if (isa<LabelStmt>(CurStmt)) {
2728 LabelScopeMap[CurStmt] = ScopeStack.size() ? ScopeStack.back() : 0;
2729 }
2730 if (isa<DeclStmt>(*i)) continue;
2731 Stmt* CurCompound = isa<CompoundStmt>(*i) ? *i : ParentCompoundStmt;
2732 RecursiveCalcLabelScopes(LabelScopeMap, PopScopeMap, ScopeStack,
2733 *i, CurCompound);
2734 }
2735
2736 while (ScopeStack.size() && PopScopeMap[ScopeStack.back()] == CurStmt) {
2737 ScopeStack.pop_back();
2738 }
2739}
2740
2741void Sema::RecursiveCalcJumpScopes(llvm::DenseMap<Stmt*, void*>& LabelScopeMap,
2742 llvm::DenseMap<void*, Stmt*>& PopScopeMap,
2743 llvm::DenseMap<Stmt*, void*>& GotoScopeMap,
2744 std::vector<void*>& ScopeStack,
2745 Stmt* CurStmt) {
2746 for (Stmt::child_iterator i = CurStmt->child_begin();
2747 i != CurStmt->child_end(); ++i) {
2748 if (!*i) continue;
2749 if (StatementCreatesScope(*i)) {
2750 ScopeStack.push_back(*i);
2751 } else if (GotoStmt* GS = dyn_cast<GotoStmt>(*i)) {
2752 void* LScope = LabelScopeMap[GS->getLabel()];
2753 if (LScope) {
2754 bool foundScopeInStack = false;
2755 for (unsigned i = ScopeStack.size(); i > 0; --i) {
2756 if (LScope == ScopeStack[i-1]) {
2757 foundScopeInStack = true;
2758 break;
2759 }
2760 }
2761 if (!foundScopeInStack) {
2762 Diag(GS->getSourceRange().getBegin(), diag::err_goto_into_scope);
2763 }
2764 }
2765 }
2766 if (isa<DeclStmt>(*i)) continue;
Chris Lattner24793662009-03-05 22:45:59 +00002767 RecursiveCalcJumpScopes(LabelScopeMap, PopScopeMap, GotoScopeMap,
2768 ScopeStack, *i);
Eli Friedman8f17b662009-02-28 05:41:13 +00002769 }
2770
2771 while (ScopeStack.size() && PopScopeMap[ScopeStack.back()] == CurStmt) {
2772 ScopeStack.pop_back();
2773 }
2774}
2775
Sebastian Redl798d1192008-12-13 16:23:55 +00002776Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002777 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002778 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002779 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Ted Kremenekeaab2062009-03-12 18:33:24 +00002780 FD->setBody(cast<CompoundStmt>(Body));
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002781 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002782 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Chris Lattnerffed1632009-02-16 19:27:54 +00002783 assert(MD == getCurMethodDecl() && "Method parsing confused");
Ted Kremenekeaab2062009-03-12 18:33:24 +00002784 MD->setBody(cast<CompoundStmt>(Body));
Ted Kremenek8189cde2009-02-07 01:47:29 +00002785 } else {
2786 Body->Destroy(Context);
Steve Naroff394f3f42008-07-25 17:57:26 +00002787 return 0;
Ted Kremenek8189cde2009-02-07 01:47:29 +00002788 }
Chris Lattnerb048c982008-04-06 04:47:34 +00002789 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002790 // Verify and clean out per-function state.
Eli Friedman8f17b662009-02-28 05:41:13 +00002791
Steve Naroffcaaacec2009-03-13 15:38:40 +00002792 bool HaveLabels = !LabelMap.empty();
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 // Check goto/label use.
Steve Naroffcaaacec2009-03-13 15:38:40 +00002794 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2795 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 // Verify that we have no forward references left. If so, there was a goto
2797 // or address of a label taken, but no definition of it. Label fwd
2798 // definitions are indicated with a null substmt.
Steve Naroffcaaacec2009-03-13 15:38:40 +00002799 if (I->second->getSubStmt() == 0) {
2800 LabelStmt *L = I->second;
Reid Spencer5f016e22007-07-11 17:01:13 +00002801 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002802 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002803
2804 // At this point, we have gotos that use the bogus label. Stitch it into
2805 // the function body so that they aren't leaked and that the AST is well
2806 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002807 if (Body) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00002808#if 0
2809 // FIXME: Why do this? Having a 'push_back' in CompoundStmt is ugly,
2810 // and the AST is malformed anyway. We should just blow away 'L'.
2811 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
2812 cast<CompoundStmt>(Body)->push_back(L);
2813#else
2814 L->Destroy(Context);
2815#endif
Chris Lattner0cbc2152008-01-25 00:01:10 +00002816 } else {
2817 // The whole function wasn't parsed correctly, just delete this.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002818 L->Destroy(Context);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002819 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 }
2821 }
Steve Naroffcaaacec2009-03-13 15:38:40 +00002822 LabelMap.clear();
Eli Friedman8f17b662009-02-28 05:41:13 +00002823
2824 if (!Body) return D;
2825
2826 if (HaveLabels) {
2827 llvm::DenseMap<Stmt*, void*> LabelScopeMap;
2828 llvm::DenseMap<void*, Stmt*> PopScopeMap;
2829 llvm::DenseMap<Stmt*, void*> GotoScopeMap;
2830 std::vector<void*> ScopeStack;
2831 RecursiveCalcLabelScopes(LabelScopeMap, PopScopeMap, ScopeStack, Body, Body);
2832 RecursiveCalcJumpScopes(LabelScopeMap, PopScopeMap, GotoScopeMap, ScopeStack, Body);
2833 }
2834
Steve Naroffd6d054d2007-11-11 23:20:51 +00002835 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002836}
2837
Reid Spencer5f016e22007-07-11 17:01:13 +00002838/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2839/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002840NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2841 IdentifierInfo &II, Scope *S) {
Douglas Gregor63935192009-03-02 00:19:53 +00002842 // Before we produce a declaration for an implicitly defined
2843 // function, see whether there was a locally-scoped declaration of
2844 // this name as a function or variable. If so, use that
2845 // (non-visible) declaration, and complain about it.
2846 llvm::DenseMap<DeclarationName, NamedDecl *>::iterator Pos
2847 = LocallyScopedExternalDecls.find(&II);
2848 if (Pos != LocallyScopedExternalDecls.end()) {
2849 Diag(Loc, diag::warn_use_out_of_scope_declaration) << Pos->second;
2850 Diag(Pos->second->getLocation(), diag::note_previous_declaration);
2851 return Pos->second;
2852 }
2853
Chris Lattner37d10842008-05-05 21:18:06 +00002854 // Extension in C99. Legal in C90, but warn about it.
2855 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002856 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002857 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002858 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002859
2860 // FIXME: handle stuff like:
2861 // void foo() { extern float X(); }
2862 // void bar() { X(); } <-- implicit decl for X in another scope.
2863
2864 // Set a Declarator for the implicit definition: int foo();
2865 const char *Dummy;
2866 DeclSpec DS;
2867 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2868 Error = Error; // Silence warning.
2869 assert(!Error && "Error setting up implicit decl!");
2870 Declarator D(DS, Declarator::BlockContext);
Douglas Gregor965acbb2009-02-18 07:07:28 +00002871 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, SourceLocation(),
2872 0, 0, 0, Loc, D),
Sebastian Redlab197ba2009-02-09 18:23:29 +00002873 SourceLocation());
Reid Spencer5f016e22007-07-11 17:01:13 +00002874 D.SetIdentifier(&II, Loc);
Sebastian Redlab197ba2009-02-09 18:23:29 +00002875
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002876 // Insert this function into translation-unit scope.
2877
2878 DeclContext *PrevDC = CurContext;
2879 CurContext = Context.getTranslationUnitDecl();
2880
Steve Naroffe2ef8152008-04-04 14:32:09 +00002881 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002882 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002883 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002884
2885 CurContext = PrevDC;
2886
Douglas Gregor3c385e52009-02-14 18:57:46 +00002887 AddKnownFunctionAttributes(FD);
2888
Steve Naroffe2ef8152008-04-04 14:32:09 +00002889 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002890}
2891
Douglas Gregor3c385e52009-02-14 18:57:46 +00002892/// \brief Adds any function attributes that we know a priori based on
2893/// the declaration of this function.
2894///
2895/// These attributes can apply both to implicitly-declared builtins
2896/// (like __builtin___printf_chk) or to library-declared functions
2897/// like NSLog or printf.
2898void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
2899 if (FD->isInvalidDecl())
2900 return;
2901
2902 // If this is a built-in function, map its builtin attributes to
2903 // actual attributes.
2904 if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
2905 // Handle printf-formatting attributes.
2906 unsigned FormatIdx;
2907 bool HasVAListArg;
2908 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
2909 if (!FD->getAttr<FormatAttr>())
Chris Lattner0b2b6e12009-03-04 06:34:08 +00002910 FD->addAttr(::new (Context) FormatAttr("printf", FormatIdx + 1,
2911 FormatIdx + 2));
Douglas Gregor3c385e52009-02-14 18:57:46 +00002912 }
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00002913
2914 // Mark const if we don't care about errno and that is the only
2915 // thing preventing the function from being const. This allows
2916 // IRgen to use LLVM intrinsics for such functions.
2917 if (!getLangOptions().MathErrno &&
2918 Context.BuiltinInfo.isConstWithoutErrno(BuiltinID)) {
2919 if (!FD->getAttr<ConstAttr>())
Chris Lattner0b2b6e12009-03-04 06:34:08 +00002920 FD->addAttr(::new (Context) ConstAttr());
Daniel Dunbaref2abfe2009-02-16 22:43:43 +00002921 }
Douglas Gregor3c385e52009-02-14 18:57:46 +00002922 }
2923
2924 IdentifierInfo *Name = FD->getIdentifier();
2925 if (!Name)
2926 return;
2927 if ((!getLangOptions().CPlusPlus &&
2928 FD->getDeclContext()->isTranslationUnit()) ||
2929 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
2930 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
2931 LinkageSpecDecl::lang_c)) {
2932 // Okay: this could be a libc/libm/Objective-C function we know
2933 // about.
2934 } else
2935 return;
2936
2937 unsigned KnownID;
2938 for (KnownID = 0; KnownID != id_num_known_functions; ++KnownID)
2939 if (KnownFunctionIDs[KnownID] == Name)
2940 break;
2941
2942 switch (KnownID) {
2943 case id_NSLog:
2944 case id_NSLogv:
2945 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
2946 // FIXME: We known better than our headers.
2947 const_cast<FormatAttr *>(Format)->setType("printf");
2948 } else
Chris Lattner0b2b6e12009-03-04 06:34:08 +00002949 FD->addAttr(::new (Context) FormatAttr("printf", 1, 2));
Douglas Gregor3c385e52009-02-14 18:57:46 +00002950 break;
2951
2952 case id_asprintf:
2953 case id_vasprintf:
2954 if (!FD->getAttr<FormatAttr>())
Chris Lattner0b2b6e12009-03-04 06:34:08 +00002955 FD->addAttr(::new (Context) FormatAttr("printf", 2, 3));
Douglas Gregor3c385e52009-02-14 18:57:46 +00002956 break;
2957
2958 default:
2959 // Unknown function or known function without any attributes to
2960 // add. Do nothing.
2961 break;
2962 }
2963}
Reid Spencer5f016e22007-07-11 17:01:13 +00002964
Chris Lattner41af0932007-11-14 06:34:38 +00002965TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002966 Decl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002967 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002968 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002969
2970 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002971 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2972 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002973 D.getIdentifier(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002974 T);
Anders Carlsson4843e582009-03-10 17:07:44 +00002975
2976 if (TagType *TT = dyn_cast<TagType>(T)) {
2977 TagDecl *TD = TT->getDecl();
2978
2979 // If the TagDecl that the TypedefDecl points to is an anonymous decl
2980 // keep track of the TypedefDecl.
2981 if (!TD->getIdentifier() && !TD->getTypedefForAnonDecl())
2982 TD->setTypedefForAnonDecl(NewTD);
2983 }
2984
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002985 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002986 if (D.getInvalidType())
2987 NewTD->setInvalidDecl();
2988 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002989}
2990
Steve Naroff08d92e42007-09-15 18:49:24 +00002991/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002992/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002993/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00002994/// reference/declaration/definition of a tag.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002995Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002996 SourceLocation KWLoc, const CXXScopeSpec &SS,
2997 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorddc29e12009-02-06 22:42:48 +00002998 AttributeList *Attr) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002999 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00003000 assert((Name != 0 || TK == TK_Definition) &&
3001 "Nameless record must be a definition!");
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003002
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003003 TagDecl::TagKind Kind;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003004 switch (TagSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003005 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003006 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
3007 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
3008 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
3009 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 }
3011
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003012 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00003013 DeclContext *DC = CurContext;
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003014 NamedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003015
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003016 bool Invalid = false;
3017
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003018 if (Name && SS.isNotEmpty()) {
3019 // We have a nested-name tag ('struct foo::bar').
3020
3021 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00003022 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003023 Name = 0;
3024 goto CreateNewDecl;
3025 }
3026
Douglas Gregor4fdf1fa2009-03-11 16:48:53 +00003027 // FIXME: RequireCompleteDeclContext(SS)?
Douglas Gregore4e5b052009-03-19 00:18:19 +00003028 DC = computeDeclContext(SS);
Douglas Gregor1931b442009-02-03 00:34:39 +00003029 SearchDC = DC;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00003030 // Look-up name inside 'foo::'.
Steve Naroff3e8ffd22009-01-29 00:07:50 +00003031 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003032 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003033
3034 // A tag 'foo::bar' must already exist.
3035 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003036 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003037 Name = 0;
3038 goto CreateNewDecl;
3039 }
Chris Lattnercf79b012009-01-21 02:38:50 +00003040 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003041 // If this is a named struct, check to see if there was a previous forward
3042 // declaration or definition.
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003043 // FIXME: We're looking into outer scopes here, even when we
3044 // shouldn't be. Doing so can result in ambiguities that we
3045 // shouldn't be diagnosing.
Douglas Gregore2c565d2009-02-03 19:26:08 +00003046 LookupResult R = LookupName(S, Name, LookupTagName,
3047 /*RedeclarationOnly=*/(TK != TK_Reference));
Douglas Gregor2a3009a2009-02-03 19:21:40 +00003048 if (R.isAmbiguous()) {
3049 DiagnoseAmbiguousLookup(R, Name, NameLoc);
3050 // FIXME: This is not best way to recover from case like:
3051 //
3052 // struct S s;
3053 //
3054 // causes needless err_ovl_no_viable_function_in_init latter.
3055 Name = 0;
3056 PrevDecl = 0;
3057 Invalid = true;
3058 }
3059 else
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003060 PrevDecl = R;
Douglas Gregor72de6672009-01-08 20:45:30 +00003061
3062 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
3063 // FIXME: This makes sure that we ignore the contexts associated
3064 // with C structs, unions, and enums when looking for a matching
3065 // tag declaration or definition. See the similar lookup tweak
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003066 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003067 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
3068 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00003069 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00003070 }
3071
Douglas Gregorf57172b2008-12-08 18:40:42 +00003072 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003073 // Maybe we will complain about the shadowed template parameter.
3074 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
3075 // Just pretend that we didn't see the previous declaration.
3076 PrevDecl = 0;
3077 }
3078
Chris Lattner22bd9052009-02-16 22:07:16 +00003079 if (PrevDecl) {
Douglas Gregor48f3bb92009-02-18 21:56:37 +00003080 // Check whether the previous declaration is usable.
3081 (void)DiagnoseUseOfDecl(PrevDecl, NameLoc);
Chris Lattner22bd9052009-02-16 22:07:16 +00003082
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003083 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00003084 // If this is a use of a previous tag, or if the tag is already declared
3085 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003086 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003087 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00003088 // Make sure that this wasn't declared as an enum and now used as a
3089 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003090 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003091 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003092 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00003093 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003094 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00003095 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003096 Invalid = true;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003097 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003098 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00003099
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003100 // FIXME: In the future, return a variant or some other clue
3101 // for the consumer of this Decl to know it doesn't own it.
3102 // For our current ASTs this shouldn't be a problem, but will
3103 // need to be changed with DeclGroups.
3104 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00003105 return PrevDecl;
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003106
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003107 // Diagnose attempts to redefine a tag.
3108 if (TK == TK_Definition) {
3109 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
3110 Diag(NameLoc, diag::err_redefinition) << Name;
3111 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003112 // If this is a redefinition, recover by making this
3113 // struct be anonymous, which will make any later
3114 // references get the previous definition.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003115 Name = 0;
3116 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003117 Invalid = true;
3118 } else {
3119 // If the type is currently being defined, complain
3120 // about a nested redefinition.
3121 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
3122 if (Tag->isBeingDefined()) {
3123 Diag(NameLoc, diag::err_nested_redefinition) << Name;
3124 Diag(PrevTagDecl->getLocation(),
3125 diag::note_previous_definition);
3126 Name = 0;
3127 PrevDecl = 0;
3128 Invalid = true;
3129 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003130 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003131
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003132 // Okay, this is definition of a previously declared or referenced
3133 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003134 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003135 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003136 // If we get here we have (another) forward declaration or we
3137 // have a definition. Just create a new decl.
3138 } else {
3139 // If we get here, this is a definition of a new tag type in a nested
3140 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
3141 // new decl/type. We set PrevDecl to NULL so that the entities
3142 // have distinct types.
3143 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00003144 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003145 // If we get here, we're going to create a new Decl. If PrevDecl
3146 // is non-NULL, it's a definition of the tag declared by
3147 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00003148 } else {
Douglas Gregor66973122009-01-28 17:15:10 +00003149 // PrevDecl is a namespace, template, or anything else
3150 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003151 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00003152 // The tag name clashes with a namespace name, issue an error and
3153 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00003154 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003155 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003156 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003157 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003158 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003159 } else {
3160 // The existing declaration isn't relevant to us; we're in a
3161 // new scope, so clear out the previous declaration.
3162 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003163 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003164 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003165 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
Douglas Gregor80711a22009-03-06 18:34:03 +00003166 (Kind != TagDecl::TK_enum || !getLangOptions().CPlusPlus)) {
3167 // C.scope.pdecl]p5:
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003168 // -- for an elaborated-type-specifier of the form
3169 //
3170 // class-key identifier
3171 //
3172 // if the elaborated-type-specifier is used in the
3173 // decl-specifier-seq or parameter-declaration-clause of a
3174 // function defined in namespace scope, the identifier is
3175 // declared as a class-name in the namespace that contains
3176 // the declaration; otherwise, except as a friend
3177 // declaration, the identifier is declared in the smallest
3178 // non-class, non-function-prototype scope that contains the
3179 // declaration.
3180 //
3181 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3182 // C structs and unions.
Douglas Gregor80711a22009-03-06 18:34:03 +00003183 //
3184 // GNU C also supports this behavior as part of its incomplete
3185 // enum types extension, while GNU C++ does not.
3186 //
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003187 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003188 // FIXME: We would like to maintain the current DeclContext as the
3189 // lexical context,
Douglas Gregor1931b442009-02-03 00:34:39 +00003190 while (SearchDC->isRecord())
3191 SearchDC = SearchDC->getParent();
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003192
3193 // Find the scope where we'll be declaring the tag.
3194 while (S->isClassScope() ||
3195 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003196 ((S->getFlags() & Scope::DeclScope) == 0) ||
3197 (S->getEntity() &&
3198 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003199 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003200 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003201
Chris Lattnercc98eac2008-12-17 07:13:27 +00003202CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003203
3204 // If there is an identifier, use the location of the identifier as the
3205 // location of the decl, otherwise use the location of the struct/union
3206 // keyword.
3207 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3208
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003209 // Otherwise, create a new declaration. If there is a previous
3210 // declaration of the same entity, the two will be linked via
3211 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003212 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003213
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003214 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003215 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3216 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor1931b442009-02-03 00:34:39 +00003217 New = EnumDecl::Create(Context, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003218 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003219 // If this is an undefined enum, warn.
Douglas Gregor80711a22009-03-06 18:34:03 +00003220 if (TK != TK_Definition && !Invalid) {
3221 unsigned DK = getLangOptions().CPlusPlus? diag::err_forward_ref_enum
3222 : diag::ext_forward_ref_enum;
3223 Diag(Loc, DK);
3224 }
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003225 } else {
3226 // struct/union/class
3227
Reid Spencer5f016e22007-07-11 17:01:13 +00003228 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3229 // struct X { int A; } D; D should chain to X.
Douglas Gregorddc29e12009-02-06 22:42:48 +00003230 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003231 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor1931b442009-02-03 00:34:39 +00003232 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003233 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregorddc29e12009-02-06 22:42:48 +00003234 else
Douglas Gregor1931b442009-02-03 00:34:39 +00003235 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003236 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003237 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003238
3239 if (Kind != TagDecl::TK_enum) {
3240 // Handle #pragma pack: if the #pragma pack stack has non-default
3241 // alignment, make up a packed attribute for this decl. These
3242 // attributes are checked when the ASTContext lays out the
3243 // structure.
3244 //
3245 // It is important for implementing the correct semantics that this
3246 // happen here (in act on tag decl). The #pragma pack stack is
3247 // maintained as a result of parser callbacks which can occur at
3248 // many points during the parsing of a struct declaration (because
3249 // the #pragma tokens are effectively skipped over during the
3250 // parsing of the struct).
Chris Lattner574aa402009-02-17 01:09:29 +00003251 if (unsigned Alignment = getPragmaPackAlignment())
Chris Lattner0b2b6e12009-03-04 06:34:08 +00003252 New->addAttr(::new (Context) PackedAttr(Alignment * 8));
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003253 }
3254
Douglas Gregor66973122009-01-28 17:15:10 +00003255 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3256 // C++ [dcl.typedef]p3:
3257 // [...] Similarly, in a given scope, a class or enumeration
3258 // shall not be declared with the same name as a typedef-name
3259 // that is declared in that scope and refers to a type other
3260 // than the class or enumeration itself.
Douglas Gregor4c921ae2009-01-30 01:04:22 +00003261 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregor66973122009-01-28 17:15:10 +00003262 TypedefDecl *PrevTypedef = 0;
3263 if (Lookup.getKind() == LookupResult::Found)
3264 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3265
3266 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3267 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3268 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3269 Diag(Loc, diag::err_tag_definition_of_typedef)
3270 << Context.getTypeDeclType(New)
3271 << PrevTypedef->getUnderlyingType();
3272 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3273 Invalid = true;
3274 }
3275 }
3276
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003277 if (Invalid)
3278 New->setInvalidDecl();
3279
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003280 if (Attr)
3281 ProcessDeclAttributeList(New, Attr);
3282
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003283 // If we're declaring or defining a tag in function prototype scope
3284 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003285 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3286 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3287
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003288 // Set the lexical context. If the tag has a C++ scope specifier, the
3289 // lexical context will be different from the semantic context.
Douglas Gregor1931b442009-02-03 00:34:39 +00003290 New->setLexicalDeclContext(CurContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003291
3292 if (TK == TK_Definition)
3293 New->startDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +00003294
3295 // If this has an identifier, add it to the scope stack.
3296 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003297 S = getNonFieldDeclScope(S);
Douglas Gregor1931b442009-02-03 00:34:39 +00003298 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003299 } else {
Douglas Gregor1931b442009-02-03 00:34:39 +00003300 CurContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003301 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003302
Reid Spencer5f016e22007-07-11 17:01:13 +00003303 return New;
3304}
3305
Douglas Gregor72de6672009-01-08 20:45:30 +00003306void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003307 AdjustDeclIfTemplate(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +00003308 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3309
3310 // Enter the tag context.
3311 PushDeclContext(S, Tag);
3312
3313 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3314 FieldCollector->StartClass();
3315
3316 if (Record->getIdentifier()) {
3317 // C++ [class]p2:
3318 // [...] The class-name is also inserted into the scope of the
3319 // class itself; this is known as the injected-class-name. For
3320 // purposes of access checking, the injected-class-name is treated
3321 // as if it were a public member name.
3322 RecordDecl *InjectedClassName
3323 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3324 CurContext, Record->getLocation(),
3325 Record->getIdentifier(), Record);
3326 InjectedClassName->setImplicit();
3327 PushOnScopeChains(InjectedClassName, S);
3328 }
3329 }
3330}
3331
3332void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregoraaba5e32009-02-04 19:02:06 +00003333 AdjustDeclIfTemplate(TagD);
Douglas Gregor72de6672009-01-08 20:45:30 +00003334 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3335
3336 if (isa<CXXRecordDecl>(Tag))
3337 FieldCollector->FinishClass();
3338
3339 // Exit this scope of this tag's definition.
3340 PopDeclContext();
3341
3342 // Notify the consumer that we've defined a tag.
3343 Consumer.HandleTagDeclDefinition(Tag);
3344}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003345
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003346bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003347 QualType FieldTy, const Expr *BitWidth) {
Chris Lattner24793662009-03-05 22:45:59 +00003348 // C99 6.7.2.1p4 - verify the field type.
Chris Lattner8b963ef2009-03-05 23:01:03 +00003349 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003350 if (!FieldTy->isDependentType() && !FieldTy->isIntegralType()) {
Chris Lattner24793662009-03-05 22:45:59 +00003351 // Handle incomplete types with specific error.
Douglas Gregora03aca82009-03-10 21:58:27 +00003352 if (RequireCompleteType(FieldLoc, FieldTy, diag::err_field_incomplete))
3353 return true;
Chris Lattner8b963ef2009-03-05 23:01:03 +00003354 return Diag(FieldLoc, diag::err_not_integral_type_bitfield)
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003355 << FieldName << FieldTy << BitWidth->getSourceRange();
Chris Lattner24793662009-03-05 22:45:59 +00003356 }
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003357
3358 // If the bit-width is type- or value-dependent, don't try to check
3359 // it now.
3360 if (BitWidth->isValueDependent() || BitWidth->isTypeDependent())
3361 return false;
3362
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003363 llvm::APSInt Value;
3364 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3365 return true;
3366
Chris Lattnercd087072008-12-12 04:56:04 +00003367 // Zero-width bitfield is ok for anonymous field.
3368 if (Value == 0 && FieldName)
3369 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3370
Anders Carlssonf257b612009-03-16 18:19:21 +00003371 if (Value.isSigned() && Value.isNegative())
Douglas Gregordf032512009-03-12 22:46:12 +00003372 return Diag(FieldLoc, diag::err_bitfield_has_negative_width)
3373 << FieldName << Value.toString(10);
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003374
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003375 if (!FieldTy->isDependentType()) {
3376 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3377 // FIXME: We won't need the 0 size once we check that the field type is valid.
3378 if (TypeSize && Value.getZExtValue() > TypeSize)
3379 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3380 << FieldName << (unsigned)TypeSize;
3381 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003382
3383 return false;
3384}
3385
Steve Naroff08d92e42007-09-15 18:49:24 +00003386/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003387/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003388Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003389 SourceLocation DeclStart,
3390 Declarator &D, ExprTy *BitfieldWidth) {
Douglas Gregor021c3b32009-03-11 23:00:04 +00003391
Chris Lattner24793662009-03-05 22:45:59 +00003392 return HandleField(S, static_cast<RecordDecl*>(TagD), DeclStart, D,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00003393 static_cast<Expr*>(BitfieldWidth),
3394 AS_public);
Chris Lattner24793662009-03-05 22:45:59 +00003395}
3396
3397/// HandleField - Analyze a field of a C struct or a C++ data member.
3398///
3399FieldDecl *Sema::HandleField(Scope *S, RecordDecl *Record,
3400 SourceLocation DeclStart,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00003401 Declarator &D, Expr *BitWidth,
3402 AccessSpecifier AS) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003403 IdentifierInfo *II = D.getIdentifier();
Reid Spencer5f016e22007-07-11 17:01:13 +00003404 SourceLocation Loc = DeclStart;
3405 if (II) Loc = D.getIdentifierLoc();
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003406
Reid Spencer5f016e22007-07-11 17:01:13 +00003407 QualType T = GetTypeForDeclarator(D, S);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003408
Douglas Gregor021c3b32009-03-11 23:00:04 +00003409 if (getLangOptions().CPlusPlus) {
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003410 CheckExtraCXXDefaultArguments(D);
3411
Douglas Gregor021c3b32009-03-11 23:00:04 +00003412 if (D.getDeclSpec().isVirtualSpecified())
3413 Diag(D.getDeclSpec().getVirtualSpecLoc(),
3414 diag::err_virtual_non_function);
3415 }
3416
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003417 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
3418 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
3419 PrevDecl = 0;
3420
3421 FieldDecl *NewFD
3422 = CheckFieldDecl(II, T, Record, Loc,
3423 D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_mutable,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00003424 BitWidth, AS, PrevDecl, &D);
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003425 if (NewFD->isInvalidDecl() && PrevDecl) {
3426 // Don't introduce NewFD into scope; there's already something
3427 // with the same name in the same scope.
3428 } else if (II) {
3429 PushOnScopeChains(NewFD, S);
3430 } else
3431 Record->addDecl(NewFD);
3432
3433 return NewFD;
3434}
3435
3436/// \brief Build a new FieldDecl and check its well-formedness.
3437///
3438/// This routine builds a new FieldDecl given the fields name, type,
3439/// record, etc. \p PrevDecl should refer to any previous declaration
3440/// with the same name and in the same scope as the field to be
3441/// created.
3442///
3443/// \returns a new FieldDecl.
3444///
3445/// \todo The Declarator argument is a hack. It will be removed once
3446FieldDecl *Sema::CheckFieldDecl(DeclarationName Name, QualType T,
3447 RecordDecl *Record, SourceLocation Loc,
3448 bool Mutable, Expr *BitWidth,
Douglas Gregor4dd55f52009-03-11 20:50:30 +00003449 AccessSpecifier AS, NamedDecl *PrevDecl,
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003450 Declarator *D) {
3451 IdentifierInfo *II = Name.getAsIdentifierInfo();
Steve Naroff5912a352007-08-28 20:14:24 +00003452 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003453
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003454 // If we receive a broken type, recover by assuming 'int' and
3455 // marking this declaration as invalid.
3456 if (T.isNull()) {
3457 InvalidDecl = true;
3458 T = Context.IntTy;
3459 }
3460
Reid Spencer5f016e22007-07-11 17:01:13 +00003461 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3462 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003463 if (T->isVariablyModifiedType()) {
Eli Friedman1ca48132009-02-21 00:44:51 +00003464 bool SizeIsNegative;
3465 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context,
3466 SizeIsNegative);
3467 if (!FixedTy.isNull()) {
3468 Diag(Loc, diag::warn_illegal_constant_array_size);
3469 T = FixedTy;
3470 } else {
3471 if (SizeIsNegative)
3472 Diag(Loc, diag::err_typecheck_negative_array_size);
3473 else
3474 Diag(Loc, diag::err_typecheck_field_variable_size);
3475 T = Context.IntTy;
3476 InvalidDecl = true;
3477 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003478 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003479
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003480 // If this is declared as a bit-field, check the bit-field.
3481 if (BitWidth && VerifyBitField(Loc, II, T, BitWidth)) {
3482 InvalidDecl = true;
3483 DeleteExpr(BitWidth);
3484 BitWidth = 0;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003485 }
3486
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003487 FieldDecl *NewFD = FieldDecl::Create(Context, Record, Loc, II, T, BitWidth,
3488 Mutable);
Douglas Gregor44b43212008-12-11 16:49:14 +00003489
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003490 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
3491 Diag(Loc, diag::err_duplicate_member) << II;
3492 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3493 NewFD->setInvalidDecl();
3494 Record->setInvalidDecl();
Douglas Gregor72de6672009-01-08 20:45:30 +00003495 }
3496
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003497 if (getLangOptions().CPlusPlus && !T->isPODType())
3498 cast<CXXRecordDecl>(Record)->setPOD(false);
Douglas Gregor72b505b2008-12-16 21:30:33 +00003499
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003500 // FIXME: We need to pass in the attributes given an AST
3501 // representation, not a parser representation.
3502 if (D)
3503 ProcessDeclAttributes(NewFD, *D);
3504
Fariborz Jahanianf6123ca2009-02-19 00:22:47 +00003505 if (T.isObjCGCWeak())
Fariborz Jahanianed7e9ef2009-02-18 18:14:41 +00003506 Diag(Loc, diag::warn_attribute_weak_on_field);
Anders Carlssonad148062008-02-16 00:29:18 +00003507
Douglas Gregor3cf538d2009-03-11 18:59:21 +00003508 if (InvalidDecl)
Steve Naroff5912a352007-08-28 20:14:24 +00003509 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003510
Douglas Gregor4dd55f52009-03-11 20:50:30 +00003511 NewFD->setAccess(AS);
3512
3513 // C++ [dcl.init.aggr]p1:
3514 // An aggregate is an array or a class (clause 9) with [...] no
3515 // private or protected non-static data members (clause 11).
3516 // A POD must be an aggregate.
3517 if (getLangOptions().CPlusPlus &&
3518 (AS == AS_private || AS == AS_protected)) {
3519 CXXRecordDecl *CXXRecord = cast<CXXRecordDecl>(Record);
3520 CXXRecord->setAggregate(false);
3521 CXXRecord->setPOD(false);
3522 }
3523
Steve Naroff5912a352007-08-28 20:14:24 +00003524 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003525}
3526
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003527/// TranslateIvarVisibility - Translate visibility from a token ID to an
3528/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003529static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003530TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003531 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003532 default: assert(0 && "Unknown visitibility kind");
3533 case tok::objc_private: return ObjCIvarDecl::Private;
3534 case tok::objc_public: return ObjCIvarDecl::Public;
3535 case tok::objc_protected: return ObjCIvarDecl::Protected;
3536 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003537 }
3538}
3539
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003540/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3541/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003542Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003543 SourceLocation DeclStart,
3544 Declarator &D, ExprTy *BitfieldWidth,
3545 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003546
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003547 IdentifierInfo *II = D.getIdentifier();
3548 Expr *BitWidth = (Expr*)BitfieldWidth;
3549 SourceLocation Loc = DeclStart;
3550 if (II) Loc = D.getIdentifierLoc();
3551
3552 // FIXME: Unnamed fields can be handled in various different ways, for
3553 // example, unnamed unions inject all members into the struct namespace!
3554
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003555 QualType T = GetTypeForDeclarator(D, S);
3556 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3557 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003558
3559 if (BitWidth) {
Steve Naroff63359c82009-02-20 17:57:11 +00003560 // 6.7.2.1p3, 6.7.2.1p4
Chris Lattner24793662009-03-05 22:45:59 +00003561 if (VerifyBitField(Loc, II, T, BitWidth)) {
Steve Naroff63359c82009-02-20 17:57:11 +00003562 InvalidDecl = true;
Chris Lattner24793662009-03-05 22:45:59 +00003563 DeleteExpr(BitWidth);
3564 BitWidth = 0;
3565 }
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003566 } else {
3567 // Not a bitfield.
3568
3569 // validate II.
3570
3571 }
3572
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003573 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3574 // than a variably modified type.
3575 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003576 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003577 InvalidDecl = true;
3578 }
3579
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003580 // Get the visibility (access control) for this ivar.
3581 ObjCIvarDecl::AccessControl ac =
3582 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3583 : ObjCIvarDecl::None;
3584
3585 // Construct the decl.
Argyrios Kyrtzidis0c00aac2009-02-17 20:20:37 +00003586 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, CurContext, Loc, II, T,ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003587 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003588
Douglas Gregor72de6672009-01-08 20:45:30 +00003589 if (II) {
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003590 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor72de6672009-01-08 20:45:30 +00003591 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3592 && !isa<TagDecl>(PrevDecl)) {
3593 Diag(Loc, diag::err_duplicate_member) << II;
3594 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3595 NewID->setInvalidDecl();
3596 }
3597 }
3598
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003599 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003600 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003601
3602 if (D.getInvalidType() || InvalidDecl)
3603 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003604
Douglas Gregor72de6672009-01-08 20:45:30 +00003605 if (II) {
3606 // FIXME: When interfaces are DeclContexts, we'll need to add
3607 // these to the interface.
3608 S->AddDecl(NewID);
3609 IdResolver.AddDecl(NewID);
3610 }
3611
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003612 return NewID;
3613}
3614
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003615void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003616 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003617 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003618 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003619 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003620 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3621 assert(EnclosingDecl && "missing record or interface decl");
Chris Lattner1829a6d2009-02-23 22:00:08 +00003622
3623 // If the decl this is being inserted into is invalid, then it may be a
3624 // redeclaration or some other bogus case. Don't try to add fields to it.
3625 if (EnclosingDecl->isInvalidDecl()) {
3626 // FIXME: Deallocate fields?
3627 return;
3628 }
3629
Steve Naroff74216642007-09-14 22:20:54 +00003630
Reid Spencer5f016e22007-07-11 17:01:13 +00003631 // Verify that all the fields are okay.
3632 unsigned NumNamedMembers = 0;
3633 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003634
Chris Lattner1829a6d2009-02-23 22:00:08 +00003635 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00003636 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003637 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3638 assert(FD && "missing field decl");
3639
Reid Spencer5f016e22007-07-11 17:01:13 +00003640 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003641 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003642
Douglas Gregor72de6672009-01-08 20:45:30 +00003643 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003644 // Remember all fields written by the user.
3645 RecFields.push_back(FD);
3646 }
Chris Lattner24793662009-03-05 22:45:59 +00003647
3648 // If the field is already invalid for some reason, don't emit more
3649 // diagnostics about it.
3650 if (FD->isInvalidDecl())
3651 continue;
Steve Narofff13271f2007-09-14 23:09:53 +00003652
Reid Spencer5f016e22007-07-11 17:01:13 +00003653 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003654 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003655 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003656 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003657 FD->setInvalidDecl();
3658 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003659 continue;
3660 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003661 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3662 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003663 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor86447ec2009-03-09 16:13:40 +00003664 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003665 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003666 FD->setInvalidDecl();
3667 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003668 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003669 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003670 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003671 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003672 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor86447ec2009-03-09 16:13:40 +00003673 RequireCompleteType(FD->getLocation(), FD->getType(),
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003674 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003675 FD->setInvalidDecl();
3676 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003677 continue;
3678 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003679 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003680 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003681 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003682 FD->setInvalidDecl();
3683 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003684 continue;
3685 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003686 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003687 if (Record)
3688 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003689 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003690 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3691 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003692 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003693 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3694 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003695 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003696 Record->setHasFlexibleArrayMember(true);
3697 } else {
3698 // If this is a struct/class and this is not the last element, reject
3699 // it. Note that GCC supports variable sized arrays in the middle of
3700 // structures.
Douglas Gregore4f3e062009-03-06 23:41:27 +00003701 if (i != NumFields-1)
3702 Diag(FD->getLocation(), diag::ext_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003703 << FD->getDeclName();
Douglas Gregore4f3e062009-03-06 23:41:27 +00003704 else {
3705 // We support flexible arrays at the end of structs in
3706 // other structs as an extension.
3707 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
3708 << FD->getDeclName();
3709 if (Record)
3710 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003711 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003712 }
3713 }
3714 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003715 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003716 if (FDTy->isObjCInterfaceType()) {
Steve Naroffccef3712009-02-20 22:59:16 +00003717 Diag(FD->getLocation(), diag::err_statically_allocated_object);
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003718 FD->setInvalidDecl();
3719 EnclosingDecl->setInvalidDecl();
3720 continue;
3721 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003722 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003723 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003724 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003725 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003726
Reid Spencer5f016e22007-07-11 17:01:13 +00003727 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003728 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003729 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003730 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003731 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003732 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner38af2de2009-02-20 21:35:13 +00003733 ID->setIVarList(ClsFields, RecFields.size(), Context);
3734 ID->setLocEnd(RBrac);
3735
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003736 // Must enforce the rule that ivars in the base classes may not be
3737 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003738 if (ID->getSuperClass()) {
3739 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3740 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3741 ObjCIvarDecl* Ivar = (*IVI);
3742 IdentifierInfo *II = Ivar->getIdentifier();
Chris Lattner24793662009-03-05 22:45:59 +00003743 ObjCIvarDecl* prevIvar =
3744 ID->getSuperClass()->lookupInstanceVariable(II);
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003745 if (prevIvar) {
3746 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003747 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003748 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003749 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003750 }
Chris Lattner1829a6d2009-02-23 22:00:08 +00003751 } else if (ObjCImplementationDecl *IMPDecl =
3752 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003753 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
Chris Lattner38af2de2009-02-20 21:35:13 +00003754 IMPDecl->setIVarList(ClsFields, RecFields.size(), Context);
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003755 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003756 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003757 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003758
3759 if (Attr)
3760 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003761}
3762
Douglas Gregor879fd492009-03-17 19:05:46 +00003763EnumConstantDecl *Sema::CheckEnumConstant(EnumDecl *Enum,
3764 EnumConstantDecl *LastEnumConst,
3765 SourceLocation IdLoc,
3766 IdentifierInfo *Id,
3767 ExprArg val) {
3768 Expr *Val = (Expr *)val.get();
3769
3770 llvm::APSInt EnumVal(32);
3771 QualType EltTy;
3772 if (Val && !Val->isTypeDependent()) {
3773 // Make sure to promote the operand type to int.
3774 UsualUnaryConversions(Val);
3775 if (Val != val.get()) {
3776 val.release();
3777 val = Val;
3778 }
3779
3780 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3781 SourceLocation ExpLoc;
3782 if (!Val->isValueDependent() &&
3783 VerifyIntegerConstantExpression(Val, &EnumVal)) {
3784 Val = 0;
3785 } else {
3786 EltTy = Val->getType();
3787 }
3788 }
3789
3790 if (!Val) {
3791 if (LastEnumConst) {
3792 // Assign the last value + 1.
3793 EnumVal = LastEnumConst->getInitVal();
3794 ++EnumVal;
3795
3796 // Check for overflow on increment.
3797 if (EnumVal < LastEnumConst->getInitVal())
3798 Diag(IdLoc, diag::warn_enum_value_overflow);
3799
3800 EltTy = LastEnumConst->getType();
3801 } else {
3802 // First value, set to zero.
3803 EltTy = Context.IntTy;
3804 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
3805 }
3806 }
3807
3808 val.release();
3809 return EnumConstantDecl::Create(Context, Enum, IdLoc, Id, EltTy,
3810 Val, EnumVal);
3811}
3812
3813
Steve Naroff08d92e42007-09-15 18:49:24 +00003814Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003815 DeclTy *lastEnumConst,
3816 SourceLocation IdLoc, IdentifierInfo *Id,
3817 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003818 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003819 EnumConstantDecl *LastEnumConst =
3820 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3821 Expr *Val = static_cast<Expr*>(val);
3822
Chris Lattner31e05722007-08-26 06:24:45 +00003823 // The scope passed in may not be a decl scope. Zip up the scope tree until
3824 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003825 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003826
Reid Spencer5f016e22007-07-11 17:01:13 +00003827 // Verify that there isn't already something declared with this name in this
3828 // scope.
Douglas Gregor47b9a1c2009-02-04 17:27:36 +00003829 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003830 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003831 // Maybe we will complain about the shadowed template parameter.
3832 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3833 // Just pretend that we didn't see the previous declaration.
3834 PrevDecl = 0;
3835 }
3836
3837 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003838 // When in C++, we may get a TagDecl with the same name; in this case the
3839 // enum constant will 'hide' the tag.
3840 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3841 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003842 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003843 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003844 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003845 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003846 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003847 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnerf306f862009-02-28 19:37:57 +00003848 if (Val) Val->Destroy(Context);
Reid Spencer5f016e22007-07-11 17:01:13 +00003849 return 0;
3850 }
3851 }
3852
Douglas Gregor879fd492009-03-17 19:05:46 +00003853 EnumConstantDecl *New = CheckEnumConstant(TheEnumDecl, LastEnumConst,
3854 IdLoc, Id, Owned(Val));
Chris Lattner421a23d2007-08-27 21:16:18 +00003855
Reid Spencer5f016e22007-07-11 17:01:13 +00003856 // Register this decl in the current scope stack.
Douglas Gregor879fd492009-03-17 19:05:46 +00003857 if (New)
3858 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003859
Reid Spencer5f016e22007-07-11 17:01:13 +00003860 return New;
3861}
3862
Steve Naroff02408c62008-08-07 14:08:16 +00003863// FIXME: For consistency with ActOnFields(), we should have the parser
3864// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003865void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003866 DeclTy **Elements, unsigned NumElements) {
3867 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003868 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003869
Chris Lattnere37f0be2007-08-28 05:10:31 +00003870 // TODO: If the result value doesn't fit in an int, it must be a long or long
3871 // long value. ISO C does not support this, but GCC does as an extension,
3872 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003873 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003874
Chris Lattnerac609682007-08-28 06:15:15 +00003875 // Verify that all the values are okay, compute the size of the values, and
3876 // reverse the list.
3877 unsigned NumNegativeBits = 0;
3878 unsigned NumPositiveBits = 0;
3879
3880 // Keep track of whether all elements have type int.
3881 bool AllElementsInt = true;
3882
Reid Spencer5f016e22007-07-11 17:01:13 +00003883 for (unsigned i = 0; i != NumElements; ++i) {
3884 EnumConstantDecl *ECD =
3885 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3886 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003887
3888 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003889 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003890 assert(InitVal.getBitWidth() >= IntWidth &&
3891 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003892 if (InitVal.getBitWidth() > IntWidth) {
3893 llvm::APSInt V(InitVal);
3894 V.trunc(IntWidth);
3895 V.extend(InitVal.getBitWidth());
3896 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003897 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3898 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003899 }
Chris Lattnerac609682007-08-28 06:15:15 +00003900
3901 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003902 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003903 NumPositiveBits = std::max(NumPositiveBits,
3904 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003905 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003906 NumNegativeBits = std::max(NumNegativeBits,
3907 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003908
Chris Lattnerac609682007-08-28 06:15:15 +00003909 // Keep track of whether every enum element has type int (very commmon).
3910 if (AllElementsInt)
3911 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003912 }
3913
Chris Lattnerac609682007-08-28 06:15:15 +00003914 // Figure out the type that should be used for this enum.
3915 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3916 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003917 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003918
3919 if (NumNegativeBits) {
3920 // If there is a negative value, figure out the smallest integer type (of
3921 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003922 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003923 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003924 BestWidth = IntWidth;
3925 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003926 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003927
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003928 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003929 BestType = Context.LongTy;
3930 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003931 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003932
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003933 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003934 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3935 BestType = Context.LongLongTy;
3936 }
3937 }
3938 } else {
3939 // If there is no negative value, figure out which of uint, ulong, ulonglong
3940 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003941 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003942 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003943 BestWidth = IntWidth;
3944 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003945 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003946 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003947 } else {
3948 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003949 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003950 "How could an initializer get larger than ULL?");
3951 BestType = Context.UnsignedLongLongTy;
3952 }
3953 }
3954
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003955 // Loop over all of the enumerator constants, changing their types to match
3956 // the type of the enum if needed.
3957 for (unsigned i = 0; i != NumElements; ++i) {
3958 EnumConstantDecl *ECD =
3959 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3960 if (!ECD) continue; // Already issued a diagnostic.
3961
3962 // Standard C says the enumerators have int type, but we allow, as an
3963 // extension, the enumerators to be larger than int size. If each
3964 // enumerator value fits in an int, type it as an int, otherwise type it the
3965 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3966 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003967 if (ECD->getType() == Context.IntTy) {
3968 // Make sure the init value is signed.
3969 llvm::APSInt IV = ECD->getInitVal();
3970 IV.setIsSigned(true);
3971 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003972
3973 if (getLangOptions().CPlusPlus)
3974 // C++ [dcl.enum]p4: Following the closing brace of an
3975 // enum-specifier, each enumerator has the type of its
3976 // enumeration.
3977 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003978 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003979 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003980
3981 // Determine whether the value fits into an int.
3982 llvm::APSInt InitVal = ECD->getInitVal();
3983 bool FitsInInt;
3984 if (InitVal.isUnsigned() || !InitVal.isNegative())
3985 FitsInInt = InitVal.getActiveBits() < IntWidth;
3986 else
3987 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3988
3989 // If it fits into an integer type, force it. Otherwise force it to match
3990 // the enum decl type.
3991 QualType NewTy;
3992 unsigned NewWidth;
3993 bool NewSign;
3994 if (FitsInInt) {
3995 NewTy = Context.IntTy;
3996 NewWidth = IntWidth;
3997 NewSign = true;
3998 } else if (ECD->getType() == BestType) {
3999 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004000 if (getLangOptions().CPlusPlus)
4001 // C++ [dcl.enum]p4: Following the closing brace of an
4002 // enum-specifier, each enumerator has the type of its
4003 // enumeration.
4004 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004005 continue;
4006 } else {
4007 NewTy = BestType;
4008 NewWidth = BestWidth;
4009 NewSign = BestType->isSignedIntegerType();
4010 }
4011
4012 // Adjust the APSInt value.
4013 InitVal.extOrTrunc(NewWidth);
4014 InitVal.setIsSigned(NewSign);
4015 ECD->setInitVal(InitVal);
4016
4017 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00004018 if (ECD->getInitExpr())
Ted Kremenek8189cde2009-02-07 01:47:29 +00004019 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(),
4020 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00004021 if (getLangOptions().CPlusPlus)
4022 // C++ [dcl.enum]p4: Following the closing brace of an
4023 // enum-specifier, each enumerator has the type of its
4024 // enumeration.
4025 ECD->setType(EnumType);
4026 else
4027 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00004028 }
Chris Lattnerac609682007-08-28 06:15:15 +00004029
Douglas Gregor44b43212008-12-11 16:49:14 +00004030 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00004031}
4032
Anders Carlssondfab6cb2008-02-08 00:33:21 +00004033Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00004034 ExprArg expr) {
4035 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
4036
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004037 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00004038}
4039