blob: 3960a7d57c060598d891d9e59188bb8c93c2b761 [file] [log] [blame]
Chris Lattner697e5d62006-11-09 06:32:27 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner697e5d62006-11-09 06:32:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
Chris Lattnere168f762006-11-10 05:29:30 +000014#include "Sema.h"
Anders Carlsson7a241ba2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner622c1932008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner5c5fbcc2006-12-03 08:41:30 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar6e8aa532008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Douglas Gregorded2d7b2009-02-04 19:02:06 +000019#include "clang/AST/DeclTemplate.h"
Chris Lattner2c6fcf52008-06-26 18:38:35 +000020#include "clang/AST/ExprCXX.h"
Chris Lattner591a6752006-11-19 23:16:18 +000021#include "clang/Parse/DeclSpec.h"
Chris Lattner9561a0b2007-01-28 08:20:04 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffe101f952008-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 Lattner622c1932008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffe101f952008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner38047f92007-01-27 06:24:01 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregor7a4fad12008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor8b9ccca2008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Chris Lattner697e5d62006-11-09 06:32:27 +000031using namespace clang;
32
Douglas Gregorec6e1892009-02-04 19:16:12 +000033/// \brief If the identifier refers to a type name within this scope,
34/// return the declaration of that type.
35///
36/// This routine performs ordinary name lookup of the identifier II
37/// within the given scope, with optional C++ scope specifier SS, to
Douglas Gregor9817f4a2009-02-09 15:09:02 +000038/// determine whether the name refers to a type. If so, returns an
39/// opaque pointer (actually a QualType) corresponding to that
40/// type. Otherwise, returns NULL.
Douglas Gregorec6e1892009-02-04 19:16:12 +000041///
42/// If name lookup results in an ambiguity, this routine will complain
43/// and then return NULL.
Douglas Gregor9817f4a2009-02-09 15:09:02 +000044Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, SourceLocation NameLoc,
Douglas Gregor8a6be5e2009-02-04 17:00:24 +000045 Scope *S, const CXXScopeSpec *SS) {
Douglas Gregor960b5bc2009-01-15 00:26:24 +000046 Decl *IIDecl = 0;
Douglas Gregorb9063fc2009-02-13 23:20:09 +000047 LookupResult Result = LookupParsedName(S, SS, &II, LookupOrdinaryName,
48 false, false);
Douglas Gregor960b5bc2009-01-15 00:26:24 +000049 switch (Result.getKind()) {
Steve Naroffd25adc92009-01-29 18:09:31 +000050 case LookupResult::NotFound:
51 case LookupResult::FoundOverloaded:
Douglas Gregor8a6be5e2009-02-04 17:00:24 +000052 return 0;
53
Steve Naroffd25adc92009-01-29 18:09:31 +000054 case LookupResult::AmbiguousBaseSubobjectTypes:
55 case LookupResult::AmbiguousBaseSubobjects:
Douglas Gregor889ceb72009-02-03 19:21:40 +000056 case LookupResult::AmbiguousReference:
Douglas Gregor8a6be5e2009-02-04 17:00:24 +000057 DiagnoseAmbiguousLookup(Result, DeclarationName(&II), NameLoc);
Steve Naroffd25adc92009-01-29 18:09:31 +000058 return 0;
Douglas Gregor8a6be5e2009-02-04 17:00:24 +000059
Steve Naroffd25adc92009-01-29 18:09:31 +000060 case LookupResult::Found:
61 IIDecl = Result.getAsDecl();
62 break;
Douglas Gregor960b5bc2009-01-15 00:26:24 +000063 }
64
Steve Naroffd25adc92009-01-29 18:09:31 +000065 if (IIDecl) {
Douglas Gregor9817f4a2009-02-09 15:09:02 +000066 if (TypeDecl *TD = dyn_cast<TypeDecl>(IIDecl))
67 return Context.getTypeDeclType(TD).getAsOpaquePtr();
68 else if (ObjCInterfaceDecl *IDecl = dyn_cast<ObjCInterfaceDecl>(IIDecl))
69 return Context.getObjCInterfaceType(IDecl).getAsOpaquePtr();
Steve Naroffd25adc92009-01-29 18:09:31 +000070 }
Steve Naroff09bf8152007-09-06 21:24:23 +000071 return 0;
Chris Lattnere168f762006-11-10 05:29:30 +000072}
73
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000074DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000075 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000076 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000077 if (MD->isOutOfLineDefinition())
78 return MD->getLexicalDeclContext();
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000079
Chris Lattner4bf74fd2009-02-15 22:43:40 +000080 // A C++ inline method is parsed *after* the topmost class it was declared
81 // in is fully parsed (it's "complete").
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000082 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +000083 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000084 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
85 DC = MD->getParent();
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +000086 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidised983422008-07-01 10:37:29 +000087 DC = RD;
88
89 // Return the declaration context of the topmost class the inline method is
90 // declared in.
91 return DC;
92 }
93
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +000094 if (isa<ObjCMethodDecl>(DC))
95 return Context.getTranslationUnitDecl();
96
Douglas Gregor6e6ad602009-01-20 01:17:11 +000097 if (Decl *D = dyn_cast<Decl>(DC))
98 return D->getLexicalDeclContext();
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +000099
Argyrios Kyrtzidis0d09c492008-11-19 18:01:13 +0000100 return DC->getLexicalParent();
Argyrios Kyrtzidised983422008-07-01 10:37:29 +0000101}
102
Douglas Gregor91f84212008-12-11 16:49:14 +0000103void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000104 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu17a37eb2008-12-08 07:14:51 +0000105 "The next DeclContext should be lexically contained in the current one.");
Chris Lattnerbec41342008-04-22 18:39:57 +0000106 CurContext = DC;
Douglas Gregor91f84212008-12-11 16:49:14 +0000107 S->setEntity(DC);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000108}
109
Chris Lattner0a5ff0d2008-04-06 04:47:34 +0000110void Sema::PopDeclContext() {
111 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor91f84212008-12-11 16:49:14 +0000112
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +0000113 CurContext = getContainingDC(CurContext);
Chris Lattnerc5ffed42008-04-04 06:12:32 +0000114}
115
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000116/// \brief Determine whether we allow overloading of the function
117/// PrevDecl with another declaration.
118///
119/// This routine determines whether overloading is possible, not
120/// whether some new function is actually an overload. It will return
121/// true in C++ (where we can always provide overloads) or, as an
122/// extension, in C when the previous function is already an
123/// overloaded function declaration or has the "overloadable"
124/// attribute.
125static bool AllowOverloadingOfFunction(Decl *PrevDecl, ASTContext &Context) {
126 if (Context.getLangOptions().CPlusPlus)
127 return true;
128
129 if (isa<OverloadedFunctionDecl>(PrevDecl))
130 return true;
131
132 return PrevDecl->getAttr<OverloadableAttr>() != 0;
133}
134
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000135/// Add this decl to the scope shadowed decl chains.
136void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor07665a62009-01-05 19:45:36 +0000137 // Move up the scope chain until we find the nearest enclosing
138 // non-transparent context. The declaration will be introduced into this
139 // scope.
140 while (S->getEntity() &&
141 ((DeclContext *)S->getEntity())->isTransparentContext())
142 S = S->getParent();
143
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000144 S->AddDecl(D);
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000145
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000146 // Add scoped declarations into their context, so that they can be
147 // found later. Declarations without a context won't be inserted
148 // into any context.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000149 CurContext->addDecl(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000150
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000151 // C++ [basic.scope]p4:
152 // -- exactly one declaration shall declare a class name or
153 // enumeration name that is not a typedef name and the other
154 // declarations shall all refer to the same object or
155 // enumerator, or all refer to functions and function templates;
156 // in this case the class name or enumeration name is hidden.
157 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
158 // We are pushing the name of a tag (enum or class).
Douglas Gregore9558802009-01-07 16:34:42 +0000159 if (CurContext->getLookupContext()
160 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor91f84212008-12-11 16:49:14 +0000161 // We're pushing the tag into the current context, which might
162 // require some reshuffling in the identifier resolver.
163 IdentifierResolver::iterator
Douglas Gregored8f2882009-01-30 01:04:22 +0000164 I = IdResolver.begin(TD->getDeclName()),
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000165 IEnd = IdResolver.end();
166 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
167 NamedDecl *PrevDecl = *I;
168 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
169 PrevDecl = *I, ++I) {
170 if (TD->declarationReplaces(*I)) {
171 // This is a redeclaration. Remove it from the chain and
172 // break out, so that we'll add in the shadowed
173 // declaration.
174 S->RemoveDecl(*I);
175 if (PrevDecl == *I) {
176 IdResolver.RemoveDecl(*I);
177 IdResolver.AddDecl(TD);
178 return;
179 } else {
180 IdResolver.RemoveDecl(*I);
181 break;
182 }
183 }
184 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000185
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000186 // There is already a declaration with the same name in the same
187 // scope, which is not a tag declaration. It must be found
188 // before we find the new declaration, so insert the new
189 // declaration at the end of the chain.
190 IdResolver.AddShadowedDecl(TD, PrevDecl);
191
192 return;
Douglas Gregor91f84212008-12-11 16:49:14 +0000193 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000194 }
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +0000195 } else if (isa<FunctionDecl>(D) &&
196 AllowOverloadingOfFunction(D, Context)) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000197 // We are pushing the name of a function, which might be an
198 // overloaded name.
Douglas Gregor91f84212008-12-11 16:49:14 +0000199 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000200 IdentifierResolver::iterator Redecl
Douglas Gregored8f2882009-01-30 01:04:22 +0000201 = std::find_if(IdResolver.begin(FD->getDeclName()),
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000202 IdResolver.end(),
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000203 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000204 FD));
205 if (Redecl != IdResolver.end()) {
206 // There is already a declaration of a function on our
207 // IdResolver chain. Replace it with this declaration.
208 S->RemoveDecl(*Redecl);
209 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000210 }
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000211 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000212
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000213 IdResolver.AddDecl(D);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +0000214}
215
Steve Naroffc62adb62007-10-09 22:01:59 +0000216void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner1a76a3c2007-08-26 06:24:45 +0000217 if (S->decl_empty()) return;
Douglas Gregor5101c242008-12-05 18:15:24 +0000218 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
219 "Scope shouldn't contain decls!");
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000220
Chris Lattner302b4be2006-11-19 02:31:38 +0000221 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
222 I != E; ++I) {
Steve Naroff9324db12007-09-13 18:10:37 +0000223 Decl *TmpD = static_cast<Decl*>(*I);
224 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000225
Douglas Gregor91f84212008-12-11 16:49:14 +0000226 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
227 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis406fb232008-06-10 01:32:09 +0000228
Douglas Gregor91f84212008-12-11 16:49:14 +0000229 if (!D->getDeclName()) continue;
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000230
Douglas Gregor91f84212008-12-11 16:49:14 +0000231 // Remove this name from our lexical scope.
232 IdResolver.RemoveDecl(D);
Chris Lattner302b4be2006-11-19 02:31:38 +0000233 }
234}
235
Steve Naroff257520b2008-04-01 23:04:06 +0000236/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
237/// return 0 if one not found.
Steve Naroff257520b2008-04-01 23:04:06 +0000238ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff77892752008-04-02 18:30:49 +0000239 // The third "scope" argument is 0 since we aren't enabling lazy built-in
240 // creation from this context.
Douglas Gregor2ada0482009-02-04 17:27:36 +0000241 NamedDecl *IDecl = LookupName(TUScope, Id, LookupOrdinaryName);
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000242
Steve Naroff2fc93f52008-04-02 14:35:35 +0000243 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanianc7afeeb2007-10-12 19:38:20 +0000244}
245
Douglas Gregor45a33ec2009-01-12 18:45:55 +0000246/// getNonFieldDeclScope - Retrieves the innermost scope, starting
247/// from S, where a non-field would be declared. This routine copes
248/// with the difference between C and C++ scoping rules in structs and
249/// unions. For example, the following code is well-formed in C but
250/// ill-formed in C++:
251/// @code
252/// struct S6 {
253/// enum { BAR } e;
254/// };
255///
256/// void test_S6() {
257/// struct S6 a;
258/// a.e = BAR;
259/// }
260/// @endcode
261/// For the declaration of BAR, this routine will return a different
262/// scope. The scope S will be the scope of the unnamed enumeration
263/// within S6. In C++, this routine will return the scope associated
264/// with S6, because the enumeration's scope is a transparent
265/// context but structures can contain non-field names. In C, this
266/// routine will return the translation unit scope, since the
267/// enumeration's scope is a transparent context and structures cannot
268/// contain non-field names.
269Scope *Sema::getNonFieldDeclScope(Scope *S) {
270 while (((S->getFlags() & Scope::DeclScope) == 0) ||
271 (S->getEntity() &&
272 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
273 (S->isClassScope() && !getLangOptions().CPlusPlus))
274 S = S->getParent();
275 return S;
276}
277
Chris Lattner4dd27102008-05-05 22:18:14 +0000278void Sema::InitBuiltinVaListType() {
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000279 if (!Context.getBuiltinVaListType().isNull())
280 return;
281
282 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Douglas Gregor2ada0482009-02-04 17:27:36 +0000283 NamedDecl *VaDecl = LookupName(TUScope, VaIdent, LookupOrdinaryName);
Steve Naroffeee59eb2007-10-18 22:17:45 +0000284 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000285 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
286}
287
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000288/// LazilyCreateBuiltin - The specified Builtin-ID was first used at
289/// file scope. lazily create a decl for it. ForRedeclaration is true
290/// if we're creating this built-in in anticipation of redeclaring the
291/// built-in.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000292NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000293 Scope *S, bool ForRedeclaration,
294 SourceLocation Loc) {
Chris Lattner9561a0b2007-01-28 08:20:04 +0000295 Builtin::ID BID = (Builtin::ID)bid;
296
Chris Lattnerff2c1872008-09-28 05:54:29 +0000297 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7e13ab82007-10-15 20:28:48 +0000298 InitBuiltinVaListType();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000299
Douglas Gregor538c3d82009-02-14 01:52:53 +0000300 Builtin::Context::GetBuiltinTypeError Error;
301 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context, Error);
302 switch (Error) {
303 case Builtin::Context::GE_None:
304 // Okay
305 break;
306
307 case Builtin::Context::GE_Missing_FILE:
308 if (ForRedeclaration)
309 Diag(Loc, diag::err_implicit_decl_requires_stdio)
310 << Context.BuiltinInfo.GetName(BID);
311 return 0;
312 }
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000313
314 if (!ForRedeclaration && Context.BuiltinInfo.isPredefinedLibFunction(BID)) {
315 Diag(Loc, diag::ext_implicit_lib_function_decl)
316 << Context.BuiltinInfo.GetName(BID)
317 << R;
Douglas Gregorac5d4c52009-02-14 00:32:47 +0000318 if (!Context.BuiltinInfo.getHeaderName(BID).empty() &&
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000319 Diags.getDiagnosticMapping(diag::ext_implicit_lib_function_decl)
320 != diag::MAP_IGNORE)
321 Diag(Loc, diag::note_please_include_header)
322 << Context.BuiltinInfo.getHeaderName(BID)
323 << Context.BuiltinInfo.GetName(BID);
324 }
325
Argyrios Kyrtzidis6d053032008-04-17 14:47:13 +0000326 FunctionDecl *New = FunctionDecl::Create(Context,
327 Context.getTranslationUnitDecl(),
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000328 Loc, II, R,
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000329 FunctionDecl::Extern, false);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000330 New->setImplicit();
331
Chris Lattner4dd27102008-05-05 22:18:14 +0000332 // Create Decl objects for each parameter, adding them to the
333 // FunctionDecl.
334 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
335 llvm::SmallVector<ParmVarDecl*, 16> Params;
336 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
337 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000338 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenek4ba36fc2009-01-14 00:42:25 +0000339 New->setParams(Context, &Params[0], Params.size());
Chris Lattner4dd27102008-05-05 22:18:14 +0000340 }
341
Douglas Gregore711f702009-02-14 18:57:46 +0000342 AddKnownFunctionAttributes(New);
Chris Lattner4dd27102008-05-05 22:18:14 +0000343
Chris Lattnerc5c95b52008-04-11 07:00:53 +0000344 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregorc72e6452009-01-09 18:51:29 +0000345 // FIXME: This is hideous. We need to teach PushOnScopeChains to
346 // relate Scopes to DeclContexts, and probably eliminate CurContext
347 // entirely, but we're not there yet.
348 DeclContext *SavedContext = CurContext;
349 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidisfa8e15b2008-05-09 23:39:43 +0000350 PushOnScopeChains(New, TUScope);
Douglas Gregorc72e6452009-01-09 18:51:29 +0000351 CurContext = SavedContext;
Chris Lattner9561a0b2007-01-28 08:20:04 +0000352 return New;
353}
354
Sebastian Redlc4704762008-11-11 11:37:55 +0000355/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
356/// everything from the standard library is defined.
357NamespaceDecl *Sema::GetStdNamespace() {
358 if (!StdNamespace) {
Chris Lattner0e73b2c2008-11-20 05:45:14 +0000359 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc4704762008-11-11 11:37:55 +0000360 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregored8f2882009-01-30 01:04:22 +0000361 Decl *Std = LookupQualifiedName(Global, StdIdent, LookupNamespaceName);
Sebastian Redlc4704762008-11-11 11:37:55 +0000362 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
363 }
364 return StdNamespace;
365}
366
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000367/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the
368/// same name and scope as a previous declaration 'Old'. Figure out
369/// how to resolve this situation, merging decls or emitting
370/// diagnostics as appropriate. Returns true if there was an error,
371/// false otherwise.
Chris Lattner01564d92007-01-27 19:27:06 +0000372///
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000373bool Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000374 bool objc_types = false;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000375 // Allow multiple definitions for ObjC built-in typedefs.
376 // FIXME: Verify the underlying types are equivalent!
377 if (getLangOptions().ObjC1) {
Chris Lattner66e32812008-11-20 05:41:43 +0000378 const IdentifierInfo *TypeID = New->getIdentifier();
379 switch (TypeID->getLength()) {
380 default: break;
381 case 2:
382 if (!TypeID->isStr("id"))
383 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000384 Context.setObjCIdType(New);
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000385 objc_types = true;
386 break;
Chris Lattner66e32812008-11-20 05:41:43 +0000387 case 5:
388 if (!TypeID->isStr("Class"))
389 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000390 Context.setObjCClassType(New);
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000391 objc_types = true;
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000392 return false;
Chris Lattner66e32812008-11-20 05:41:43 +0000393 case 3:
394 if (!TypeID->isStr("SEL"))
395 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000396 Context.setObjCSelType(New);
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000397 objc_types = true;
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000398 return false;
Chris Lattner66e32812008-11-20 05:41:43 +0000399 case 8:
400 if (!TypeID->isStr("Protocol"))
401 break;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000402 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000403 objc_types = true;
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000404 return false;
Steve Naroff44cfcb62008-09-09 14:32:20 +0000405 }
406 // Fall through - the typedef name was not a builtin type.
407 }
Douglas Gregorfb034662009-01-28 17:15:10 +0000408 // Verify the old decl was also a type.
409 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Chris Lattnerc511efb2007-01-27 19:32:14 +0000410 if (!Old) {
Douglas Gregorfb034662009-01-28 17:15:10 +0000411 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000412 << New->getDeclName();
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000413 if (!objc_types)
414 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000415 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +0000416 }
Douglas Gregorfb034662009-01-28 17:15:10 +0000417
418 // Determine the "old" type we'll use for checking and diagnostics.
419 QualType OldType;
420 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
421 OldType = OldTypedef->getUnderlyingType();
422 else
423 OldType = Context.getTypeDeclType(Old);
424
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000425 // If the typedef types are not identical, reject them in all languages and
426 // with any extensions enabled.
Douglas Gregorfb034662009-01-28 17:15:10 +0000427
428 if (OldType != New->getUnderlyingType() &&
429 Context.getCanonicalType(OldType) !=
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000430 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +0000431 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregorfb034662009-01-28 17:15:10 +0000432 << New->getUnderlyingType() << OldType;
Fariborz Jahanian1778f4b2009-01-16 19:58:32 +0000433 if (!objc_types)
434 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000435 return true;
Chris Lattnerf9c49e52008-07-25 18:44:27 +0000436 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000437 if (objc_types) return false;
438 if (getLangOptions().Microsoft) return false;
Eli Friedman61b529f2008-06-11 06:20:39 +0000439
Douglas Gregor5d58c3a2008-11-21 16:29:06 +0000440 // C++ [dcl.typedef]p2:
441 // In a given non-class scope, a typedef specifier can be used to
442 // redefine the name of any type declared in that scope to refer
443 // to the type to which it already refers.
444 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000445 return false;
Douglas Gregor5d58c3a2008-11-21 16:29:06 +0000446
447 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroffe101f952008-01-30 23:46:05 +0000448 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
449 // *either* declaration is in a system header. The code below implements
450 // this adhoc compatibility rule. FIXME: The following code will not
451 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar84b70f72008-09-12 18:10:20 +0000452 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
453 SourceManager &SrcMgr = Context.getSourceManager();
454 if (SrcMgr.isInSystemHeader(Old->getLocation()))
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000455 return false;
Daniel Dunbar84b70f72008-09-12 18:10:20 +0000456 if (SrcMgr.isInSystemHeader(New->getLocation()))
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000457 return false;
Daniel Dunbar84b70f72008-09-12 18:10:20 +0000458 }
Eli Friedman61b529f2008-06-11 06:20:39 +0000459
Chris Lattnere3d20d92008-11-23 21:45:46 +0000460 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000461 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000462 return true;
Chris Lattner01564d92007-01-27 19:27:06 +0000463}
464
Chris Lattner2c6fcf52008-06-26 18:38:35 +0000465/// DeclhasAttr - returns true if decl Declaration already has the target
466/// attribute.
Chris Lattner84966392008-03-03 03:28:21 +0000467static bool DeclHasAttr(const Decl *decl, const Attr *target) {
468 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
469 if (attr->getKind() == target->getKind())
470 return true;
471
472 return false;
473}
474
475/// MergeAttributes - append attributes from the Old decl to the New one.
476static void MergeAttributes(Decl *New, Decl *Old) {
477 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
478
Chris Lattner84966392008-03-03 03:28:21 +0000479 while (attr) {
Douglas Gregor633b7372009-02-13 00:26:38 +0000480 tmp = attr;
481 attr = attr->getNext();
Chris Lattner84966392008-03-03 03:28:21 +0000482
Douglas Gregor633b7372009-02-13 00:26:38 +0000483 if (!DeclHasAttr(New, tmp) && tmp->isMerged()) {
484 tmp->setInherited(true);
485 New->addAttr(tmp);
Chris Lattner84966392008-03-03 03:28:21 +0000486 } else {
Douglas Gregor633b7372009-02-13 00:26:38 +0000487 tmp->setNext(0);
488 delete(tmp);
Chris Lattner84966392008-03-03 03:28:21 +0000489 }
490 }
Nuno Lopes3fe46512008-06-01 22:53:53 +0000491
492 Old->invalidateAttrs();
Chris Lattner84966392008-03-03 03:28:21 +0000493}
494
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000495/// MergeFunctionDecl - We just parsed a function 'New' from
496/// declarator D which has the same name and scope as a previous
497/// declaration 'Old'. Figure out how to resolve this situation,
498/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000499///
500/// In C++, New and Old must be declarations that are not
501/// overloaded. Use IsOverload to determine whether New and Old are
502/// overloaded, and to select the Old declaration that New should be
503/// merged with.
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000504///
505/// Returns true if there was an error, false otherwise.
506bool Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD) {
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000507 assert(!isa<OverloadedFunctionDecl>(OldD) &&
508 "Cannot merge with an overloaded function declaration");
509
Chris Lattnerc511efb2007-01-27 19:32:14 +0000510 // Verify the old decl was also a function.
511 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
512 if (!Old) {
Chris Lattnerf7e3f6d2008-11-20 06:13:02 +0000513 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000514 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000515 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000516 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +0000517 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000518
519 // Determine whether the previous declaration was a definition,
520 // implicit declaration, or a declaration.
521 diag::kind PrevDiag;
522 if (Old->isThisDeclarationADefinition())
Chris Lattner0369c572008-11-23 23:12:31 +0000523 PrevDiag = diag::note_previous_definition;
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000524 else if (Old->isImplicit())
525 PrevDiag = diag::note_previous_implicit_declaration;
526 else
Chris Lattner0369c572008-11-23 23:12:31 +0000527 PrevDiag = diag::note_previous_declaration;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000528
Chris Lattnerfc4379f2008-04-06 23:10:54 +0000529 QualType OldQType = Context.getCanonicalType(Old->getType());
530 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner5c3f1542007-11-20 19:04:50 +0000531
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000532 if (getLangOptions().CPlusPlus) {
533 // (C++98 13.1p2):
534 // Certain function declarations cannot be overloaded:
535 // -- Function declarations that differ only in the return type
536 // cannot be overloaded.
537 QualType OldReturnType
538 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
539 QualType NewReturnType
540 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
541 if (OldReturnType != NewReturnType) {
542 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000543 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000544 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000545 }
546
547 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
548 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
549 if (OldMethod && NewMethod) {
550 // -- Member function declarations with the same name and the
551 // same parameter types cannot be overloaded if any of them
552 // is a static member function declaration.
553 if (OldMethod->isStatic() || NewMethod->isStatic()) {
554 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000555 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000556 return true;
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000557 }
Douglas Gregor1349b452008-12-15 21:24:18 +0000558
559 // C++ [class.mem]p1:
560 // [...] A member shall not be declared twice in the
561 // member-specification, except that a nested class or member
562 // class template can be declared and then later defined.
563 if (OldMethod->getLexicalDeclContext() ==
564 NewMethod->getLexicalDeclContext()) {
565 unsigned NewDiag;
566 if (isa<CXXConstructorDecl>(OldMethod))
567 NewDiag = diag::err_constructor_redeclared;
568 else if (isa<CXXDestructorDecl>(NewMethod))
569 NewDiag = diag::err_destructor_redeclared;
570 else if (isa<CXXConversionDecl>(NewMethod))
571 NewDiag = diag::err_conv_function_redeclared;
572 else
573 NewDiag = diag::err_member_redeclared;
574
575 Diag(New->getLocation(), NewDiag);
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000576 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor1349b452008-12-15 21:24:18 +0000577 }
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000578 }
579
580 // (C++98 8.3.5p3):
581 // All declarations for a function shall agree exactly in both the
582 // return type and the parameter-type-list.
583 if (OldQType == NewQType) {
584 // We have a redeclaration.
585 MergeAttributes(New, Old);
Douglas Gregor5251f1b2008-10-21 16:13:35 +0000586 return MergeCXXFunctionDecl(New, Old);
587 }
588
589 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor89f238c2008-04-21 02:02:58 +0000590 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000591
592 // C: Function types need to be compatible, not identical. This handles
Steve Naroff012484d2008-01-14 20:51:29 +0000593 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000594 if (!getLangOptions().CPlusPlus &&
Eli Friedman47f77112008-08-22 00:56:42 +0000595 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor89f238c2008-04-21 02:02:58 +0000596 MergeAttributes(New, Old);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000597 return false;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000598 }
Chris Lattner45d561a2007-11-06 06:07:26 +0000599
Steve Naroff17832a42008-01-16 15:01:34 +0000600 // A function that has already been declared has been redeclared or defined
601 // with a different type- show appropriate diagnostic
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000602 if (unsigned BuiltinID = Old->getBuiltinID(Context)) {
603 // The user has declared a builtin function with an incompatible
604 // signature.
605 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
606 // The function the user is redeclaring is a library-defined
607 // function like 'malloc' or 'printf'. Warn about the
608 // redeclaration, then ignore it.
609 Diag(New->getLocation(), diag::warn_redecl_library_builtin) << New;
610 Diag(Old->getLocation(), diag::note_previous_builtin_declaration)
611 << Old << Old->getType();
612 return false;
613 }
Steve Naroff17832a42008-01-16 15:01:34 +0000614
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000615 PrevDiag = diag::note_previous_builtin_declaration;
616 }
617
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000618 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Douglas Gregorb9063fc2009-02-13 23:20:09 +0000619 Diag(Old->getLocation(), PrevDiag) << Old << Old->getType();
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000620 return true;
Chris Lattner01564d92007-01-27 19:27:06 +0000621}
622
Steve Naroff5bb8f222008-08-08 17:50:35 +0000623/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroff63ebb3c2008-08-10 15:28:06 +0000624static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroff5bb8f222008-08-08 17:50:35 +0000625 if (VD->isFileVarDecl())
626 return (!VD->getInit() &&
627 (VD->getStorageClass() == VarDecl::None ||
628 VD->getStorageClass() == VarDecl::Static));
629 return false;
630}
631
632/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
633/// when dealing with C "tentative" external object definitions (C99 6.9.2).
634void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
635 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff84e37352008-08-10 15:20:13 +0000636 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroff5bb8f222008-08-08 17:50:35 +0000637
Douglas Gregore9558802009-01-07 16:34:42 +0000638 // FIXME: I don't think this will actually see all of the
Douglas Gregor8b9ccca2008-12-23 21:05:05 +0000639 // redefinitions. Can't we check this property on-the-fly?
Douglas Gregored8f2882009-01-30 01:04:22 +0000640 for (IdentifierResolver::iterator I = IdResolver.begin(VD->getIdentifier()),
641 E = IdResolver.end();
642 I != E; ++I) {
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +0000643 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroff5bb8f222008-08-08 17:50:35 +0000644 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
645
Steve Naroff84e37352008-08-10 15:20:13 +0000646 // Handle the following case:
647 // int a[10];
648 // int a[]; - the code below makes sure we set the correct type.
649 // int a[11]; - this is an error, size isn't 10.
650 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
651 OldDecl->getType()->isConstantArrayType())
652 VD->setType(OldDecl->getType());
653
Steve Naroff5bb8f222008-08-08 17:50:35 +0000654 // Check for "tentative" definitions. We can't accomplish this in
655 // MergeVarDecl since the initializer hasn't been attached.
656 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
657 continue;
658
659 // Handle __private_extern__ just like extern.
660 if (OldDecl->getStorageClass() != VarDecl::Extern &&
661 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
662 VD->getStorageClass() != VarDecl::Extern &&
663 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000664 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000665 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Sebastian Redl95ea38f2009-02-08 10:49:44 +0000666 // One redefinition error is enough.
667 break;
Steve Naroff5bb8f222008-08-08 17:50:35 +0000668 }
669 }
670 }
671}
672
Chris Lattner01564d92007-01-27 19:27:06 +0000673/// MergeVarDecl - We just parsed a variable 'New' which has the same name
674/// and scope as a previous declaration 'Old'. Figure out how to resolve this
675/// situation, merging decls or emitting diagnostics as appropriate.
676///
Steve Naroff5bb8f222008-08-08 17:50:35 +0000677/// Tentative definition rules (C99 6.9.2p2) are checked by
678/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
679/// definitions here, since the initializer hasn't been attached.
Steve Narofffc49d672007-04-01 21:27:45 +0000680///
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000681bool Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattnerc511efb2007-01-27 19:32:14 +0000682 // Verify the old decl was also a variable.
683 VarDecl *Old = dyn_cast<VarDecl>(OldD);
684 if (!Old) {
Chris Lattner651d42d2008-11-20 06:38:18 +0000685 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnere3d20d92008-11-23 21:45:46 +0000686 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000687 Diag(OldD->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000688 return true;
Chris Lattnerc511efb2007-01-27 19:32:14 +0000689 }
Chris Lattner84966392008-03-03 03:28:21 +0000690
691 MergeAttributes(New, Old);
692
Eli Friedman8b7c5262009-01-24 23:49:55 +0000693 // Merge the types
694 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
695 if (MergedT.isNull()) {
Douglas Gregor020713e2009-01-09 19:42:16 +0000696 Diag(New->getLocation(), diag::err_redefinition_different_type)
697 << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000698 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000699 return true;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000700 }
Eli Friedman8b7c5262009-01-24 23:49:55 +0000701 New->setType(MergedT);
Steve Naroff1e787362008-01-30 00:44:01 +0000702 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
703 if (New->getStorageClass() == VarDecl::Static &&
704 (Old->getStorageClass() == VarDecl::None ||
705 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000706 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000707 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000708 return true;
Steve Naroff1e787362008-01-30 00:44:01 +0000709 }
710 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
711 if (New->getStorageClass() != VarDecl::Static &&
712 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000713 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000714 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000715 return true;
Steve Naroff1e787362008-01-30 00:44:01 +0000716 }
Steve Naroffa5629372008-09-17 14:05:40 +0000717 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
718 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnere3d20d92008-11-23 21:45:46 +0000719 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +0000720 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000721 return true;
Steve Naroff6fbf0dc2007-03-16 00:33:25 +0000722 }
Douglas Gregor75a45ba2009-02-16 17:45:42 +0000723 return false;
Chris Lattner01564d92007-01-27 19:27:06 +0000724}
725
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000726/// CheckParmsForFunctionDef - Check that the parameters of the given
727/// function are appropriate for the definition of a function. This
728/// takes care of any checks that cannot be performed on the
729/// declaration itself, e.g., that the types of each of the function
730/// parameters are complete.
731bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
732 bool HasInvalidParm = false;
733 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
734 ParmVarDecl *Param = FD->getParamDecl(p);
735
736 // C99 6.7.5.3p4: the parameters in a parameter type list in a
737 // function declarator that is part of a function definition of
738 // that function shall not have incomplete type.
Douglas Gregordd430f72009-01-19 19:26:10 +0000739 if (!Param->isInvalidDecl() &&
740 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
741 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000742 Param->setInvalidDecl();
743 HasInvalidParm = true;
744 }
Chris Lattner3d722972008-12-17 07:32:46 +0000745
746 // C99 6.9.1p5: If the declarator includes a parameter type list, the
747 // declaration of each parameter shall include an identifier.
748 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
749 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattneraa9c7ae2008-04-08 04:40:51 +0000750 }
751
752 return HasInvalidParm;
753}
754
Chris Lattnerb6738ec2007-01-28 00:38:24 +0000755/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
756/// no declarator (e.g. "struct foo;") is parsed.
757Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor9817f4a2009-02-09 15:09:02 +0000758 TagDecl *Tag = 0;
759 if (DS.getTypeSpecType() == DeclSpec::TST_class ||
760 DS.getTypeSpecType() == DeclSpec::TST_struct ||
761 DS.getTypeSpecType() == DeclSpec::TST_union ||
762 DS.getTypeSpecType() == DeclSpec::TST_enum)
763 Tag = dyn_cast<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
764
Douglas Gregorc6f58fe2009-01-12 22:49:06 +0000765 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
766 if (!Record->getDeclName() && Record->isDefinition() &&
767 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
768 return BuildAnonymousStructOrUnion(S, DS, Record);
769
770 // Microsoft allows unnamed struct/union fields. Don't complain
771 // about them.
772 // FIXME: Should we support Microsoft's extensions in this area?
773 if (Record->getDeclName() && getLangOptions().Microsoft)
774 return Tag;
775 }
776
Douglas Gregorcd72ba92009-02-06 22:42:48 +0000777 if (!DS.isMissingDeclaratorOk() &&
778 DS.getTypeSpecType() != DeclSpec::TST_error) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +0000779 // Warn about typedefs of enums without names, since this is an
780 // extension in both Microsoft an GNU.
Douglas Gregor051d8fd2009-01-17 02:55:50 +0000781 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
782 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor2d9dde0e2009-01-22 16:23:54 +0000783 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregor2b136fe2009-01-13 23:10:51 +0000784 << DS.getSourceRange();
785 return Tag;
786 }
787
Sebastian Redla2b5e312008-12-28 15:28:59 +0000788 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
789 << DS.getSourceRange();
790 return 0;
791 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000792
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000793 return Tag;
794}
795
796/// InjectAnonymousStructOrUnionMembers - Inject the members of the
797/// anonymous struct or union AnonRecord into the owning context Owner
798/// and scope S. This routine will be invoked just after we realize
799/// that an unnamed union or struct is actually an anonymous union or
800/// struct, e.g.,
801///
802/// @code
803/// union {
804/// int i;
805/// float f;
806/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
807/// // f into the surrounding scope.x
808/// @endcode
809///
810/// This routine is recursive, injecting the names of nested anonymous
811/// structs/unions into the owning context and scope as well.
812bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
813 RecordDecl *AnonRecord) {
814 bool Invalid = false;
815 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
816 FEnd = AnonRecord->field_end();
817 F != FEnd; ++F) {
818 if ((*F)->getDeclName()) {
Douglas Gregor2ada0482009-02-04 17:27:36 +0000819 NamedDecl *PrevDecl = LookupQualifiedName(Owner, (*F)->getDeclName(),
820 LookupOrdinaryName, true);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000821 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
822 // C++ [class.union]p2:
823 // The names of the members of an anonymous union shall be
824 // distinct from the names of any other entity in the
825 // scope in which the anonymous union is declared.
826 unsigned diagKind
827 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
828 : diag::err_anonymous_struct_member_redecl;
829 Diag((*F)->getLocation(), diagKind)
830 << (*F)->getDeclName();
831 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
832 Invalid = true;
833 } else {
834 // C++ [class.union]p2:
835 // For the purpose of name lookup, after the anonymous union
836 // definition, the members of the anonymous union are
837 // considered to have been defined in the scope in which the
838 // anonymous union is declared.
Douglas Gregor0da5ac82009-01-20 16:54:50 +0000839 Owner->makeDeclVisibleInContext(*F);
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000840 S->AddDecl(*F);
841 IdResolver.AddDecl(*F);
842 }
843 } else if (const RecordType *InnerRecordType
844 = (*F)->getType()->getAsRecordType()) {
845 RecordDecl *InnerRecord = InnerRecordType->getDecl();
846 if (InnerRecord->isAnonymousStructOrUnion())
847 Invalid = Invalid ||
848 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
849 }
850 }
851
852 return Invalid;
853}
854
855/// ActOnAnonymousStructOrUnion - Handle the declaration of an
856/// anonymous structure or union. Anonymous unions are a C++ feature
857/// (C++ [class.union]) and a GNU C extension; anonymous structures
858/// are a GNU C and GNU C++ extension.
859Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
860 RecordDecl *Record) {
861 DeclContext *Owner = Record->getDeclContext();
862
863 // Diagnose whether this anonymous struct/union is an extension.
864 if (Record->isUnion() && !getLangOptions().CPlusPlus)
865 Diag(Record->getLocation(), diag::ext_anonymous_union);
866 else if (!Record->isUnion())
867 Diag(Record->getLocation(), diag::ext_anonymous_struct);
868
869 // C and C++ require different kinds of checks for anonymous
870 // structs/unions.
871 bool Invalid = false;
872 if (getLangOptions().CPlusPlus) {
873 const char* PrevSpec = 0;
874 // C++ [class.union]p3:
875 // Anonymous unions declared in a named namespace or in the
876 // global namespace shall be declared static.
877 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
878 (isa<TranslationUnitDecl>(Owner) ||
879 (isa<NamespaceDecl>(Owner) &&
880 cast<NamespaceDecl>(Owner)->getDeclName()))) {
881 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
882 Invalid = true;
883
884 // Recover by adding 'static'.
885 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
886 }
887 // C++ [class.union]p3:
888 // A storage class is not allowed in a declaration of an
889 // anonymous union in a class scope.
890 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
891 isa<RecordDecl>(Owner)) {
892 Diag(DS.getStorageClassSpecLoc(),
893 diag::err_anonymous_union_with_storage_spec);
894 Invalid = true;
895
896 // Recover by removing the storage specifier.
897 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
898 PrevSpec);
899 }
Douglas Gregorf4d33272009-01-07 19:46:03 +0000900
901 // C++ [class.union]p2:
902 // The member-specification of an anonymous union shall only
903 // define non-static data members. [Note: nested types and
904 // functions cannot be declared within an anonymous union. ]
905 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
906 MemEnd = Record->decls_end();
907 Mem != MemEnd; ++Mem) {
908 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
909 // C++ [class.union]p3:
910 // An anonymous union shall not have private or protected
911 // members (clause 11).
912 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
913 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
914 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
915 Invalid = true;
916 }
917 } else if ((*Mem)->isImplicit()) {
918 // Any implicit members are fine.
Douglas Gregor8761da52009-02-03 00:34:39 +0000919 } else if (isa<TagDecl>(*Mem) && (*Mem)->getDeclContext() != Record) {
920 // This is a type that showed up in an
921 // elaborated-type-specifier inside the anonymous struct or
922 // union, but which actually declares a type outside of the
923 // anonymous struct or union. It's okay.
Douglas Gregorf4d33272009-01-07 19:46:03 +0000924 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
925 if (!MemRecord->isAnonymousStructOrUnion() &&
926 MemRecord->getDeclName()) {
927 // This is a nested type declaration.
928 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
929 << (int)Record->isUnion();
930 Invalid = true;
931 }
932 } else {
933 // We have something that isn't a non-static data
934 // member. Complain about it.
935 unsigned DK = diag::err_anonymous_record_bad_member;
936 if (isa<TypeDecl>(*Mem))
937 DK = diag::err_anonymous_record_with_type;
938 else if (isa<FunctionDecl>(*Mem))
939 DK = diag::err_anonymous_record_with_function;
940 else if (isa<VarDecl>(*Mem))
941 DK = diag::err_anonymous_record_with_static;
942 Diag((*Mem)->getLocation(), DK)
943 << (int)Record->isUnion();
944 Invalid = true;
945 }
946 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000947 } else {
948 // FIXME: Check GNU C semantics
Douglas Gregorc6f58fe2009-01-12 22:49:06 +0000949 if (Record->isUnion() && !Owner->isRecord()) {
950 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
951 << (int)getLangOptions().CPlusPlus;
952 Invalid = true;
953 }
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000954 }
955
956 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregorc6f58fe2009-01-12 22:49:06 +0000957 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
958 << (int)getLangOptions().CPlusPlus;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000959 Invalid = true;
960 }
961
962 // Create a declaration for this anonymous struct/union.
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000963 NamedDecl *Anon = 0;
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000964 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
965 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
966 /*IdentifierInfo=*/0,
967 Context.getTypeDeclType(Record),
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000968 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregorf4d33272009-01-07 19:46:03 +0000969 Anon->setAccess(AS_public);
970 if (getLangOptions().CPlusPlus)
971 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000972 } else {
973 VarDecl::StorageClass SC;
974 switch (DS.getStorageClassSpec()) {
975 default: assert(0 && "Unknown storage class!");
976 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
977 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
978 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
979 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
980 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
981 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
982 case DeclSpec::SCS_mutable:
983 // mutable can only appear on non-static class members, so it's always
984 // an error here
985 Diag(Record->getLocation(), diag::err_mutable_nonmember);
986 Invalid = true;
987 SC = VarDecl::None;
988 break;
989 }
990
991 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
992 /*IdentifierInfo=*/0,
993 Context.getTypeDeclType(Record),
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000994 SC, DS.getSourceRange().getBegin());
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000995 }
Douglas Gregorf4d33272009-01-07 19:46:03 +0000996 Anon->setImplicit();
Douglas Gregor9ac7a072009-01-07 00:43:41 +0000997
998 // Add the anonymous struct/union object to the current
999 // context. We'll be referencing this object when we refer to one of
1000 // its members.
Douglas Gregorb3730b52009-01-12 23:27:07 +00001001 Owner->addDecl(Anon);
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001002
1003 // Inject the members of the anonymous struct/union into the owning
1004 // context and into the identifier resolver chain for name lookup
1005 // purposes.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00001006 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
1007 Invalid = true;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00001008
1009 // Mark this as an anonymous struct/union type. Note that we do not
1010 // do this until after we have already checked and injected the
1011 // members of this anonymous struct/union type, because otherwise
1012 // the members could be injected twice: once by DeclContext when it
1013 // builds its lookup table, and once by
1014 // InjectAnonymousStructOrUnionMembers.
1015 Record->setAnonymousStructOrUnion(true);
1016
1017 if (Invalid)
1018 Anon->setInvalidDecl();
1019
1020 return Anon;
Chris Lattnerb6738ec2007-01-28 00:38:24 +00001021}
1022
Douglas Gregor5fb53972009-01-14 15:45:31 +00001023bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
1024 bool DirectInit) {
Steve Naroff2fea1392007-09-02 02:04:30 +00001025 // Get the type before calling CheckSingleAssignmentConstraints(), since
1026 // it can promote the expression.
Chris Lattner9bad62c2008-01-04 18:04:52 +00001027 QualType InitType = Init->getType();
Douglas Gregor47d3f272008-12-19 17:40:08 +00001028
Douglas Gregor5fb53972009-01-14 15:45:31 +00001029 if (getLangOptions().CPlusPlus) {
1030 // FIXME: I dislike this error message. A lot.
1031 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
1032 return Diag(Init->getSourceRange().getBegin(),
1033 diag::err_typecheck_convert_incompatible)
1034 << DeclType << Init->getType() << "initializing"
1035 << Init->getSourceRange();
1036
1037 return false;
1038 }
Douglas Gregor47d3f272008-12-19 17:40:08 +00001039
Chris Lattner9bad62c2008-01-04 18:04:52 +00001040 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1041 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1042 InitType, Init, "initializing");
Steve Naroff2fea1392007-09-02 02:04:30 +00001043}
1044
Steve Naroffaf2a0222008-01-22 00:55:40 +00001045bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattner7adf0762008-08-04 07:31:14 +00001046 const ArrayType *AT = Context.getAsArrayType(DeclT);
1047
1048 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffaf2a0222008-01-22 00:55:40 +00001049 // C99 6.7.8p14. We have an array of character type with unknown size
1050 // being initialized to a string literal.
1051 llvm::APSInt ConstVal(32);
1052 ConstVal = strLiteral->getByteLength() + 1;
1053 // Return a new array type (C99 6.7.8p22).
Eli Friedmanbd258282008-02-15 18:16:39 +00001054 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffaf2a0222008-01-22 00:55:40 +00001055 ArrayType::Normal, 0);
Chris Lattner7adf0762008-08-04 07:31:14 +00001056 } else {
1057 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffaf2a0222008-01-22 00:55:40 +00001058 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattner7adf0762008-08-04 07:31:14 +00001059 // FIXME: Avoid truncation for 64-bit length strings.
1060 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffaf2a0222008-01-22 00:55:40 +00001061 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerf490e152008-11-19 05:27:50 +00001062 diag::warn_initializer_string_for_char_array_too_long)
1063 << strLiteral->getSourceRange();
Steve Naroffaf2a0222008-01-22 00:55:40 +00001064 }
1065 // Set type from "char *" to "constant array of char".
1066 strLiteral->setType(DeclT);
1067 // For now, we always return false (meaning success).
1068 return false;
1069}
1070
1071StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattner7adf0762008-08-04 07:31:14 +00001072 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroff78c6cdf2008-01-25 00:51:06 +00001073 if (AT && AT->getElementType()->isCharType()) {
Anders Carlssonb66a3122009-01-24 17:47:50 +00001074 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Naroff78c6cdf2008-01-25 00:51:06 +00001075 }
Steve Naroffaf2a0222008-01-22 00:55:40 +00001076 return 0;
1077}
1078
Douglas Gregor6f543152008-11-05 15:29:30 +00001079bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1080 SourceLocation InitLoc,
Douglas Gregor5fb53972009-01-14 15:45:31 +00001081 DeclarationName InitEntity,
1082 bool DirectInit) {
Douglas Gregorb04675d2008-12-18 21:49:58 +00001083 if (DeclType->isDependentType() || Init->isTypeDependent())
1084 return false;
1085
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001086 // C++ [dcl.init.ref]p1:
Sebastian Redl849b1e62008-11-24 20:06:50 +00001087 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001088 // (8.3.2), shall be initialized by an object, or function, of
1089 // type T or by an object that can be converted into a T.
1090 if (DeclType->isReferenceType())
Douglas Gregor5fb53972009-01-14 15:45:31 +00001091 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor8e1cf602008-10-29 00:13:59 +00001092
Steve Narofff9eb5982008-01-21 23:53:58 +00001093 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1094 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattner7adf0762008-08-04 07:31:14 +00001095 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerf490e152008-11-19 05:27:50 +00001096 return Diag(InitLoc, diag::err_variable_object_no_init)
1097 << VAT->getSizeExpr()->getSourceRange();
Steve Narofff9eb5982008-01-21 23:53:58 +00001098
Steve Naroff91f78082007-12-10 22:44:33 +00001099 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1100 if (!InitList) {
Steve Naroffaf2a0222008-01-22 00:55:40 +00001101 // FIXME: Handle wide strings
1102 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1103 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman42978262008-02-08 00:48:24 +00001104
Douglas Gregor6f543152008-11-05 15:29:30 +00001105 // C++ [dcl.init]p14:
1106 // -- If the destination type is a (possibly cv-qualified) class
1107 // type:
1108 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1109 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1110 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1111
1112 // -- If the initialization is direct-initialization, or if it is
1113 // copy-initialization where the cv-unqualified version of the
1114 // source type is the same class as, or a derived class of, the
1115 // class of the destination, constructors are considered.
1116 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1117 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1118 CXXConstructorDecl *Constructor
1119 = PerformInitializationByConstructor(DeclType, &Init, 1,
1120 InitLoc, Init->getSourceRange(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00001121 InitEntity,
1122 DirectInit? IK_Direct : IK_Copy);
Douglas Gregor6f543152008-11-05 15:29:30 +00001123 return Constructor == 0;
1124 }
1125
1126 // -- Otherwise (i.e., for the remaining copy-initialization
1127 // cases), user-defined conversion sequences that can
1128 // convert from the source type to the destination type or
1129 // (when a conversion function is used) to a derived class
1130 // thereof are enumerated as described in 13.3.1.4, and the
1131 // best one is chosen through overload resolution
1132 // (13.3). If the conversion cannot be done or is
1133 // ambiguous, the initialization is ill-formed. The
1134 // function selected is called with the initializer
1135 // expression as its argument; if the function is a
1136 // constructor, the call initializes a temporary of the
1137 // destination type.
1138 // FIXME: We're pretending to do copy elision here; return to
1139 // this when we have ASTs for such things.
Douglas Gregor47d3f272008-12-19 17:40:08 +00001140 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6f543152008-11-05 15:29:30 +00001141 return false;
Chris Lattner377d1f82008-11-18 22:52:51 +00001142
Douglas Gregor58354032008-12-24 00:01:03 +00001143 if (InitEntity)
1144 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1145 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1146 << Init->getType() << Init->getSourceRange();
1147 else
1148 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1149 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1150 << Init->getType() << Init->getSourceRange();
Douglas Gregor6f543152008-11-05 15:29:30 +00001151 }
1152
Steve Naroff38093af2008-09-29 20:07:05 +00001153 // C99 6.7.8p16.
Eli Friedman42978262008-02-08 00:48:24 +00001154 if (DeclType->isArrayType())
Chris Lattnerf490e152008-11-19 05:27:50 +00001155 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1156 << Init->getSourceRange();
Eli Friedman42978262008-02-08 00:48:24 +00001157
Douglas Gregor5fb53972009-01-14 15:45:31 +00001158 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregord14247a2009-01-30 22:09:00 +00001159 }
Eli Friedman01321c32008-06-06 19:40:52 +00001160
Douglas Gregor85df8d82009-01-29 00:45:39 +00001161 bool hadError = CheckInitList(InitList, DeclType);
1162 Init = InitList;
1163 return hadError;
Steve Naroff2fea1392007-09-02 02:04:30 +00001164}
1165
Douglas Gregor92751d42008-11-17 22:58:34 +00001166/// GetNameForDeclarator - Determine the full declaration name for the
1167/// given Declarator.
1168DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1169 switch (D.getKind()) {
1170 case Declarator::DK_Abstract:
1171 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1172 return DeclarationName();
1173
1174 case Declarator::DK_Normal:
1175 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1176 return DeclarationName(D.getIdentifier());
1177
1178 case Declarator::DK_Constructor: {
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001179 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Douglas Gregor92751d42008-11-17 22:58:34 +00001180 Ty = Context.getCanonicalType(Ty);
1181 return Context.DeclarationNames.getCXXConstructorName(Ty);
1182 }
1183
1184 case Declarator::DK_Destructor: {
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001185 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
Douglas Gregor92751d42008-11-17 22:58:34 +00001186 Ty = Context.getCanonicalType(Ty);
1187 return Context.DeclarationNames.getCXXDestructorName(Ty);
1188 }
1189
1190 case Declarator::DK_Conversion: {
Douglas Gregor9817f4a2009-02-09 15:09:02 +00001191 // FIXME: We'd like to keep the non-canonical type for diagnostics!
Douglas Gregor92751d42008-11-17 22:58:34 +00001192 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1193 Ty = Context.getCanonicalType(Ty);
1194 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1195 }
Douglas Gregor163c5852008-11-18 14:39:36 +00001196
1197 case Declarator::DK_Operator:
1198 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1199 return Context.DeclarationNames.getCXXOperatorName(
1200 D.getOverloadedOperator());
Douglas Gregor92751d42008-11-17 22:58:34 +00001201 }
1202
1203 assert(false && "Unknown name kind");
1204 return DeclarationName();
1205}
1206
Douglas Gregor8af63e42009-02-06 17:46:57 +00001207/// isNearlyMatchingFunction - Determine whether the C++ functions
1208/// Declaration and Definition are "nearly" matching. This heuristic
1209/// is used to improve diagnostics in the case where an out-of-line
1210/// function definition doesn't match any declaration within
1211/// the class or namespace.
1212static bool isNearlyMatchingFunction(ASTContext &Context,
1213 FunctionDecl *Declaration,
1214 FunctionDecl *Definition) {
Douglas Gregorad590502008-12-15 23:53:10 +00001215 if (Declaration->param_size() != Definition->param_size())
1216 return false;
1217 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1218 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1219 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1220
1221 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1222 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1223 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1224 return false;
1225 }
1226
1227 return true;
1228}
1229
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00001230Sema::DeclTy *
Douglas Gregorad590502008-12-15 23:53:10 +00001231Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1232 bool IsFunctionDefinition) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001233 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor92751d42008-11-17 22:58:34 +00001234 DeclarationName Name = GetNameForDeclarator(D);
1235
Chris Lattner02c04392007-07-25 00:24:17 +00001236 // All of these full declarators require an identifier. If it doesn't have
1237 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor92751d42008-11-17 22:58:34 +00001238 if (!Name) {
Chris Lattner8c5dd732008-11-11 06:13:16 +00001239 if (!D.getInvalidType()) // Reject this if we think it is valid.
1240 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner3b054132008-11-19 05:08:23 +00001241 diag::err_declarator_need_ident)
1242 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner02c04392007-07-25 00:24:17 +00001243 return 0;
1244 }
1245
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001246 // The scope passed in may not be a decl scope. Zip up the scope tree until
1247 // we find one that is.
Douglas Gregor91f84212008-12-11 16:49:14 +00001248 while ((S->getFlags() & Scope::DeclScope) == 0 ||
Douglas Gregorded2d7b2009-02-04 19:02:06 +00001249 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner1a76a3c2007-08-26 06:24:45 +00001250 S = S->getParent();
1251
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001252 DeclContext *DC;
Douglas Gregor2ada0482009-02-04 17:27:36 +00001253 NamedDecl *PrevDecl;
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001254 NamedDecl *New;
Steve Narofff93b6722007-08-28 20:14:24 +00001255 bool InvalidDecl = false;
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001256
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001257 // See if this is a redefinition of a variable in the same scope.
Douglas Gregored8f2882009-01-30 01:04:22 +00001258 if (!D.getCXXScopeSpec().isSet() && !D.getCXXScopeSpec().isInvalid()) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001259 DC = CurContext;
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001260 PrevDecl = LookupName(S, Name, LookupOrdinaryName, true, true,
1261 D.getIdentifierLoc());
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001262 } else { // Something like "int foo::x;"
1263 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregorb9063fc2009-02-13 23:20:09 +00001264 PrevDecl = LookupQualifiedName(DC, Name, LookupOrdinaryName, true);
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001265
1266 // C++ 7.3.1.2p2:
1267 // Members (including explicit specializations of templates) of a named
1268 // namespace can also be defined outside that namespace by explicit
1269 // qualification of the name being defined, provided that the entity being
1270 // defined was already declared in the namespace and the definition appears
1271 // after the point of declaration in a namespace that encloses the
1272 // declarations namespace.
1273 //
Douglas Gregorad590502008-12-15 23:53:10 +00001274 // Note that we only check the context at this point. We don't yet
1275 // have enough information to make sure that PrevDecl is actually
1276 // the declaration we want to match. For example, given:
1277 //
Douglas Gregor4287b372008-12-12 08:25:50 +00001278 // class X {
1279 // void f();
Douglas Gregorad590502008-12-15 23:53:10 +00001280 // void f(float);
Douglas Gregor4287b372008-12-12 08:25:50 +00001281 // };
1282 //
Douglas Gregorad590502008-12-15 23:53:10 +00001283 // void X::f(int) { } // ill-formed
1284 //
1285 // In this case, PrevDecl will point to the overload set
1286 // containing the two f's declared in X, but neither of them
1287 // matches.
Douglas Gregor8af63e42009-02-06 17:46:57 +00001288
1289 // First check whether we named the global scope.
1290 if (isa<TranslationUnitDecl>(DC)) {
1291 Diag(D.getIdentifierLoc(), diag::err_invalid_declarator_global_scope)
1292 << Name << D.getCXXScopeSpec().getRange();
1293 } else if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001294 // The qualifying scope doesn't enclose the original declaration.
1295 // Emit diagnostic based on current scope.
1296 SourceLocation L = D.getIdentifierLoc();
1297 SourceRange R = D.getCXXScopeSpec().getRange();
Douglas Gregor8af63e42009-02-06 17:46:57 +00001298 if (isa<FunctionDecl>(CurContext))
Chris Lattnerf7e69d52008-11-23 20:28:15 +00001299 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Douglas Gregor8af63e42009-02-06 17:46:57 +00001300 else
Chris Lattnerf7e69d52008-11-23 20:28:15 +00001301 Diag(L, diag::err_invalid_declarator_scope)
Douglas Gregor8af63e42009-02-06 17:46:57 +00001302 << Name << cast<NamedDecl>(DC) << R;
Douglas Gregor91f84212008-12-11 16:49:14 +00001303 InvalidDecl = true;
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00001304 }
1305 }
1306
Douglas Gregor5daeee22008-12-08 18:40:42 +00001307 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00001308 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor4619e432008-12-05 23:32:09 +00001309 InvalidDecl = InvalidDecl
1310 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor5101c242008-12-05 18:15:24 +00001311 // Just pretend that we didn't see the previous declaration.
1312 PrevDecl = 0;
1313 }
1314
Douglas Gregor83a586e2008-04-13 21:07:44 +00001315 // In C++, the previous declaration we find might be a tag type
1316 // (class or enum). In this case, the new declaration will hide the
Douglas Gregorfb034662009-01-28 17:15:10 +00001317 // tag type. Note that this does does not apply if we're declaring a
1318 // typedef (C++ [dcl.typedef]p4).
1319 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1320 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor83a586e2008-04-13 21:07:44 +00001321 PrevDecl = 0;
1322
Chris Lattner07b201d2007-11-14 06:34:38 +00001323 QualType R = GetTypeForDeclarator(D, S);
1324 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1325
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001326 bool Redeclaration = false;
Chris Lattner01a7c532007-01-25 23:09:03 +00001327 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00001328 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001329 InvalidDecl, Redeclaration);
Chris Lattner07b201d2007-11-14 06:34:38 +00001330 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00001331 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001332 IsFunctionDefinition, InvalidDecl,
1333 Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00001334 } else {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00001335 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001336 InvalidDecl, Redeclaration);
Chris Lattner01a7c532007-01-25 23:09:03 +00001337 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00001338
1339 if (New == 0)
1340 return 0;
Chris Lattner302b4be2006-11-19 02:31:38 +00001341
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00001342 // Set the lexical context. If the declarator has a C++ scope specifier, the
1343 // lexical context will be different from the semantic context.
1344 New->setLexicalDeclContext(CurContext);
1345
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001346 // If this has an identifier and is not an invalid redeclaration,
1347 // add it to the scope stack.
1348 if (Name && !(Redeclaration && InvalidDecl))
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00001349 PushOnScopeChains(New, S);
Steve Narofff93b6722007-08-28 20:14:24 +00001350 // If any semantic error occurred, mark the decl as invalid.
1351 if (D.getInvalidType() || InvalidDecl)
1352 New->setInvalidDecl();
Chris Lattnere168f762006-11-10 05:29:30 +00001353
1354 return New;
1355}
1356
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001357NamedDecl*
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00001358Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001359 QualType R, Decl* LastDeclarator,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001360 Decl* PrevDecl, bool& InvalidDecl,
1361 bool &Redeclaration) {
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00001362 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1363 if (D.getCXXScopeSpec().isSet()) {
1364 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1365 << D.getCXXScopeSpec().getRange();
1366 InvalidDecl = true;
1367 // Pretend we didn't see the scope specifier.
1368 DC = 0;
1369 }
1370
1371 // Check that there are no default arguments (C++ only).
1372 if (getLangOptions().CPlusPlus)
1373 CheckExtraCXXDefaultArguments(D);
1374
1375 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1376 if (!NewTD) return 0;
1377
1378 // Handle attributes prior to checking for duplicates in MergeVarDecl
1379 ProcessDeclAttributes(NewTD, D);
1380 // Merge the decl with the existing one if appropriate. If the decl is
1381 // in an outer scope, it isn't the same thing.
1382 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001383 Redeclaration = true;
1384 if (MergeTypeDefDecl(NewTD, PrevDecl))
1385 InvalidDecl = true;
Zhongxing Xuac8ef9e2009-01-16 03:34:13 +00001386 }
1387
1388 if (S->getFnParent() == 0) {
1389 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1390 // then it shall have block scope.
1391 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1392 if (NewTD->getUnderlyingType()->isVariableArrayType())
1393 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1394 else
1395 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1396
1397 InvalidDecl = true;
1398 }
1399 }
1400 return NewTD;
1401}
1402
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001403NamedDecl*
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00001404Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001405 QualType R, Decl* LastDeclarator,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001406 Decl* PrevDecl, bool& InvalidDecl,
1407 bool &Redeclaration) {
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00001408 DeclarationName Name = GetNameForDeclarator(D);
1409
1410 // Check that there are no default arguments (C++ only).
1411 if (getLangOptions().CPlusPlus)
1412 CheckExtraCXXDefaultArguments(D);
1413
1414 if (R.getTypePtr()->isObjCInterfaceType()) {
1415 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1416 << D.getIdentifier();
1417 InvalidDecl = true;
1418 }
1419
1420 VarDecl *NewVD;
1421 VarDecl::StorageClass SC;
1422 switch (D.getDeclSpec().getStorageClassSpec()) {
1423 default: assert(0 && "Unknown storage class!");
1424 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1425 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1426 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1427 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1428 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1429 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1430 case DeclSpec::SCS_mutable:
1431 // mutable can only appear on non-static class members, so it's always
1432 // an error here
1433 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1434 InvalidDecl = true;
1435 SC = VarDecl::None;
1436 break;
1437 }
1438
1439 IdentifierInfo *II = Name.getAsIdentifierInfo();
1440 if (!II) {
1441 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1442 << Name.getAsString();
1443 return 0;
1444 }
1445
1446 if (DC->isRecord()) {
1447 // This is a static data member for a C++ class.
1448 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1449 D.getIdentifierLoc(), II,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001450 R);
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00001451 } else {
1452 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1453 if (S->getFnParent() == 0) {
1454 // C99 6.9p2: The storage-class specifiers auto and register shall not
1455 // appear in the declaration specifiers in an external declaration.
1456 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1457 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1458 InvalidDecl = true;
1459 }
1460 }
1461 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001462 II, R, SC,
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00001463 // FIXME: Move to DeclGroup...
1464 D.getDeclSpec().getSourceRange().getBegin());
1465 NewVD->setThreadSpecified(ThreadSpecified);
1466 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001467 NewVD->setNextDeclarator(LastDeclarator);
1468
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00001469 // Handle attributes prior to checking for duplicates in MergeVarDecl
1470 ProcessDeclAttributes(NewVD, D);
1471
1472 // Handle GNU asm-label extension (encoded as an attribute).
1473 if (Expr *E = (Expr*) D.getAsmLabel()) {
1474 // The parser guarantees this is a string.
1475 StringLiteral *SE = cast<StringLiteral>(E);
1476 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1477 SE->getByteLength())));
1478 }
1479
1480 // Emit an error if an address space was applied to decl with local storage.
1481 // This includes arrays of objects with address space qualifiers, but not
1482 // automatic variables that point to other address spaces.
1483 // ISO/IEC TR 18037 S5.1.2
1484 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1485 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1486 InvalidDecl = true;
1487 }
1488 // Merge the decl with the existing one if appropriate. If the decl is
1489 // in an outer scope, it isn't the same thing.
1490 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1491 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1492 // The user tried to define a non-static data member
1493 // out-of-line (C++ [dcl.meaning]p1).
1494 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1495 << D.getCXXScopeSpec().getRange();
1496 NewVD->Destroy(Context);
1497 return 0;
1498 }
1499
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001500 Redeclaration = true;
1501 if (MergeVarDecl(NewVD, PrevDecl))
1502 InvalidDecl = true;
Zhongxing Xu9b7714d2009-01-16 02:36:34 +00001503
1504 if (D.getCXXScopeSpec().isSet()) {
1505 // No previous declaration in the qualifying scope.
1506 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1507 << Name << D.getCXXScopeSpec().getRange();
1508 InvalidDecl = true;
1509 }
1510 }
1511 return NewVD;
1512}
1513
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001514NamedDecl*
Zhongxing Xubece5d62009-01-16 01:13:29 +00001515Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001516 QualType R, Decl *LastDeclarator,
Zhongxing Xubece5d62009-01-16 01:13:29 +00001517 Decl* PrevDecl, bool IsFunctionDefinition,
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001518 bool& InvalidDecl, bool &Redeclaration) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00001519 assert(R.getTypePtr()->isFunctionType());
1520
1521 DeclarationName Name = GetNameForDeclarator(D);
1522 FunctionDecl::StorageClass SC = FunctionDecl::None;
1523 switch (D.getDeclSpec().getStorageClassSpec()) {
1524 default: assert(0 && "Unknown storage class!");
1525 case DeclSpec::SCS_auto:
1526 case DeclSpec::SCS_register:
1527 case DeclSpec::SCS_mutable:
1528 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1529 InvalidDecl = true;
1530 break;
1531 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1532 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1533 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1534 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1535 }
1536
1537 bool isInline = D.getDeclSpec().isInlineSpecified();
1538 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1539 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1540
1541 FunctionDecl *NewFD;
1542 if (D.getKind() == Declarator::DK_Constructor) {
1543 // This is a C++ constructor declaration.
1544 assert(DC->isRecord() &&
1545 "Constructors can only be declared in a member context");
1546
1547 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1548
1549 // Create the new declaration
1550 NewFD = CXXConstructorDecl::Create(Context,
1551 cast<CXXRecordDecl>(DC),
1552 D.getIdentifierLoc(), Name, R,
1553 isExplicit, isInline,
1554 /*isImplicitlyDeclared=*/false);
1555
1556 if (InvalidDecl)
1557 NewFD->setInvalidDecl();
1558 } else if (D.getKind() == Declarator::DK_Destructor) {
1559 // This is a C++ destructor declaration.
1560 if (DC->isRecord()) {
1561 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1562
1563 NewFD = CXXDestructorDecl::Create(Context,
1564 cast<CXXRecordDecl>(DC),
1565 D.getIdentifierLoc(), Name, R,
1566 isInline,
1567 /*isImplicitlyDeclared=*/false);
1568
1569 if (InvalidDecl)
1570 NewFD->setInvalidDecl();
1571 } else {
1572 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1573
1574 // Create a FunctionDecl to satisfy the function definition parsing
1575 // code path.
1576 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001577 Name, R, SC, isInline,
Zhongxing Xubece5d62009-01-16 01:13:29 +00001578 // FIXME: Move to DeclGroup...
1579 D.getDeclSpec().getSourceRange().getBegin());
1580 InvalidDecl = true;
1581 NewFD->setInvalidDecl();
1582 }
1583 } else if (D.getKind() == Declarator::DK_Conversion) {
1584 if (!DC->isRecord()) {
1585 Diag(D.getIdentifierLoc(),
1586 diag::err_conv_function_not_member);
1587 return 0;
1588 } else {
1589 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1590
1591 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1592 D.getIdentifierLoc(), Name, R,
1593 isInline, isExplicit);
1594
1595 if (InvalidDecl)
1596 NewFD->setInvalidDecl();
1597 }
1598 } else if (DC->isRecord()) {
1599 // This is a C++ method declaration.
1600 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1601 D.getIdentifierLoc(), Name, R,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001602 (SC == FunctionDecl::Static), isInline);
Zhongxing Xubece5d62009-01-16 01:13:29 +00001603 } else {
1604 NewFD = FunctionDecl::Create(Context, DC,
1605 D.getIdentifierLoc(),
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001606 Name, R, SC, isInline,
Zhongxing Xubece5d62009-01-16 01:13:29 +00001607 // FIXME: Move to DeclGroup...
1608 D.getDeclSpec().getSourceRange().getBegin());
1609 }
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001610 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xubece5d62009-01-16 01:13:29 +00001611
1612 // Set the lexical context. If the declarator has a C++
1613 // scope specifier, the lexical context will be different
1614 // from the semantic context.
1615 NewFD->setLexicalDeclContext(CurContext);
1616
1617 // Handle GNU asm-label extension (encoded as an attribute).
1618 if (Expr *E = (Expr*) D.getAsmLabel()) {
1619 // The parser guarantees this is a string.
1620 StringLiteral *SE = cast<StringLiteral>(E);
1621 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1622 SE->getByteLength())));
1623 }
1624
1625 // Copy the parameter declarations from the declarator D to
1626 // the function declaration NewFD, if they are available.
1627 if (D.getNumTypeObjects() > 0) {
1628 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1629
1630 // Create Decl objects for each parameter, adding them to the
1631 // FunctionDecl.
1632 llvm::SmallVector<ParmVarDecl*, 16> Params;
1633
1634 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1635 // function that takes no arguments, not a function that takes a
1636 // single void argument.
1637 // We let through "const void" here because Sema::GetTypeForDeclarator
1638 // already checks for that case.
1639 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1640 FTI.ArgInfo[0].Param &&
1641 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1642 // empty arg list, don't push any params.
1643 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1644
1645 // In C++, the empty parameter-type-list must be spelled "void"; a
1646 // typedef of void is not permitted.
1647 if (getLangOptions().CPlusPlus &&
1648 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1649 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1650 }
1651 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1652 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1653 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1654 }
1655
1656 NewFD->setParams(Context, &Params[0], Params.size());
1657 } else if (R->getAsTypedefType()) {
1658 // When we're declaring a function with a typedef, as in the
1659 // following example, we'll need to synthesize (unnamed)
1660 // parameters for use in the declaration.
1661 //
1662 // @code
1663 // typedef void fn(int);
1664 // fn f;
1665 // @endcode
1666 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1667 if (!FT) {
1668 // This is a typedef of a function with no prototype, so we
1669 // don't need to do anything.
1670 } else if ((FT->getNumArgs() == 0) ||
1671 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1672 FT->getArgType(0)->isVoidType())) {
1673 // This is a zero-argument function. We don't need to do anything.
1674 } else {
1675 // Synthesize a parameter for each argument type.
1676 llvm::SmallVector<ParmVarDecl*, 16> Params;
1677 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1678 ArgType != FT->arg_type_end(); ++ArgType) {
1679 Params.push_back(ParmVarDecl::Create(Context, DC,
1680 SourceLocation(), 0,
1681 *ArgType, VarDecl::None,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00001682 0));
Zhongxing Xubece5d62009-01-16 01:13:29 +00001683 }
1684
1685 NewFD->setParams(Context, &Params[0], Params.size());
1686 }
1687 }
1688
1689 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1690 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1691 else if (isa<CXXDestructorDecl>(NewFD)) {
1692 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1693 Record->setUserDeclaredDestructor(true);
1694 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1695 // user-defined destructor.
1696 Record->setPOD(false);
1697 } else if (CXXConversionDecl *Conversion =
1698 dyn_cast<CXXConversionDecl>(NewFD))
1699 ActOnConversionDeclarator(Conversion);
1700
1701 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1702 if (NewFD->isOverloadedOperator() &&
1703 CheckOverloadedOperatorDeclaration(NewFD))
1704 NewFD->setInvalidDecl();
1705
1706 // Merge the decl with the existing one if appropriate. Since C functions
1707 // are in a flat namespace, make sure we consider decls in outer scopes.
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001708 bool OverloadableAttrRequired = false;
Zhongxing Xubece5d62009-01-16 01:13:29 +00001709 if (PrevDecl &&
1710 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001711 // Determine whether NewFD is an overload of PrevDecl or
Zhongxing Xubece5d62009-01-16 01:13:29 +00001712 // a declaration that requires merging. If it's an overload,
1713 // there's no more work to do here; we'll just add the new
1714 // function to the scope.
1715 OverloadedFunctionDecl::function_iterator MatchedDecl;
Douglas Gregor633b7372009-02-13 00:26:38 +00001716
1717 if (!getLangOptions().CPlusPlus &&
1718 AllowOverloadingOfFunction(PrevDecl, Context))
1719 OverloadableAttrRequired = true;
1720
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001721 if (!AllowOverloadingOfFunction(PrevDecl, Context) ||
Zhongxing Xubece5d62009-01-16 01:13:29 +00001722 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001723 Redeclaration = true;
Zhongxing Xubece5d62009-01-16 01:13:29 +00001724 Decl *OldDecl = PrevDecl;
1725
1726 // If PrevDecl was an overloaded function, extract the
1727 // FunctionDecl that matched.
1728 if (isa<OverloadedFunctionDecl>(PrevDecl))
1729 OldDecl = *MatchedDecl;
1730
1731 // NewFD and PrevDecl represent declarations that need to be
1732 // merged.
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001733 if (MergeFunctionDecl(NewFD, OldDecl))
1734 InvalidDecl = true;
Zhongxing Xubece5d62009-01-16 01:13:29 +00001735
Douglas Gregor75a45ba2009-02-16 17:45:42 +00001736 if (!InvalidDecl) {
Zhongxing Xubece5d62009-01-16 01:13:29 +00001737 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1738
1739 // An out-of-line member function declaration must also be a
1740 // definition (C++ [dcl.meaning]p1).
1741 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1742 !InvalidDecl) {
1743 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1744 << D.getCXXScopeSpec().getRange();
1745 NewFD->setInvalidDecl();
1746 }
1747 }
1748 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00001749 }
Zhongxing Xubece5d62009-01-16 01:13:29 +00001750
Douglas Gregor8af63e42009-02-06 17:46:57 +00001751 if (D.getCXXScopeSpec().isSet() &&
1752 (!PrevDecl || !Redeclaration)) {
1753 // The user tried to provide an out-of-line definition for a
1754 // function that is a member of a class or namespace, but there
1755 // was no such member function declared (C++ [class.mfct]p2,
1756 // C++ [namespace.memdef]p2). For example:
1757 //
1758 // class X {
1759 // void f() const;
1760 // };
1761 //
1762 // void X::f() { } // ill-formed
1763 //
1764 // Complain about this problem, and attempt to suggest close
1765 // matches (e.g., those that differ only in cv-qualifiers and
1766 // whether the parameter types are references).
Douglas Gregor8af63e42009-02-06 17:46:57 +00001767 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
Douglas Gregor706a6a92009-02-06 22:58:38 +00001768 << cast<NamedDecl>(DC) << D.getCXXScopeSpec().getRange();
Douglas Gregor8af63e42009-02-06 17:46:57 +00001769 InvalidDecl = true;
1770
1771 LookupResult Prev = LookupQualifiedName(DC, Name, LookupOrdinaryName,
1772 true);
1773 assert(!Prev.isAmbiguous() &&
1774 "Cannot have an ambiguity in previous-declaration lookup");
1775 for (LookupResult::iterator Func = Prev.begin(), FuncEnd = Prev.end();
1776 Func != FuncEnd; ++Func) {
1777 if (isa<FunctionDecl>(*Func) &&
1778 isNearlyMatchingFunction(Context, cast<FunctionDecl>(*Func), NewFD))
1779 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
Zhongxing Xubece5d62009-01-16 01:13:29 +00001780 }
Douglas Gregor8af63e42009-02-06 17:46:57 +00001781
1782 PrevDecl = 0;
Zhongxing Xubece5d62009-01-16 01:13:29 +00001783 }
Douglas Gregor0e8fc3c2009-02-02 21:35:47 +00001784
Zhongxing Xubece5d62009-01-16 01:13:29 +00001785 // Handle attributes. We need to have merged decls when handling attributes
1786 // (for example to check for conflicts, etc).
1787 ProcessDeclAttributes(NewFD, D);
Douglas Gregore711f702009-02-14 18:57:46 +00001788 AddKnownFunctionAttributes(NewFD);
Zhongxing Xubece5d62009-01-16 01:13:29 +00001789
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001790 if (OverloadableAttrRequired && !NewFD->getAttr<OverloadableAttr>()) {
1791 // If a function name is overloadable in C, then every function
1792 // with that name must be marked "overloadable".
1793 Diag(NewFD->getLocation(), diag::err_attribute_overloadable_missing)
Douglas Gregor633b7372009-02-13 00:26:38 +00001794 << Redeclaration << NewFD;
Douglas Gregor4e5cbdc2009-02-11 23:02:49 +00001795 if (PrevDecl)
1796 Diag(PrevDecl->getLocation(),
1797 diag::note_attribute_overloadable_prev_overload);
1798 NewFD->addAttr(new OverloadableAttr);
1799 }
1800
Zhongxing Xubece5d62009-01-16 01:13:29 +00001801 if (getLangOptions().CPlusPlus) {
Sebastian Redldf0913b2009-02-08 14:56:26 +00001802 // In C++, check default arguments now that we have merged decls. Unless
1803 // the lexical context is the class, because in this case this is done
1804 // during delayed parsing anyway.
1805 if (!CurContext->isRecord())
1806 CheckCXXDefaultArguments(NewFD);
Zhongxing Xubece5d62009-01-16 01:13:29 +00001807
1808 // An out-of-line member function declaration must also be a
1809 // definition (C++ [dcl.meaning]p1).
1810 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1811 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1812 << D.getCXXScopeSpec().getRange();
1813 InvalidDecl = true;
1814 }
1815 }
1816 return NewFD;
1817}
1818
Steve Naroffc6db58a2008-10-27 11:34:16 +00001819void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerf490e152008-11-19 05:27:50 +00001820 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1821 << Init->getSourceRange();
Steve Naroffc6db58a2008-10-27 11:34:16 +00001822}
1823
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001824bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1825 switch (Init->getStmtClass()) {
1826 default:
Steve Naroffc6db58a2008-10-27 11:34:16 +00001827 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001828 return true;
1829 case Expr::ParenExprClass: {
1830 const ParenExpr* PE = cast<ParenExpr>(Init);
1831 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1832 }
1833 case Expr::CompoundLiteralExprClass:
1834 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00001835 case Expr::DeclRefExprClass:
1836 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001837 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman86346ed2008-05-21 03:39:11 +00001838 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1839 if (VD->hasGlobalStorage())
1840 return false;
Steve Naroffc6db58a2008-10-27 11:34:16 +00001841 InitializerElementNotConstant(Init);
Eli Friedman86346ed2008-05-21 03:39:11 +00001842 return true;
1843 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001844 if (isa<FunctionDecl>(D))
1845 return false;
Steve Naroffc6db58a2008-10-27 11:34:16 +00001846 InitializerElementNotConstant(Init);
Steve Naroff98f72032008-01-10 22:15:12 +00001847 return true;
1848 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001849 case Expr::MemberExprClass: {
1850 const MemberExpr *M = cast<MemberExpr>(Init);
1851 if (M->isArrow())
1852 return CheckAddressConstantExpression(M->getBase());
1853 return CheckAddressConstantExpressionLValue(M->getBase());
1854 }
1855 case Expr::ArraySubscriptExprClass: {
1856 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1857 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1858 return CheckAddressConstantExpression(ASE->getBase()) ||
1859 CheckArithmeticConstantExpression(ASE->getIdx());
1860 }
1861 case Expr::StringLiteralClass:
Chris Lattner6307f192008-08-10 01:53:14 +00001862 case Expr::PredefinedExprClass:
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001863 return false;
1864 case Expr::UnaryOperatorClass: {
1865 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1866
1867 // C99 6.6p9
1868 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman86346ed2008-05-21 03:39:11 +00001869 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001870
Steve Naroffc6db58a2008-10-27 11:34:16 +00001871 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001872 return true;
1873 }
1874 }
1875}
1876
1877bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1878 switch (Init->getStmtClass()) {
1879 default:
Steve Naroffc6db58a2008-10-27 11:34:16 +00001880 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001881 return true;
Chris Lattnera97132a2008-10-06 07:26:43 +00001882 case Expr::ParenExprClass:
1883 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001884 case Expr::StringLiteralClass:
1885 case Expr::ObjCStringLiteralClass:
1886 return false;
Chris Lattnera97132a2008-10-06 07:26:43 +00001887 case Expr::CallExprClass:
Douglas Gregor993603d2008-11-14 16:09:21 +00001888 case Expr::CXXOperatorCallExprClass:
Chris Lattnera97132a2008-10-06 07:26:43 +00001889 // __builtin___CFStringMakeConstantString is a valid constant l-value.
Douglas Gregore711f702009-02-14 18:57:46 +00001890 if (cast<CallExpr>(Init)->isBuiltinCall(Context) ==
Chris Lattnera97132a2008-10-06 07:26:43 +00001891 Builtin::BI__builtin___CFStringMakeConstantString)
1892 return false;
1893
Steve Naroffc6db58a2008-10-27 11:34:16 +00001894 InitializerElementNotConstant(Init);
Chris Lattnera97132a2008-10-06 07:26:43 +00001895 return true;
1896
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001897 case Expr::UnaryOperatorClass: {
1898 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1899
1900 // C99 6.6p9
1901 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1902 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1903
1904 if (Exp->getOpcode() == UnaryOperator::Extension)
1905 return CheckAddressConstantExpression(Exp->getSubExpr());
1906
Steve Naroffc6db58a2008-10-27 11:34:16 +00001907 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001908 return true;
1909 }
1910 case Expr::BinaryOperatorClass: {
1911 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1912 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1913
1914 Expr *PExp = Exp->getLHS();
1915 Expr *IExp = Exp->getRHS();
1916 if (IExp->getType()->isPointerType())
1917 std::swap(PExp, IExp);
1918
1919 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1920 return CheckAddressConstantExpression(PExp) ||
1921 CheckArithmeticConstantExpression(IExp);
1922 }
Eli Friedman0a2ba3f2008-08-25 20:46:57 +00001923 case Expr::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00001924 case Expr::CStyleCastExprClass: {
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001925 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman0a2ba3f2008-08-25 20:46:57 +00001926 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1927 // Check for implicit promotion
1928 if (SubExpr->getType()->isFunctionType() ||
1929 SubExpr->getType()->isArrayType())
1930 return CheckAddressConstantExpressionLValue(SubExpr);
1931 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001932
1933 // Check for pointer->pointer cast
1934 if (SubExpr->getType()->isPointerType())
1935 return CheckAddressConstantExpression(SubExpr);
1936
Eli Friedman0a2ba3f2008-08-25 20:46:57 +00001937 if (SubExpr->getType()->isIntegralType()) {
1938 // Check for the special-case of a pointer->int->pointer cast;
1939 // this isn't standard, but some code requires it. See
1940 // PR2720 for an example.
1941 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1942 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1943 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1944 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1945 if (IntWidth >= PointerWidth) {
1946 return CheckAddressConstantExpression(SubCast->getSubExpr());
1947 }
1948 }
1949 }
1950 }
1951 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001952 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman0a2ba3f2008-08-25 20:46:57 +00001953 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001954
Steve Naroffc6db58a2008-10-27 11:34:16 +00001955 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001956 return true;
1957 }
1958 case Expr::ConditionalOperatorClass: {
1959 // FIXME: Should we pedwarn here?
1960 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1961 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroffc6db58a2008-10-27 11:34:16 +00001962 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00001963 return true;
1964 }
1965 if (CheckArithmeticConstantExpression(Exp->getCond()))
1966 return true;
1967 if (Exp->getLHS() &&
1968 CheckAddressConstantExpression(Exp->getLHS()))
1969 return true;
1970 return CheckAddressConstantExpression(Exp->getRHS());
1971 }
1972 case Expr::AddrLabelExprClass:
1973 return false;
1974 }
1975}
1976
Eli Friedmane6e0f232008-06-09 05:05:07 +00001977static const Expr* FindExpressionBaseAddress(const Expr* E);
1978
1979static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1980 switch (E->getStmtClass()) {
1981 default:
1982 return E;
1983 case Expr::ParenExprClass: {
1984 const ParenExpr* PE = cast<ParenExpr>(E);
1985 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1986 }
1987 case Expr::MemberExprClass: {
1988 const MemberExpr *M = cast<MemberExpr>(E);
1989 if (M->isArrow())
1990 return FindExpressionBaseAddress(M->getBase());
1991 return FindExpressionBaseAddressLValue(M->getBase());
1992 }
1993 case Expr::ArraySubscriptExprClass: {
1994 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1995 return FindExpressionBaseAddress(ASE->getBase());
1996 }
1997 case Expr::UnaryOperatorClass: {
1998 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1999
2000 if (Exp->getOpcode() == UnaryOperator::Deref)
2001 return FindExpressionBaseAddress(Exp->getSubExpr());
2002
2003 return E;
2004 }
2005 }
2006}
2007
2008static const Expr* FindExpressionBaseAddress(const Expr* E) {
2009 switch (E->getStmtClass()) {
2010 default:
2011 return E;
2012 case Expr::ParenExprClass: {
2013 const ParenExpr* PE = cast<ParenExpr>(E);
2014 return FindExpressionBaseAddress(PE->getSubExpr());
2015 }
2016 case Expr::UnaryOperatorClass: {
2017 const UnaryOperator *Exp = cast<UnaryOperator>(E);
2018
2019 // C99 6.6p9
2020 if (Exp->getOpcode() == UnaryOperator::AddrOf)
2021 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
2022
2023 if (Exp->getOpcode() == UnaryOperator::Extension)
2024 return FindExpressionBaseAddress(Exp->getSubExpr());
2025
2026 return E;
2027 }
2028 case Expr::BinaryOperatorClass: {
2029 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2030
2031 Expr *PExp = Exp->getLHS();
2032 Expr *IExp = Exp->getRHS();
2033 if (IExp->getType()->isPointerType())
2034 std::swap(PExp, IExp);
2035
2036 return FindExpressionBaseAddress(PExp);
2037 }
2038 case Expr::ImplicitCastExprClass: {
2039 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2040
2041 // Check for implicit promotion
2042 if (SubExpr->getType()->isFunctionType() ||
2043 SubExpr->getType()->isArrayType())
2044 return FindExpressionBaseAddressLValue(SubExpr);
2045
2046 // Check for pointer->pointer cast
2047 if (SubExpr->getType()->isPointerType())
2048 return FindExpressionBaseAddress(SubExpr);
2049
2050 // We assume that we have an arithmetic expression here;
2051 // if we don't, we'll figure it out later
2052 return 0;
2053 }
Douglas Gregorf19b2312008-10-28 15:36:24 +00002054 case Expr::CStyleCastExprClass: {
Eli Friedmane6e0f232008-06-09 05:05:07 +00002055 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2056
2057 // Check for pointer->pointer cast
2058 if (SubExpr->getType()->isPointerType())
2059 return FindExpressionBaseAddress(SubExpr);
2060
2061 // We assume that we have an arithmetic expression here;
2062 // if we don't, we'll figure it out later
2063 return 0;
2064 }
2065 }
2066}
2067
Anders Carlsson59689ed2008-11-22 21:04:56 +00002068bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002069 switch (Init->getStmtClass()) {
2070 default:
Steve Naroffc6db58a2008-10-27 11:34:16 +00002071 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002072 return true;
2073 case Expr::ParenExprClass: {
2074 const ParenExpr* PE = cast<ParenExpr>(Init);
2075 return CheckArithmeticConstantExpression(PE->getSubExpr());
2076 }
2077 case Expr::FloatingLiteralClass:
2078 case Expr::IntegerLiteralClass:
2079 case Expr::CharacterLiteralClass:
2080 case Expr::ImaginaryLiteralClass:
2081 case Expr::TypesCompatibleExprClass:
2082 case Expr::CXXBoolLiteralExprClass:
2083 return false;
Douglas Gregor993603d2008-11-14 16:09:21 +00002084 case Expr::CallExprClass:
2085 case Expr::CXXOperatorCallExprClass: {
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002086 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattnercb136912008-10-06 06:49:02 +00002087
2088 // Allow any constant foldable calls to builtins.
Douglas Gregore711f702009-02-14 18:57:46 +00002089 if (CE->isBuiltinCall(Context) && CE->isEvaluatable(Context))
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002090 return false;
Chris Lattnercb136912008-10-06 06:49:02 +00002091
Steve Naroffc6db58a2008-10-27 11:34:16 +00002092 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002093 return true;
2094 }
Douglas Gregorc7acfdf2009-01-06 05:10:23 +00002095 case Expr::DeclRefExprClass:
2096 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002097 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2098 if (isa<EnumConstantDecl>(D))
2099 return false;
Steve Naroffc6db58a2008-10-27 11:34:16 +00002100 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002101 return true;
2102 }
2103 case Expr::CompoundLiteralExprClass:
2104 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2105 // but vectors are allowed to be magic.
2106 if (Init->getType()->isVectorType())
2107 return false;
Steve Naroffc6db58a2008-10-27 11:34:16 +00002108 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002109 return true;
2110 case Expr::UnaryOperatorClass: {
2111 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2112
2113 switch (Exp->getOpcode()) {
2114 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2115 // See C99 6.6p3.
2116 default:
Steve Naroffc6db58a2008-10-27 11:34:16 +00002117 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002118 return true;
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002119 case UnaryOperator::OffsetOf:
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002120 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2121 return false;
Steve Naroffc6db58a2008-10-27 11:34:16 +00002122 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002123 return true;
2124 case UnaryOperator::Extension:
2125 case UnaryOperator::LNot:
2126 case UnaryOperator::Plus:
2127 case UnaryOperator::Minus:
2128 case UnaryOperator::Not:
2129 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2130 }
2131 }
Sebastian Redl6f282892008-11-11 17:56:53 +00002132 case Expr::SizeOfAlignOfExprClass: {
2133 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002134 // Special check for void types, which are allowed as an extension
Sebastian Redl6f282892008-11-11 17:56:53 +00002135 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002136 return false;
2137 // alignof always evaluates to a constant.
2138 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl6f282892008-11-11 17:56:53 +00002139 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroffc6db58a2008-10-27 11:34:16 +00002140 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002141 return true;
2142 }
2143 return false;
2144 }
2145 case Expr::BinaryOperatorClass: {
2146 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2147
2148 if (Exp->getLHS()->getType()->isArithmeticType() &&
2149 Exp->getRHS()->getType()->isArithmeticType()) {
2150 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2151 CheckArithmeticConstantExpression(Exp->getRHS());
2152 }
2153
Eli Friedmane6e0f232008-06-09 05:05:07 +00002154 if (Exp->getLHS()->getType()->isPointerType() &&
2155 Exp->getRHS()->getType()->isPointerType()) {
2156 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2157 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2158
2159 // Only allow a null (constant integer) base; we could
2160 // allow some additional cases if necessary, but this
2161 // is sufficient to cover offsetof-like constructs.
2162 if (!LHSBase && !RHSBase) {
2163 return CheckAddressConstantExpression(Exp->getLHS()) ||
2164 CheckAddressConstantExpression(Exp->getRHS());
2165 }
2166 }
2167
Steve Naroffc6db58a2008-10-27 11:34:16 +00002168 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002169 return true;
2170 }
2171 case Expr::ImplicitCastExprClass:
Douglas Gregorf19b2312008-10-28 15:36:24 +00002172 case Expr::CStyleCastExprClass: {
Nuno Lopes7cffb632009-02-02 22:57:15 +00002173 const CastExpr *CE = cast<CastExpr>(Init);
2174 const Expr *SubExpr = CE->getSubExpr();
2175
Eli Friedman4c55e2c2008-09-01 22:08:17 +00002176 if (SubExpr->getType()->isArithmeticType())
2177 return CheckArithmeticConstantExpression(SubExpr);
2178
Eli Friedmande09ce02008-09-02 09:37:00 +00002179 if (SubExpr->getType()->isPointerType()) {
2180 const Expr* Base = FindExpressionBaseAddress(SubExpr);
Nuno Lopes7cffb632009-02-02 22:57:15 +00002181 if (Base) {
2182 // the cast is only valid if done to a wide enough type
2183 if (Context.getTypeSize(CE->getType()) >=
2184 Context.getTypeSize(SubExpr->getType()))
2185 return false;
2186 } else {
2187 // If the pointer has a null base, this is an offsetof-like construct
2188 return CheckAddressConstantExpression(SubExpr);
2189 }
Eli Friedmande09ce02008-09-02 09:37:00 +00002190 }
2191
Steve Naroffc6db58a2008-10-27 11:34:16 +00002192 InitializerElementNotConstant(Init);
Eli Friedman4c55e2c2008-09-01 22:08:17 +00002193 return true;
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002194 }
2195 case Expr::ConditionalOperatorClass: {
2196 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattnerc4346752008-10-06 05:42:39 +00002197
2198 // If GNU extensions are disabled, we require all operands to be arithmetic
2199 // constant expressions.
2200 if (getLangOptions().NoExtensions) {
2201 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2202 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2203 CheckArithmeticConstantExpression(Exp->getRHS());
2204 }
2205
2206 // Otherwise, we have to emulate some of the behavior of fold here.
2207 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2208 // because it can constant fold things away. To retain compatibility with
2209 // GCC code, we see if we can fold the condition to a constant (which we
2210 // should always be able to do in theory). If so, we only require the
2211 // specified arm of the conditional to be a constant. This is a horrible
2212 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002213 Expr::EvalResult EvalResult;
2214 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2215 EvalResult.HasSideEffects) {
Chris Lattner67d7b922008-11-16 21:24:15 +00002216 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattnerc4346752008-10-06 05:42:39 +00002217 // won't be able to either. Use it to emit the diagnostic though.
2218 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner67d7b922008-11-16 21:24:15 +00002219 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattnerc4346752008-10-06 05:42:39 +00002220 return Res;
2221 }
2222
2223 // Verify that the side following the condition is also a constant.
2224 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson6736d1a22008-12-19 20:58:05 +00002225 if (EvalResult.Val.getInt() == 0)
Chris Lattnerc4346752008-10-06 05:42:39 +00002226 std::swap(TrueSide, FalseSide);
2227
2228 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002229 return true;
Chris Lattnerc4346752008-10-06 05:42:39 +00002230
2231 // Okay, the evaluated side evaluates to a constant, so we accept this.
2232 // Check to see if the other side is obviously not a constant. If so,
2233 // emit a warning that this is a GNU extension.
Chris Lattnercb136912008-10-06 06:49:02 +00002234 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattnerc4346752008-10-06 05:42:39 +00002235 Diag(Init->getExprLoc(),
Chris Lattnerf490e152008-11-19 05:27:50 +00002236 diag::ext_typecheck_expression_not_constant_but_accepted)
2237 << FalseSide->getSourceRange();
Chris Lattnerc4346752008-10-06 05:42:39 +00002238 return false;
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002239 }
2240 }
2241}
2242
2243bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregore4a0bb72009-01-22 00:58:24 +00002244 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2245 Init = DIE->getInit();
2246
Nuno Lopes7bfa1802008-07-07 16:46:50 +00002247 Init = Init->IgnoreParens();
2248
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00002249 if (Init->isEvaluatable(Context))
Anders Carlsson1e495d92008-12-05 05:09:56 +00002250 return false;
2251
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002252 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2253 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2254 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2255
Nuno Lopes7bfa1802008-07-07 16:46:50 +00002256 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2257 return CheckForConstantInitializer(e->getInitializer(), DclT);
2258
Douglas Gregor0202cb42009-01-29 17:44:32 +00002259 if (isa<ImplicitValueInitExpr>(Init)) {
2260 // FIXME: In C++, check for non-POD types.
2261 return false;
2262 }
2263
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002264 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2265 unsigned numInits = Exp->getNumInits();
2266 for (unsigned i = 0; i < numInits; i++) {
2267 // FIXME: Need to get the type of the declaration for C++,
2268 // because it could be a reference?
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002269
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002270 if (CheckForConstantInitializer(Exp->getInit(i),
2271 Exp->getInit(i)->getType()))
2272 return true;
2273 }
2274 return false;
2275 }
2276
Anders Carlsson1e495d92008-12-05 05:09:56 +00002277 // FIXME: We can probably remove some of this code below, now that
2278 // Expr::Evaluate is doing the heavy lifting for scalars.
2279
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002280 if (Init->isNullPointerConstant(Context))
2281 return false;
2282 if (Init->getType()->isArithmeticType()) {
Chris Lattner574dee62008-07-26 22:17:49 +00002283 QualType InitTy = Context.getCanonicalType(Init->getType())
2284 .getUnqualifiedType();
Eli Friedman66572af2008-05-30 18:14:48 +00002285 if (InitTy == Context.BoolTy) {
2286 // Special handling for pointers implicitly cast to bool;
2287 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2288 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2289 Expr* SubE = ICE->getSubExpr();
2290 if (SubE->getType()->isPointerType() ||
2291 SubE->getType()->isArrayType() ||
2292 SubE->getType()->isFunctionType()) {
2293 return CheckAddressConstantExpression(Init);
2294 }
2295 }
2296 } else if (InitTy->isIntegralType()) {
2297 Expr* SubE = 0;
Argyrios Kyrtzidis3bab3d22008-08-18 23:01:59 +00002298 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman66572af2008-05-30 18:14:48 +00002299 SubE = CE->getSubExpr();
2300 // Special check for pointer cast to int; we allow as an extension
2301 // an address constant cast to an integer if the integer
2302 // is of an appropriate width (this sort of code is apparently used
2303 // in some places).
2304 // FIXME: Add pedwarn?
2305 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2306 if (SubE && (SubE->getType()->isPointerType() ||
2307 SubE->getType()->isArrayType() ||
2308 SubE->getType()->isFunctionType())) {
2309 unsigned IntWidth = Context.getTypeSize(Init->getType());
2310 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2311 if (IntWidth >= PointerWidth)
2312 return CheckAddressConstantExpression(Init);
2313 }
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002314 }
2315
2316 return CheckArithmeticConstantExpression(Init);
2317 }
2318
2319 if (Init->getType()->isPointerType())
2320 return CheckAddressConstantExpression(Init);
2321
Eli Friedman66572af2008-05-30 18:14:48 +00002322 // An array type at the top level that isn't an init-list must
2323 // be a string literal
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002324 if (Init->getType()->isArrayType())
2325 return false;
2326
Nuno Lopes2c5208c2008-09-01 18:42:41 +00002327 if (Init->getType()->isFunctionType())
2328 return false;
2329
Steve Naroffd40a3962008-10-02 17:12:56 +00002330 // Allow block exprs at top level.
2331 if (Init->getType()->isBlockPointerType())
2332 return false;
Nuno Lopes6be29392009-01-15 16:44:45 +00002333
2334 // GCC cast to union extension
2335 // note: the validity of the cast expr is checked by CheckCastTypes()
2336 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2337 QualType T = C->getType();
2338 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2339 }
2340
Steve Naroffc6db58a2008-10-27 11:34:16 +00002341 InitializerElementNotConstant(Init);
Eli Friedmand5a55bd2008-05-20 13:48:25 +00002342 return true;
Steve Naroff98f72032008-01-10 22:15:12 +00002343}
2344
Sebastian Redlc675bab2008-12-13 16:23:55 +00002345void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor5fb53972009-01-14 15:45:31 +00002346 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2347}
2348
2349/// AddInitializerToDecl - Adds the initializer Init to the
2350/// declaration dcl. If DirectInit is true, this is C++ direct
2351/// initialization rather than copy initialization.
2352void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff437b4d82007-09-12 20:13:48 +00002353 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redlc675bab2008-12-13 16:23:55 +00002354 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner8beb9de2007-10-19 20:10:30 +00002355 assert(Init && "missing initializer");
Steve Naroff61091402007-09-12 14:07:44 +00002356
Chris Lattner8beb9de2007-10-19 20:10:30 +00002357 // If there is no declaration, there was an error parsing it. Just ignore
2358 // the initializer.
2359 if (RealDecl == 0) {
Ted Kremenek5a201952009-02-07 01:47:29 +00002360 Init->Destroy(Context);
Chris Lattner8beb9de2007-10-19 20:10:30 +00002361 return;
2362 }
Steve Naroff61091402007-09-12 14:07:44 +00002363
Steve Naroff437b4d82007-09-12 20:13:48 +00002364 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2365 if (!VDecl) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002366 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff437b4d82007-09-12 20:13:48 +00002367 RealDecl->setInvalidDecl();
2368 return;
2369 }
Steve Naroff61091402007-09-12 14:07:44 +00002370 // Get the decls type and save a reference for later, since
Steve Naroff98f72032008-01-10 22:15:12 +00002371 // CheckInitializerTypes may change it.
Steve Naroff437b4d82007-09-12 20:13:48 +00002372 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff08899ff2008-04-15 22:42:06 +00002373 if (VDecl->isBlockVarDecl()) {
2374 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff61091402007-09-12 14:07:44 +00002375 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff437b4d82007-09-12 20:13:48 +00002376 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00002377 VDecl->setInvalidDecl();
2378 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6f543152008-11-05 15:29:30 +00002379 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002380 VDecl->getDeclName(), DirectInit))
Steve Naroff08899ff2008-04-15 22:42:06 +00002381 VDecl->setInvalidDecl();
Anders Carlsson41e08812008-08-22 05:00:02 +00002382
2383 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2384 if (!getLangOptions().CPlusPlus) {
2385 if (SC == VarDecl::Static) // C99 6.7.8p4.
2386 CheckForConstantInitializer(Init, DclT);
2387 }
Steve Naroff61091402007-09-12 14:07:44 +00002388 }
Steve Naroff08899ff2008-04-15 22:42:06 +00002389 } else if (VDecl->isFileVarDecl()) {
2390 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff437b4d82007-09-12 20:13:48 +00002391 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff08899ff2008-04-15 22:42:06 +00002392 if (!VDecl->isInvalidDecl())
Douglas Gregor6f543152008-11-05 15:29:30 +00002393 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor5fb53972009-01-14 15:45:31 +00002394 VDecl->getDeclName(), DirectInit))
Steve Naroff08899ff2008-04-15 22:42:06 +00002395 VDecl->setInvalidDecl();
Steve Naroff98f72032008-01-10 22:15:12 +00002396
Anders Carlsson41e08812008-08-22 05:00:02 +00002397 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2398 if (!getLangOptions().CPlusPlus) {
2399 // C99 6.7.8p4. All file scoped initializers need to be constant.
2400 CheckForConstantInitializer(Init, DclT);
2401 }
Steve Naroff61091402007-09-12 14:07:44 +00002402 }
2403 // If the type changed, it means we had an incomplete type that was
2404 // completed by the initializer. For example:
2405 // int ary[] = { 1, 3, 5 };
2406 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00002407 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff437b4d82007-09-12 20:13:48 +00002408 VDecl->setType(DclT);
Christopher Lamb2ed9afd2007-11-29 19:09:19 +00002409 Init->setType(DclT);
2410 }
Steve Naroff61091402007-09-12 14:07:44 +00002411
2412 // Attach the initializer to the decl.
Steve Naroff437b4d82007-09-12 20:13:48 +00002413 VDecl->setInit(Init);
Steve Naroff61091402007-09-12 14:07:44 +00002414 return;
2415}
2416
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002417void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2418 Decl *RealDecl = static_cast<Decl *>(dcl);
2419
Argyrios Kyrtzidis6709e7d2008-11-07 13:01:22 +00002420 // If there is no declaration, there was an error parsing it. Just ignore it.
2421 if (RealDecl == 0)
2422 return;
2423
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002424 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2425 QualType Type = Var->getType();
2426 // C++ [dcl.init.ref]p3:
2427 // The initializer can be omitted for a reference only in a
2428 // parameter declaration (8.3.5), in the declaration of a
2429 // function return type, in the declaration of a class member
2430 // within its class declaration (9.2), and where the extern
2431 // specifier is explicitly used.
Douglas Gregor1349b452008-12-15 21:24:18 +00002432 if (Type->isReferenceType() &&
2433 Var->getStorageClass() != VarDecl::Extern &&
2434 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner29e812b2008-11-20 06:06:08 +00002435 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002436 << Var->getDeclName()
2437 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc28b57d2008-11-03 20:45:27 +00002438 Var->setInvalidDecl();
2439 return;
2440 }
2441
2442 // C++ [dcl.init]p9:
2443 //
2444 // If no initializer is specified for an object, and the object
2445 // is of (possibly cv-qualified) non-POD class type (or array
2446 // thereof), the object shall be default-initialized; if the
2447 // object is of const-qualified type, the underlying class type
2448 // shall have a user-declared default constructor.
2449 if (getLangOptions().CPlusPlus) {
2450 QualType InitType = Type;
2451 if (const ArrayType *Array = Context.getAsArrayType(Type))
2452 InitType = Array->getElementType();
Douglas Gregor1349b452008-12-15 21:24:18 +00002453 if (Var->getStorageClass() != VarDecl::Extern &&
2454 Var->getStorageClass() != VarDecl::PrivateExtern &&
2455 InitType->isRecordType()) {
Douglas Gregor6f543152008-11-05 15:29:30 +00002456 const CXXConstructorDecl *Constructor
2457 = PerformInitializationByConstructor(InitType, 0, 0,
2458 Var->getLocation(),
2459 SourceRange(Var->getLocation(),
2460 Var->getLocation()),
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002461 Var->getDeclName(),
Douglas Gregor6f543152008-11-05 15:29:30 +00002462 IK_Default);
Douglas Gregorc28b57d2008-11-03 20:45:27 +00002463 if (!Constructor)
2464 Var->setInvalidDecl();
2465 }
2466 }
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002467
Douglas Gregor9774aa12008-10-29 13:50:18 +00002468#if 0
2469 // FIXME: Temporarily disabled because we are not properly parsing
2470 // linkage specifications on declarations, e.g.,
2471 //
2472 // extern "C" const CGPoint CGPointerZero;
2473 //
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002474 // C++ [dcl.init]p9:
2475 //
2476 // If no initializer is specified for an object, and the
2477 // object is of (possibly cv-qualified) non-POD class type (or
2478 // array thereof), the object shall be default-initialized; if
2479 // the object is of const-qualified type, the underlying class
2480 // type shall have a user-declared default
2481 // constructor. Otherwise, if no initializer is specified for
2482 // an object, the object and its subobjects, if any, have an
2483 // indeterminate initial value; if the object or any of its
2484 // subobjects are of const-qualified type, the program is
2485 // ill-formed.
2486 //
2487 // This isn't technically an error in C, so we don't diagnose it.
2488 //
2489 // FIXME: Actually perform the POD/user-defined default
2490 // constructor check.
2491 if (getLangOptions().CPlusPlus &&
Douglas Gregor9774aa12008-10-29 13:50:18 +00002492 Context.getCanonicalType(Type).isConstQualified() &&
2493 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner651d42d2008-11-20 06:38:18 +00002494 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2495 << Var->getName()
2496 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor9774aa12008-10-29 13:50:18 +00002497#endif
Douglas Gregor8e1cf602008-10-29 00:13:59 +00002498 }
2499}
2500
Chris Lattner776fac82007-06-09 00:53:06 +00002501/// The declarators are chained together backwards, reverse the list.
2502Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2503 // Often we have single declarators, handle them quickly.
Steve Naroffa23cc792007-09-13 23:52:58 +00002504 Decl *GroupDecl = static_cast<Decl*>(group);
2505 if (GroupDecl == 0)
Steve Naroff61091402007-09-12 14:07:44 +00002506 return 0;
Steve Naroffa23cc792007-09-13 23:52:58 +00002507
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002508 Decl *Group = dyn_cast<Decl>(GroupDecl);
2509 Decl *NewGroup = 0;
Steve Naroff61091402007-09-12 14:07:44 +00002510 if (Group->getNextDeclarator() == 0)
Chris Lattner776fac82007-06-09 00:53:06 +00002511 NewGroup = Group;
Steve Naroff61091402007-09-12 14:07:44 +00002512 else { // reverse the list.
2513 while (Group) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002514 Decl *Next = Group->getNextDeclarator();
Steve Naroff61091402007-09-12 14:07:44 +00002515 Group->setNextDeclarator(NewGroup);
2516 NewGroup = Group;
2517 Group = Next;
2518 }
2519 }
2520 // Perform semantic analysis that depends on having fully processed both
2521 // the declarator and initializer.
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002522 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff61091402007-09-12 14:07:44 +00002523 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2524 if (!IDecl)
2525 continue;
Steve Naroff61091402007-09-12 14:07:44 +00002526 QualType T = IDecl->getType();
2527
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00002528 if (T->isVariableArrayType()) {
Anders Carlsson5d985f52008-12-20 21:51:53 +00002529 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlssona1a9c282008-12-07 00:49:48 +00002530
2531 // FIXME: This won't give the correct result for
2532 // int a[10][n];
2533 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00002534 if (IDecl->isFileVarDecl()) {
Anders Carlssona1a9c282008-12-07 00:49:48 +00002535 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2536 SizeRange;
2537
Eli Friedmanbd258282008-02-15 18:16:39 +00002538 IDecl->setInvalidDecl();
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00002539 } else {
2540 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2541 // static storage duration, it shall not have a variable length array.
2542 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssona1a9c282008-12-07 00:49:48 +00002543 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2544 << SizeRange;
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00002545 IDecl->setInvalidDecl();
2546 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssona1a9c282008-12-07 00:49:48 +00002547 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2548 << SizeRange;
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00002549 IDecl->setInvalidDecl();
2550 }
2551 }
2552 } else if (T->isVariablyModifiedType()) {
2553 if (IDecl->isFileVarDecl()) {
2554 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2555 IDecl->setInvalidDecl();
2556 } else {
2557 if (IDecl->getStorageClass() == VarDecl::Extern) {
2558 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2559 IDecl->setInvalidDecl();
2560 }
Steve Naroff61091402007-09-12 14:07:44 +00002561 }
2562 }
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00002563
Steve Naroff61091402007-09-12 14:07:44 +00002564 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2565 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff08899ff2008-04-15 22:42:06 +00002566 if (IDecl->isBlockVarDecl() &&
2567 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregordd430f72009-01-19 19:26:10 +00002568 if (!IDecl->isInvalidDecl() &&
2569 DiagnoseIncompleteType(IDecl->getLocation(), T,
2570 diag::err_typecheck_decl_incomplete_type))
Steve Naroff61091402007-09-12 14:07:44 +00002571 IDecl->setInvalidDecl();
Steve Naroff61091402007-09-12 14:07:44 +00002572 }
2573 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2574 // object that has file scope without an initializer, and without a
2575 // storage-class specifier or with the storage-class specifier "static",
2576 // constitutes a tentative definition. Note: A tentative definition with
2577 // external linkage is valid (C99 6.2.2p5).
Steve Naroff5bb8f222008-08-08 17:50:35 +00002578 if (isTentativeDefinition(IDecl)) {
Eli Friedman9e805b22008-02-15 12:53:51 +00002579 if (T->isIncompleteArrayType()) {
Steve Naroffacb6fa62008-01-18 20:40:52 +00002580 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2581 // array to be completed. Don't issue a diagnostic.
Douglas Gregordd430f72009-01-19 19:26:10 +00002582 } else if (!IDecl->isInvalidDecl() &&
2583 DiagnoseIncompleteType(IDecl->getLocation(), T,
2584 diag::err_typecheck_decl_incomplete_type))
Steve Naroffacb6fa62008-01-18 20:40:52 +00002585 // C99 6.9.2p3: If the declaration of an identifier for an object is
2586 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2587 // declared type shall not be an incomplete type.
Steve Naroff61091402007-09-12 14:07:44 +00002588 IDecl->setInvalidDecl();
Steve Naroff61091402007-09-12 14:07:44 +00002589 }
Steve Naroff5bb8f222008-08-08 17:50:35 +00002590 if (IDecl->isFileVarDecl())
2591 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner776fac82007-06-09 00:53:06 +00002592 }
2593 return NewGroup;
2594}
Steve Naroff7e6f7c22007-08-28 03:03:08 +00002595
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002596/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2597/// to introduce parameters into function prototype scope.
2598Sema::DeclTy *
2599Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattnercf31de32008-06-26 06:49:43 +00002600 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorad590502008-12-15 23:53:10 +00002601
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002602 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar0ff41922008-09-03 21:54:21 +00002603 VarDecl::StorageClass StorageClass = VarDecl::None;
2604 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2605 StorageClass = VarDecl::Register;
2606 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002607 Diag(DS.getStorageClassSpecLoc(),
2608 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00002609 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002610 }
2611 if (DS.isThreadSpecified()) {
2612 Diag(DS.getThreadSpecLoc(),
2613 diag::err_invalid_storage_class_in_func_decl);
Chris Lattnercf31de32008-06-26 06:49:43 +00002614 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002615 }
2616
Douglas Gregorcaa8ace2008-05-07 04:49:29 +00002617 // Check that there are no default arguments inside the type of this
2618 // parameter (C++ only).
2619 if (getLangOptions().CPlusPlus)
2620 CheckExtraCXXDefaultArguments(D);
2621
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002622 // In this context, we *do not* check D.getInvalidType(). If the declarator
2623 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2624 // though it will not reflect the user specified type.
2625 QualType parmDeclType = GetTypeForDeclarator(D, S);
2626
2627 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2628
Chris Lattnerc284e9b2007-01-23 05:14:32 +00002629 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2630 // Can this happen for params? We already checked that they don't conflict
2631 // among each other. Here they can only shadow globals, which is ok.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002632 IdentifierInfo *II = D.getIdentifier();
Chris Lattnerd9773512009-01-21 02:38:50 +00002633 if (II) {
Douglas Gregor2ada0482009-02-04 17:27:36 +00002634 if (NamedDecl *PrevDecl = LookupName(S, II, LookupOrdinaryName)) {
Chris Lattnerd9773512009-01-21 02:38:50 +00002635 if (PrevDecl->isTemplateParameter()) {
2636 // Maybe we will complain about the shadowed template parameter.
2637 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2638 // Just pretend that we didn't see the previous declaration.
2639 PrevDecl = 0;
2640 } else if (S->isDeclScope(PrevDecl)) {
2641 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002642
Chris Lattnerd9773512009-01-21 02:38:50 +00002643 // Recover by removing the name
2644 II = 0;
2645 D.SetIdentifier(0, D.getIdentifierLoc());
2646 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002647 }
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002648 }
Steve Naroff773df5c2007-08-07 22:44:21 +00002649
2650 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2651 // Doing the promotion here has a win and a loss. The win is the type for
2652 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2653 // code generator). The loss is the orginal type isn't preserved. For example:
2654 //
2655 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2656 // int blockvardecl[5];
2657 // sizeof(parmvardecl); // size == 4
2658 // sizeof(blockvardecl); // size == 20
2659 // }
2660 //
2661 // For expressions, all implicit conversions are captured using the
2662 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2663 //
2664 // FIXME: If a source translation tool needs to see the original type, then
2665 // we need to consider storing both types (in ParmVarDecl)...
2666 //
Chris Lattnera21ad802008-04-02 05:18:44 +00002667 if (parmDeclType->isArrayType()) {
Chris Lattner4f203512008-01-02 22:50:48 +00002668 // int x[restrict 4] -> int *restrict
Chris Lattnera21ad802008-04-02 05:18:44 +00002669 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner4f203512008-01-02 22:50:48 +00002670 } else if (parmDeclType->isFunctionType())
Steve Naroff773df5c2007-08-07 22:44:21 +00002671 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor91f84212008-12-11 16:49:14 +00002672
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002673 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2674 D.getIdentifierLoc(), II,
Daniel Dunbar0ff41922008-09-03 21:54:21 +00002675 parmDeclType, StorageClass,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002676 0);
Anders Carlsson1a841062008-02-15 07:04:12 +00002677
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002678 if (D.getInvalidType())
Steve Naroffcf871f52007-08-28 18:45:29 +00002679 New->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00002680
Douglas Gregorad590502008-12-15 23:53:10 +00002681 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2682 if (D.getCXXScopeSpec().isSet()) {
2683 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2684 << D.getCXXScopeSpec().getRange();
2685 New->setInvalidDecl();
2686 }
2687
Douglas Gregor91f84212008-12-11 16:49:14 +00002688 // Add the parameter declaration into this scope.
2689 S->AddDecl(New);
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00002690 if (II)
Douglas Gregor91f84212008-12-11 16:49:14 +00002691 IdResolver.AddDecl(New);
Nate Begemand8c41562008-02-17 21:20:31 +00002692
Chris Lattner2727d1b2008-06-29 00:02:00 +00002693 ProcessDeclAttributes(New, D);
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002694 return New;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002695
Chris Lattnerc5cdf4d2007-01-21 07:42:07 +00002696}
Fariborz Jahanian56ff1462007-11-08 23:49:49 +00002697
Douglas Gregor9aa89042009-01-23 16:23:13 +00002698void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00002699 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2700 "Not a function declarator!");
2701 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002702
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00002703 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2704 // for a K&R function.
2705 if (!FTI.hasPrototype) {
2706 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002707 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002708 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2709 << FTI.ArgInfo[i].Ident;
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00002710 // Implicitly declare the argument as type 'int' for lack of a better
2711 // type.
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002712 DeclSpec DS;
2713 const char* PrevSpec; // unused
2714 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2715 PrevSpec);
2716 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2717 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregor9aa89042009-01-23 16:23:13 +00002718 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00002719 }
2720 }
Douglas Gregor9aa89042009-01-23 16:23:13 +00002721 }
2722}
2723
2724Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2725 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2726 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2727 "Not a function declarator!");
2728 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2729
2730 if (FTI.hasPrototype) {
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002731 // FIXME: Diagnose arguments without names in C.
Chris Lattner5c5fbcc2006-12-03 08:41:30 +00002732 }
2733
Douglas Gregorad590502008-12-15 23:53:10 +00002734 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff012484d2008-01-14 20:51:29 +00002735
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002736 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorad590502008-12-15 23:53:10 +00002737 ActOnDeclarator(ParentScope, D, 0,
2738 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00002739}
2740
2741Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2742 Decl *decl = static_cast<Decl*>(D);
Chris Lattner27055192008-02-16 01:20:36 +00002743 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00002744
2745 // See if this is a redefinition.
2746 const FunctionDecl *Definition;
2747 if (FD->getBody(Definition)) {
Chris Lattnere3d20d92008-11-23 21:45:46 +00002748 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner0369c572008-11-23 23:12:31 +00002749 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregorcad304ba2008-10-29 15:10:40 +00002750 }
2751
Douglas Gregor75a45ba2009-02-16 17:45:42 +00002752 // Builtin functions cannot be defined.
2753 if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
2754 if (Context.BuiltinInfo.isPredefinedLibFunction(BuiltinID)) {
2755 Diag(FD->getLocation(), diag::err_builtin_lib_definition) << FD;
2756 Diag(FD->getLocation(), diag::note_builtin_lib_def_freestanding);
2757 } else
2758 Diag(FD->getLocation(), diag::err_builtin_definition) << FD;
2759 FD->setInvalidDecl();
2760 }
2761
Douglas Gregor91f84212008-12-11 16:49:14 +00002762 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00002763
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002764 // Check the validity of our function parameters
2765 CheckParmsForFunctionDef(FD);
2766
2767 // Introduce our parameters into the function scope
2768 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2769 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregorc72e6452009-01-09 18:51:29 +00002770 Param->setOwningFunction(FD);
2771
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002772 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00002773 if (Param->getIdentifier())
2774 PushOnScopeChains(Param, FnBodyScope);
Chris Lattnerf61c8a82007-01-21 19:04:43 +00002775 }
Chris Lattneraa9c7ae2008-04-08 04:40:51 +00002776
Anton Korobeynikovd72f47a2008-12-26 00:52:02 +00002777 // Checking attributes of current function definition
2778 // dllimport attribute.
2779 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2780 // dllimport attribute cannot be applied to definition.
2781 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2782 Diag(FD->getLocation(),
2783 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2784 << "dllimport";
2785 FD->setInvalidDecl();
2786 return FD;
2787 } else {
2788 // If a symbol previously declared dllimport is later defined, the
2789 // attribute is ignored in subsequent references, and a warning is
2790 // emitted.
2791 Diag(FD->getLocation(),
2792 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2793 << FD->getNameAsCString() << "dllimport";
2794 }
2795 }
Chris Lattnere168f762006-11-10 05:29:30 +00002796 return FD;
2797}
2798
Sebastian Redlc675bab2008-12-13 16:23:55 +00002799Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffb313fc32007-11-11 23:20:51 +00002800 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redlc675bab2008-12-13 16:23:55 +00002801 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff542cd5d2008-07-25 17:57:26 +00002802 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redlc675bab2008-12-13 16:23:55 +00002803 FD->setBody(Body);
Argyrios Kyrtzidis853fbea2008-06-28 06:07:14 +00002804 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff542cd5d2008-07-25 17:57:26 +00002805 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffb313fc32007-11-11 23:20:51 +00002806 MD->setBody((Stmt*)Body);
Ted Kremenek5a201952009-02-07 01:47:29 +00002807 } else {
2808 Body->Destroy(Context);
Steve Naroff542cd5d2008-07-25 17:57:26 +00002809 return 0;
Ted Kremenek5a201952009-02-07 01:47:29 +00002810 }
Chris Lattner0a5ff0d2008-04-06 04:47:34 +00002811 PopDeclContext();
Chris Lattnere2473062007-05-28 06:28:18 +00002812 // Verify and clean out per-function state.
2813
2814 // Check goto/label use.
Chris Lattner23b7eb62007-06-15 23:05:46 +00002815 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2816 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
Chris Lattnere2473062007-05-28 06:28:18 +00002817 // Verify that we have no forward references left. If so, there was a goto
2818 // or address of a label taken, but no definition of it. Label fwd
2819 // definitions are indicated with a null substmt.
2820 if (I->second->getSubStmt() == 0) {
2821 LabelStmt *L = I->second;
2822 // Emit error.
Chris Lattner651d42d2008-11-20 06:38:18 +00002823 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattnere2473062007-05-28 06:28:18 +00002824
2825 // At this point, we have gotos that use the bogus label. Stitch it into
2826 // the function body so that they aren't leaked and that the AST is well
2827 // formed.
Chris Lattner3efff542008-01-25 00:01:10 +00002828 if (Body) {
Ted Kremenek5a201952009-02-07 01:47:29 +00002829#if 0
2830 // FIXME: Why do this? Having a 'push_back' in CompoundStmt is ugly,
2831 // and the AST is malformed anyway. We should just blow away 'L'.
2832 L->setSubStmt(new (Context) NullStmt(L->getIdentLoc()));
2833 cast<CompoundStmt>(Body)->push_back(L);
2834#else
2835 L->Destroy(Context);
2836#endif
Chris Lattner3efff542008-01-25 00:01:10 +00002837 } else {
2838 // The whole function wasn't parsed correctly, just delete this.
Ted Kremenek5a201952009-02-07 01:47:29 +00002839 L->Destroy(Context);
Chris Lattner3efff542008-01-25 00:01:10 +00002840 }
Chris Lattnere2473062007-05-28 06:28:18 +00002841 }
2842 }
2843 LabelMap.clear();
2844
Steve Naroffb313fc32007-11-11 23:20:51 +00002845 return D;
Fariborz Jahanian85e1d0d2007-11-10 16:31:34 +00002846}
2847
Chris Lattnerac18be92006-11-20 06:49:47 +00002848/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2849/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002850NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2851 IdentifierInfo &II, Scope *S) {
Chris Lattner00e26072008-05-05 21:18:06 +00002852 // Extension in C99. Legal in C90, but warn about it.
2853 if (getLangOptions().C99)
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002854 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner00e26072008-05-05 21:18:06 +00002855 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00002856 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattnerac18be92006-11-20 06:49:47 +00002857
2858 // FIXME: handle stuff like:
2859 // void foo() { extern float X(); }
2860 // void bar() { X(); } <-- implicit decl for X in another scope.
2861
2862 // Set a Declarator for the implicit definition: int foo();
Chris Lattner353f5742006-11-28 04:50:12 +00002863 const char *Dummy;
Chris Lattnerac18be92006-11-20 06:49:47 +00002864 DeclSpec DS;
Chris Lattnerb20e8942006-11-28 05:30:29 +00002865 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
Chris Lattnerb055f2d2007-02-11 08:19:57 +00002866 Error = Error; // Silence warning.
Chris Lattner353f5742006-11-28 04:50:12 +00002867 assert(!Error && "Error setting up implicit decl!");
Chris Lattnerac18be92006-11-20 06:49:47 +00002868 Declarator D(DS, Declarator::BlockContext);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002869 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D),
2870 SourceLocation());
Chris Lattnerac18be92006-11-20 06:49:47 +00002871 D.SetIdentifier(&II, Loc);
Sebastian Redlf6591ca2009-02-09 18:23:29 +00002872
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00002873 // Insert this function into translation-unit scope.
2874
2875 DeclContext *PrevDC = CurContext;
2876 CurContext = Context.getTranslationUnitDecl();
2877
Steve Naroff3913ea42008-04-04 14:32:09 +00002878 FunctionDecl *FD =
Daniel Dunbar1ff1d1f2008-08-05 16:28:08 +00002879 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff3913ea42008-04-04 14:32:09 +00002880 FD->setImplicit();
Argyrios Kyrtzidis694dda12008-05-01 21:04:16 +00002881
2882 CurContext = PrevDC;
2883
Douglas Gregore711f702009-02-14 18:57:46 +00002884 AddKnownFunctionAttributes(FD);
2885
Steve Naroff3913ea42008-04-04 14:32:09 +00002886 return FD;
Chris Lattnerac18be92006-11-20 06:49:47 +00002887}
2888
Douglas Gregore711f702009-02-14 18:57:46 +00002889/// \brief Adds any function attributes that we know a priori based on
2890/// the declaration of this function.
2891///
2892/// These attributes can apply both to implicitly-declared builtins
2893/// (like __builtin___printf_chk) or to library-declared functions
2894/// like NSLog or printf.
2895void Sema::AddKnownFunctionAttributes(FunctionDecl *FD) {
2896 if (FD->isInvalidDecl())
2897 return;
2898
2899 // If this is a built-in function, map its builtin attributes to
2900 // actual attributes.
2901 if (unsigned BuiltinID = FD->getBuiltinID(Context)) {
2902 // Handle printf-formatting attributes.
2903 unsigned FormatIdx;
2904 bool HasVAListArg;
2905 if (Context.BuiltinInfo.isPrintfLike(BuiltinID, FormatIdx, HasVAListArg)) {
2906 if (!FD->getAttr<FormatAttr>())
2907 FD->addAttr(new FormatAttr("printf", FormatIdx + 1, FormatIdx + 2));
2908 }
2909 }
2910
2911 IdentifierInfo *Name = FD->getIdentifier();
2912 if (!Name)
2913 return;
2914 if ((!getLangOptions().CPlusPlus &&
2915 FD->getDeclContext()->isTranslationUnit()) ||
2916 (isa<LinkageSpecDecl>(FD->getDeclContext()) &&
2917 cast<LinkageSpecDecl>(FD->getDeclContext())->getLanguage() ==
2918 LinkageSpecDecl::lang_c)) {
2919 // Okay: this could be a libc/libm/Objective-C function we know
2920 // about.
2921 } else
2922 return;
2923
2924 unsigned KnownID;
2925 for (KnownID = 0; KnownID != id_num_known_functions; ++KnownID)
2926 if (KnownFunctionIDs[KnownID] == Name)
2927 break;
2928
2929 switch (KnownID) {
2930 case id_NSLog:
2931 case id_NSLogv:
2932 if (const FormatAttr *Format = FD->getAttr<FormatAttr>()) {
2933 // FIXME: We known better than our headers.
2934 const_cast<FormatAttr *>(Format)->setType("printf");
2935 } else
2936 FD->addAttr(new FormatAttr("printf", 1, 2));
2937 break;
2938
2939 case id_asprintf:
2940 case id_vasprintf:
2941 if (!FD->getAttr<FormatAttr>())
2942 FD->addAttr(new FormatAttr("printf", 2, 3));
2943 break;
2944
2945 default:
2946 // Unknown function or known function without any attributes to
2947 // add. Do nothing.
2948 break;
2949 }
2950}
Chris Lattner302b4be2006-11-19 02:31:38 +00002951
Chris Lattner07b201d2007-11-14 06:34:38 +00002952TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002953 Decl *LastDeclarator) {
Chris Lattner776fac82007-06-09 00:53:06 +00002954 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Narofff93b6722007-08-28 20:14:24 +00002955 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner0d8b1a12006-11-20 04:34:45 +00002956
Chris Lattner18b19622007-01-22 07:39:13 +00002957 // Scope manipulation handled by caller.
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002958 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2959 D.getIdentifierLoc(),
Chris Lattnera7b32872008-03-15 06:12:44 +00002960 D.getIdentifier(),
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002961 T);
2962 NewTD->setNextDeclarator(LastDeclarator);
Steve Narofff93b6722007-08-28 20:14:24 +00002963 if (D.getInvalidType())
2964 NewTD->setInvalidDecl();
2965 return NewTD;
Chris Lattnere168f762006-11-10 05:29:30 +00002966}
2967
Steve Naroff30d242c2007-09-15 18:49:24 +00002968/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner1300fb92007-01-23 23:42:53 +00002969/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregordee1be82009-01-17 00:42:38 +00002970/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Chris Lattner1300fb92007-01-23 23:42:53 +00002971/// reference/declaration/definition of a tag.
Douglas Gregordee1be82009-01-17 00:42:38 +00002972Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidis32a03792008-11-08 16:45:02 +00002973 SourceLocation KWLoc, const CXXScopeSpec &SS,
2974 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorcd72ba92009-02-06 22:42:48 +00002975 AttributeList *Attr) {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00002976 // If this is not a definition, it must have a name.
Chris Lattner7b9ace62007-01-23 20:11:08 +00002977 assert((Name != 0 || TK == TK_Definition) &&
2978 "Nameless record must be a definition!");
Douglas Gregorded2d7b2009-02-04 19:02:06 +00002979
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002980 TagDecl::TagKind Kind;
Douglas Gregordee1be82009-01-17 00:42:38 +00002981 switch (TagSpec) {
Chris Lattnerf34c4da2007-01-23 04:08:05 +00002982 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002983 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2984 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2985 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2986 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattnerf34c4da2007-01-23 04:08:05 +00002987 }
Chris Lattner7e783a12007-01-23 02:05:42 +00002988
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00002989 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00002990 DeclContext *DC = CurContext;
Douglas Gregor2ada0482009-02-04 17:27:36 +00002991 NamedDecl *PrevDecl = 0;
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00002992
Douglas Gregordee1be82009-01-17 00:42:38 +00002993 bool Invalid = false;
2994
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00002995 if (Name && SS.isNotEmpty()) {
2996 // We have a nested-name tag ('struct foo::bar').
2997
2998 // Check for invalid 'foo::'.
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00002999 if (SS.isInvalid()) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00003000 Name = 0;
3001 goto CreateNewDecl;
3002 }
3003
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00003004 DC = static_cast<DeclContext*>(SS.getScopeRep());
Douglas Gregor8761da52009-02-03 00:34:39 +00003005 SearchDC = DC;
Argyrios Kyrtzidis8ad00b22008-11-09 22:53:32 +00003006 // Look-up name inside 'foo::'.
Steve Naroffdcfe56d2009-01-29 00:07:50 +00003007 PrevDecl = dyn_cast_or_null<TagDecl>(
Douglas Gregor889ceb72009-02-03 19:21:40 +00003008 LookupQualifiedName(DC, Name, LookupTagName, true).getAsDecl());
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00003009
3010 // A tag 'foo::bar' must already exist.
3011 if (PrevDecl == 0) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003012 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00003013 Name = 0;
3014 goto CreateNewDecl;
3015 }
Chris Lattnerd9773512009-01-21 02:38:50 +00003016 } else if (Name) {
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00003017 // If this is a named struct, check to see if there was a previous forward
3018 // declaration or definition.
Douglas Gregor889ceb72009-02-03 19:21:40 +00003019 // FIXME: We're looking into outer scopes here, even when we
3020 // shouldn't be. Doing so can result in ambiguities that we
3021 // shouldn't be diagnosing.
Douglas Gregor4489e942009-02-03 19:26:08 +00003022 LookupResult R = LookupName(S, Name, LookupTagName,
3023 /*RedeclarationOnly=*/(TK != TK_Reference));
Douglas Gregor889ceb72009-02-03 19:21:40 +00003024 if (R.isAmbiguous()) {
3025 DiagnoseAmbiguousLookup(R, Name, NameLoc);
3026 // FIXME: This is not best way to recover from case like:
3027 //
3028 // struct S s;
3029 //
3030 // causes needless err_ovl_no_viable_function_in_init latter.
3031 Name = 0;
3032 PrevDecl = 0;
3033 Invalid = true;
3034 }
3035 else
Douglas Gregor2ada0482009-02-04 17:27:36 +00003036 PrevDecl = R;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003037
3038 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
3039 // FIXME: This makes sure that we ignore the contexts associated
3040 // with C structs, unions, and enums when looking for a matching
3041 // tag declaration or definition. See the similar lookup tweak
Douglas Gregored8f2882009-01-30 01:04:22 +00003042 // in Sema::LookupName; is there a better way to deal with this?
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003043 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
3044 SearchDC = SearchDC->getParent();
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003045 }
Argyrios Kyrtzidise02eb2b2008-11-09 22:09:58 +00003046 }
3047
Douglas Gregor5daeee22008-12-08 18:40:42 +00003048 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003049 // Maybe we will complain about the shadowed template parameter.
3050 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
3051 // Just pretend that we didn't see the previous declaration.
3052 PrevDecl = 0;
3053 }
3054
Ted Kremenekceb3ca92008-09-02 21:26:19 +00003055 if (PrevDecl) {
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003056 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00003057 // If this is a use of a previous tag, or if the tag is already declared
3058 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003059 // rementions the tag), reuse the decl.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003060 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner9ff58d72008-07-03 03:30:58 +00003061 // Make sure that this wasn't declared as an enum and now used as a
3062 // struct or something similar.
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003063 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003064 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00003065 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner9ff58d72008-07-03 03:30:58 +00003066 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003067 Name = 0;
Chris Lattner9ff58d72008-07-03 03:30:58 +00003068 PrevDecl = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00003069 Invalid = true;
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003070 } else {
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003071 // If this is a use, just return the declaration we found.
Chris Lattner9ff58d72008-07-03 03:30:58 +00003072
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003073 // FIXME: In the future, return a variant or some other clue
3074 // for the consumer of this Decl to know it doesn't own it.
3075 // For our current ASTs this shouldn't be a problem, but will
3076 // need to be changed with DeclGroups.
3077 if (TK == TK_Reference)
Chris Lattner9ff58d72008-07-03 03:30:58 +00003078 return PrevDecl;
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003079
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003080 // Diagnose attempts to redefine a tag.
3081 if (TK == TK_Definition) {
3082 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
3083 Diag(NameLoc, diag::err_redefinition) << Name;
3084 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregordee1be82009-01-17 00:42:38 +00003085 // If this is a redefinition, recover by making this
3086 // struct be anonymous, which will make any later
3087 // references get the previous definition.
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003088 Name = 0;
3089 PrevDecl = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00003090 Invalid = true;
3091 } else {
3092 // If the type is currently being defined, complain
3093 // about a nested redefinition.
3094 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
3095 if (Tag->isBeingDefined()) {
3096 Diag(NameLoc, diag::err_nested_redefinition) << Name;
3097 Diag(PrevTagDecl->getLocation(),
3098 diag::note_previous_definition);
3099 Name = 0;
3100 PrevDecl = 0;
3101 Invalid = true;
3102 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003103 }
Douglas Gregordee1be82009-01-17 00:42:38 +00003104
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003105 // Okay, this is definition of a previously declared or referenced
3106 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregordee1be82009-01-17 00:42:38 +00003107 }
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003108 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003109 // If we get here we have (another) forward declaration or we
3110 // have a definition. Just create a new decl.
3111 } else {
3112 // If we get here, this is a definition of a new tag type in a nested
3113 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
3114 // new decl/type. We set PrevDecl to NULL so that the entities
3115 // have distinct types.
3116 PrevDecl = 0;
Chris Lattner7b9ace62007-01-23 20:11:08 +00003117 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003118 // If we get here, we're going to create a new Decl. If PrevDecl
3119 // is non-NULL, it's a definition of the tag declared by
3120 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis08114892008-04-27 13:50:30 +00003121 } else {
Douglas Gregorfb034662009-01-28 17:15:10 +00003122 // PrevDecl is a namespace, template, or anything else
3123 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003124 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremenek3060d982008-09-03 18:03:35 +00003125 // The tag name clashes with a namespace name, issue an error and
3126 // recover by making this tag be anonymous.
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003127 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner0369c572008-11-23 23:12:31 +00003128 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00003129 Name = 0;
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003130 PrevDecl = 0;
Douglas Gregordee1be82009-01-17 00:42:38 +00003131 Invalid = true;
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003132 } else {
3133 // The existing declaration isn't relevant to us; we're in a
3134 // new scope, so clear out the previous declaration.
3135 PrevDecl = 0;
Argyrios Kyrtzidis7da34d02008-07-16 07:45:46 +00003136 }
Chris Lattner8799cf22007-01-23 01:57:16 +00003137 }
Douglas Gregor658b9552009-01-09 22:42:13 +00003138 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3139 (Kind != TagDecl::TK_enum)) {
3140 // C++ [basic.scope.pdecl]p5:
3141 // -- for an elaborated-type-specifier of the form
3142 //
3143 // class-key identifier
3144 //
3145 // if the elaborated-type-specifier is used in the
3146 // decl-specifier-seq or parameter-declaration-clause of a
3147 // function defined in namespace scope, the identifier is
3148 // declared as a class-name in the namespace that contains
3149 // the declaration; otherwise, except as a friend
3150 // declaration, the identifier is declared in the smallest
3151 // non-class, non-function-prototype scope that contains the
3152 // declaration.
3153 //
3154 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3155 // C structs and unions.
3156
3157 // Find the context where we'll be declaring the tag.
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003158 // FIXME: We would like to maintain the current DeclContext as the
3159 // lexical context,
Douglas Gregor8761da52009-02-03 00:34:39 +00003160 while (SearchDC->isRecord())
3161 SearchDC = SearchDC->getParent();
Douglas Gregor658b9552009-01-09 22:42:13 +00003162
3163 // Find the scope where we'll be declaring the tag.
3164 while (S->isClassScope() ||
3165 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor45a33ec2009-01-12 18:45:55 +00003166 ((S->getFlags() & Scope::DeclScope) == 0) ||
3167 (S->getEntity() &&
3168 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor658b9552009-01-09 22:42:13 +00003169 S = S->getParent();
Chris Lattner18b19622007-01-22 07:39:13 +00003170 }
Argyrios Kyrtzidis16ac9be2008-11-08 17:17:31 +00003171
Chris Lattner438e5012008-12-17 07:13:27 +00003172CreateNewDecl:
Chris Lattner18b19622007-01-22 07:39:13 +00003173
Chris Lattnerbf0b7982007-01-23 04:27:41 +00003174 // If there is an identifier, use the location of the identifier as the
3175 // location of the decl, otherwise use the location of the struct/union
3176 // keyword.
3177 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3178
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003179 // Otherwise, create a new declaration. If there is a previous
3180 // declaration of the same entity, the two will be linked via
3181 // PrevDecl.
Chris Lattner7b9ace62007-01-23 20:11:08 +00003182 TagDecl *New;
Douglas Gregor9ac7a072009-01-07 00:43:41 +00003183
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003184 if (Kind == TagDecl::TK_enum) {
Chris Lattner776fac82007-06-09 00:53:06 +00003185 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3186 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor8761da52009-02-03 00:34:39 +00003187 New = EnumDecl::Create(Context, SearchDC, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003188 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner5f521502007-01-25 06:27:24 +00003189 // If this is an undefined enum, warn.
Chris Lattnerc1915e22007-01-25 07:29:02 +00003190 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003191 } else {
3192 // struct/union/class
3193
Chris Lattner776fac82007-06-09 00:53:06 +00003194 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3195 // struct X { int A; } D; D should chain to X.
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003196 if (getLangOptions().CPlusPlus)
Ted Kremenek6ddf53e2008-09-05 17:39:33 +00003197 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor8761da52009-02-03 00:34:39 +00003198 New = CXXRecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003199 cast_or_null<CXXRecordDecl>(PrevDecl));
Douglas Gregorcd72ba92009-02-06 22:42:48 +00003200 else
Douglas Gregor8761da52009-02-03 00:34:39 +00003201 New = RecordDecl::Create(Context, Kind, SearchDC, Loc, Name,
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003202 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003203 }
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003204
3205 if (Kind != TagDecl::TK_enum) {
3206 // Handle #pragma pack: if the #pragma pack stack has non-default
3207 // alignment, make up a packed attribute for this decl. These
3208 // attributes are checked when the ASTContext lays out the
3209 // structure.
3210 //
3211 // It is important for implementing the correct semantics that this
3212 // happen here (in act on tag decl). The #pragma pack stack is
3213 // maintained as a result of parser callbacks which can occur at
3214 // many points during the parsing of a struct declaration (because
3215 // the #pragma tokens are effectively skipped over during the
3216 // parsing of the struct).
3217 if (unsigned Alignment = PackContext.getAlignment())
3218 New->addAttr(new PackedAttr(Alignment * 8));
3219 }
3220
Douglas Gregorfb034662009-01-28 17:15:10 +00003221 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3222 // C++ [dcl.typedef]p3:
3223 // [...] Similarly, in a given scope, a class or enumeration
3224 // shall not be declared with the same name as a typedef-name
3225 // that is declared in that scope and refers to a type other
3226 // than the class or enumeration itself.
Douglas Gregored8f2882009-01-30 01:04:22 +00003227 LookupResult Lookup = LookupName(S, Name, LookupOrdinaryName, true);
Douglas Gregorfb034662009-01-28 17:15:10 +00003228 TypedefDecl *PrevTypedef = 0;
3229 if (Lookup.getKind() == LookupResult::Found)
3230 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3231
3232 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3233 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3234 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3235 Diag(Loc, diag::err_tag_definition_of_typedef)
3236 << Context.getTypeDeclType(New)
3237 << PrevTypedef->getUnderlyingType();
3238 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3239 Invalid = true;
3240 }
3241 }
3242
Douglas Gregordee1be82009-01-17 00:42:38 +00003243 if (Invalid)
3244 New->setInvalidDecl();
3245
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003246 if (Attr)
3247 ProcessDeclAttributeList(New, Attr);
3248
Douglas Gregordee1be82009-01-17 00:42:38 +00003249 // If we're declaring or defining a tag in function prototype scope
3250 // in C, note that this type can only be used within the function.
Douglas Gregor658b9552009-01-09 22:42:13 +00003251 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3252 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3253
Douglas Gregorc811d8f2008-12-15 16:32:14 +00003254 // Set the lexical context. If the tag has a C++ scope specifier, the
3255 // lexical context will be different from the semantic context.
Douglas Gregor8761da52009-02-03 00:34:39 +00003256 New->setLexicalDeclContext(CurContext);
Douglas Gregordee1be82009-01-17 00:42:38 +00003257
3258 if (TK == TK_Definition)
3259 New->startDefinition();
Chris Lattner18b19622007-01-22 07:39:13 +00003260
3261 // If this has an identifier, add it to the scope stack.
3262 if (Name) {
Douglas Gregor45a33ec2009-01-12 18:45:55 +00003263 S = getNonFieldDeclScope(S);
Douglas Gregor8761da52009-02-03 00:34:39 +00003264 PushOnScopeChains(New, S);
Douglas Gregorc6f58fe2009-01-12 22:49:06 +00003265 } else {
Douglas Gregor8761da52009-02-03 00:34:39 +00003266 CurContext->addDecl(New);
Chris Lattner18b19622007-01-22 07:39:13 +00003267 }
Argyrios Kyrtzidis9e59b572008-11-09 23:41:00 +00003268
Chris Lattner18b19622007-01-22 07:39:13 +00003269 return New;
3270}
Chris Lattner1300fb92007-01-23 23:42:53 +00003271
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003272void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003273 AdjustDeclIfTemplate(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003274 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3275
3276 // Enter the tag context.
3277 PushDeclContext(S, Tag);
3278
3279 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3280 FieldCollector->StartClass();
3281
3282 if (Record->getIdentifier()) {
3283 // C++ [class]p2:
3284 // [...] The class-name is also inserted into the scope of the
3285 // class itself; this is known as the injected-class-name. For
3286 // purposes of access checking, the injected-class-name is treated
3287 // as if it were a public member name.
3288 RecordDecl *InjectedClassName
3289 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3290 CurContext, Record->getLocation(),
3291 Record->getIdentifier(), Record);
3292 InjectedClassName->setImplicit();
3293 PushOnScopeChains(InjectedClassName, S);
3294 }
3295 }
3296}
3297
3298void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
Douglas Gregorded2d7b2009-02-04 19:02:06 +00003299 AdjustDeclIfTemplate(TagD);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003300 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3301
3302 if (isa<CXXRecordDecl>(Tag))
3303 FieldCollector->FinishClass();
3304
3305 // Exit this scope of this tag's definition.
3306 PopDeclContext();
3307
3308 // Notify the consumer that we've defined a tag.
3309 Consumer.HandleTagDeclDefinition(Tag);
3310}
Chris Lattner535b8302008-06-21 19:39:06 +00003311
Chris Lattnerffb31a22008-11-12 21:17:48 +00003312/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3313/// types into constant array types in certain situations which would otherwise
3314/// be errors (for GCC compatibility).
3315static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3316 ASTContext &Context) {
Eli Friedman149614b2008-06-03 21:01:11 +00003317 // This method tries to turn a variable array into a constant
3318 // array even when the size isn't an ICE. This is necessary
3319 // for compatibility with code that depends on gcc's buggy
3320 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerb5da7a32008-11-12 19:48:13 +00003321 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3322 if (!VLATy) return QualType();
3323
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003324 Expr::EvalResult EvalResult;
Chris Lattnerb5da7a32008-11-12 19:48:13 +00003325 if (!VLATy->getSizeExpr() ||
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003326 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerb5da7a32008-11-12 19:48:13 +00003327 return QualType();
3328
Anders Carlsson6736d1a22008-12-19 20:58:05 +00003329 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3330 llvm::APSInt &Res = EvalResult.Val.getInt();
Nuno Lopes026bcde2009-02-02 22:32:08 +00003331 if (Res >= llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3332 return Context.getConstantArrayType(VLATy->getElementType(),
3333 Res, ArrayType::Normal, 0);
3334 return QualType();
Eli Friedman149614b2008-06-03 21:01:11 +00003335}
3336
Anders Carlsson5df391e2008-12-06 20:33:04 +00003337bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner81ed6802008-12-12 04:56:04 +00003338 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson5df391e2008-12-06 20:33:04 +00003339 // FIXME: 6.7.2.1p4 - verify the field type.
3340
3341 llvm::APSInt Value;
3342 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3343 return true;
3344
Chris Lattner81ed6802008-12-12 04:56:04 +00003345 // Zero-width bitfield is ok for anonymous field.
3346 if (Value == 0 && FieldName)
3347 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3348
3349 if (Value.isNegative())
3350 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson5df391e2008-12-06 20:33:04 +00003351
3352 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3353 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner81ed6802008-12-12 04:56:04 +00003354 if (TypeSize && Value.getZExtValue() > TypeSize)
3355 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3356 << FieldName << (unsigned)TypeSize;
Anders Carlsson5df391e2008-12-06 20:33:04 +00003357
3358 return false;
3359}
3360
Steve Naroff30d242c2007-09-15 18:49:24 +00003361/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner1300fb92007-01-23 23:42:53 +00003362/// to create a FieldDecl object for it.
Douglas Gregor91f84212008-12-11 16:49:14 +00003363Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner1300fb92007-01-23 23:42:53 +00003364 SourceLocation DeclStart,
3365 Declarator &D, ExprTy *BitfieldWidth) {
3366 IdentifierInfo *II = D.getIdentifier();
3367 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner1300fb92007-01-23 23:42:53 +00003368 SourceLocation Loc = DeclStart;
Douglas Gregor91f84212008-12-11 16:49:14 +00003369 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner1300fb92007-01-23 23:42:53 +00003370 if (II) Loc = D.getIdentifierLoc();
3371
Chris Lattner62d2e662007-01-28 00:21:37 +00003372 // FIXME: Unnamed fields can be handled in various different ways, for
3373 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner1300fb92007-01-23 23:42:53 +00003374
Steve Naroffe5aa9be2007-04-05 22:36:20 +00003375 QualType T = GetTypeForDeclarator(D, S);
Steve Narofff93b6722007-08-28 20:14:24 +00003376 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3377 bool InvalidDecl = false;
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003378
Steve Naroff8eeeb132007-05-08 21:09:37 +00003379 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3380 // than a variably modified type.
Eli Friedman9e805b22008-02-15 12:53:51 +00003381 if (T->isVariablyModifiedType()) {
Chris Lattnerffb31a22008-11-12 21:17:48 +00003382 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman149614b2008-06-03 21:01:11 +00003383 if (!FixedTy.isNull()) {
Chris Lattnerf3e388d2008-11-13 18:49:38 +00003384 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman149614b2008-06-03 21:01:11 +00003385 T = FixedTy;
3386 } else {
Chris Lattnerf3e388d2008-11-13 18:49:38 +00003387 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattnere7d1cdb2008-11-12 19:45:49 +00003388 T = Context.IntTy;
Eli Friedman149614b2008-06-03 21:01:11 +00003389 InvalidDecl = true;
3390 }
Steve Naroff8eeeb132007-05-08 21:09:37 +00003391 }
Anders Carlsson5df391e2008-12-06 20:33:04 +00003392
3393 if (BitWidth) {
3394 if (VerifyBitField(Loc, II, T, BitWidth))
3395 InvalidDecl = true;
3396 } else {
3397 // Not a bitfield.
3398
3399 // validate II.
3400
3401 }
3402
Chris Lattner776fac82007-06-09 00:53:06 +00003403 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidised983422008-07-01 10:37:29 +00003404 FieldDecl *NewFD;
3405
Douglas Gregor91f84212008-12-11 16:49:14 +00003406 NewFD = FieldDecl::Create(Context, Record,
3407 Loc, II, T, BitWidth,
3408 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003409 DeclSpec::SCS_mutable);
Douglas Gregor91f84212008-12-11 16:49:14 +00003410
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003411 if (II) {
Douglas Gregor2ada0482009-02-04 17:27:36 +00003412 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003413 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3414 && !isa<TagDecl>(PrevDecl)) {
3415 Diag(Loc, diag::err_duplicate_member) << II;
3416 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3417 NewFD->setInvalidDecl();
3418 Record->setInvalidDecl();
3419 }
3420 }
3421
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003422 if (getLangOptions().CPlusPlus) {
Douglas Gregor4d87df52008-12-16 21:30:33 +00003423 CheckExtraCXXDefaultArguments(D);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003424 if (!T->isPODType())
3425 cast<CXXRecordDecl>(Record)->setPOD(false);
3426 }
Douglas Gregor4d87df52008-12-16 21:30:33 +00003427
Chris Lattner2727d1b2008-06-29 00:02:00 +00003428 ProcessDeclAttributes(NewFD, D);
Anders Carlsson28e71082008-02-16 00:29:18 +00003429
Steve Narofff93b6722007-08-28 20:14:24 +00003430 if (D.getInvalidType() || InvalidDecl)
3431 NewFD->setInvalidDecl();
Douglas Gregor91f84212008-12-11 16:49:14 +00003432
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003433 if (II) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003434 PushOnScopeChains(NewFD, S);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003435 } else
Douglas Gregorb3730b52009-01-12 23:27:07 +00003436 Record->addDecl(NewFD);
Douglas Gregor91f84212008-12-11 16:49:14 +00003437
Steve Narofff93b6722007-08-28 20:14:24 +00003438 return NewFD;
Chris Lattner1300fb92007-01-23 23:42:53 +00003439}
3440
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00003441/// TranslateIvarVisibility - Translate visibility from a token ID to an
3442/// AST enum value.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003443static ObjCIvarDecl::AccessControl
Fariborz Jahanianf26702eb2007-10-01 16:53:59 +00003444TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroff2e688fd2007-09-14 23:09:53 +00003445 switch (ivarVisibility) {
Chris Lattner79ef8432008-10-12 00:28:42 +00003446 default: assert(0 && "Unknown visitibility kind");
3447 case tok::objc_private: return ObjCIvarDecl::Private;
3448 case tok::objc_public: return ObjCIvarDecl::Public;
3449 case tok::objc_protected: return ObjCIvarDecl::Protected;
3450 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroff2e688fd2007-09-14 23:09:53 +00003451 }
3452}
3453
Fariborz Jahanian96376742008-04-11 16:55:42 +00003454/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3455/// in order to create an IvarDecl object for it.
Fariborz Jahaniande615832008-04-10 23:32:45 +00003456Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian96376742008-04-11 16:55:42 +00003457 SourceLocation DeclStart,
3458 Declarator &D, ExprTy *BitfieldWidth,
3459 tok::ObjCKeywordKind Visibility) {
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003460
Fariborz Jahaniande615832008-04-10 23:32:45 +00003461 IdentifierInfo *II = D.getIdentifier();
3462 Expr *BitWidth = (Expr*)BitfieldWidth;
3463 SourceLocation Loc = DeclStart;
3464 if (II) Loc = D.getIdentifierLoc();
3465
3466 // FIXME: Unnamed fields can be handled in various different ways, for
3467 // example, unnamed unions inject all members into the struct namespace!
3468
Anders Carlsson5df391e2008-12-06 20:33:04 +00003469 QualType T = GetTypeForDeclarator(D, S);
3470 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3471 bool InvalidDecl = false;
Fariborz Jahaniande615832008-04-10 23:32:45 +00003472
3473 if (BitWidth) {
3474 // TODO: Validate.
3475 //printf("WARNING: BITFIELDS IGNORED!\n");
3476
3477 // 6.7.2.1p3
3478 // 6.7.2.1p4
3479
3480 } else {
3481 // Not a bitfield.
3482
3483 // validate II.
3484
3485 }
3486
Fariborz Jahaniande615832008-04-10 23:32:45 +00003487 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3488 // than a variably modified type.
3489 if (T->isVariablyModifiedType()) {
Anders Carlsson0d8f0ba2008-12-07 00:20:55 +00003490 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahaniande615832008-04-10 23:32:45 +00003491 InvalidDecl = true;
3492 }
3493
Ted Kremenek73295fa2008-07-23 18:04:17 +00003494 // Get the visibility (access control) for this ivar.
3495 ObjCIvarDecl::AccessControl ac =
3496 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3497 : ObjCIvarDecl::None;
3498
3499 // Construct the decl.
Chris Lattner4576b2e2009-02-15 22:44:22 +00003500 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffde7d0f62008-07-16 18:22:22 +00003501 (Expr *)BitfieldWidth);
Fariborz Jahaniande615832008-04-10 23:32:45 +00003502
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003503 if (II) {
Douglas Gregor2ada0482009-02-04 17:27:36 +00003504 NamedDecl *PrevDecl = LookupName(S, II, LookupMemberName, true);
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003505 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3506 && !isa<TagDecl>(PrevDecl)) {
3507 Diag(Loc, diag::err_duplicate_member) << II;
3508 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3509 NewID->setInvalidDecl();
3510 }
3511 }
3512
Ted Kremenek73295fa2008-07-23 18:04:17 +00003513 // Process attributes attached to the ivar.
Chris Lattner2727d1b2008-06-29 00:02:00 +00003514 ProcessDeclAttributes(NewID, D);
Fariborz Jahaniande615832008-04-10 23:32:45 +00003515
3516 if (D.getInvalidType() || InvalidDecl)
3517 NewID->setInvalidDecl();
Ted Kremenek73295fa2008-07-23 18:04:17 +00003518
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003519 if (II) {
3520 // FIXME: When interfaces are DeclContexts, we'll need to add
3521 // these to the interface.
3522 S->AddDecl(NewID);
3523 IdResolver.AddDecl(NewID);
3524 }
3525
Fariborz Jahaniande615832008-04-10 23:32:45 +00003526 return NewID;
3527}
3528
Fariborz Jahanian343f7092007-09-29 00:54:24 +00003529void Sema::ActOnFields(Scope* S,
Fariborz Jahanian67341402007-10-04 00:45:27 +00003530 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff30d242c2007-09-15 18:49:24 +00003531 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar15619c72008-10-03 02:03:53 +00003532 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar325601a2008-10-03 17:33:35 +00003533 AttributeList *Attr) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00003534 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3535 assert(EnclosingDecl && "missing record or interface decl");
3536 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3537
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00003538 // Verify that all the fields are okay.
Chris Lattner82625602007-01-24 02:26:21 +00003539 unsigned NumNamedMembers = 0;
Chris Lattner23b7eb62007-06-15 23:05:46 +00003540 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregorf4d33272009-01-07 19:46:03 +00003541
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00003542 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroffdb47ee22007-09-14 22:20:54 +00003543 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3544 assert(FD && "missing field decl");
3545
Chris Lattner720a0542007-01-25 00:44:24 +00003546 // Get the type for the field.
Chris Lattner0fd893e2007-07-31 21:33:24 +00003547 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregorf4d33272009-01-07 19:46:03 +00003548
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003549 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregorf4d33272009-01-07 19:46:03 +00003550 // Remember all fields written by the user.
3551 RecFields.push_back(FD);
3552 }
Steve Naroff2e688fd2007-09-14 23:09:53 +00003553
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00003554 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner0fd893e2007-07-31 21:33:24 +00003555 if (FDTy->isFunctionType()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003556 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003557 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00003558 FD->setInvalidDecl();
3559 EnclosingDecl->setInvalidDecl();
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00003560 continue;
3561 }
Chris Lattner82625602007-01-24 02:26:21 +00003562 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
Chris Lattner720a0542007-01-25 00:44:24 +00003563 if (FDTy->isIncompleteType()) {
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00003564 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregordd430f72009-01-19 19:26:10 +00003565 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3566 diag::err_field_incomplete);
Steve Naroffdb47ee22007-09-14 22:20:54 +00003567 FD->setInvalidDecl();
3568 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian67341402007-10-04 00:45:27 +00003569 continue;
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00003570 }
Chris Lattner82625602007-01-24 02:26:21 +00003571 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003572 !Record->isStruct() || // ... of a structure ...
Chris Lattner0fd893e2007-07-31 21:33:24 +00003573 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregordd430f72009-01-19 19:26:10 +00003574 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3575 diag::err_field_incomplete);
Steve Naroffdb47ee22007-09-14 22:20:54 +00003576 FD->setInvalidDecl();
3577 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00003578 continue;
3579 }
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00003580 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner651d42d2008-11-20 06:38:18 +00003581 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003582 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00003583 FD->setInvalidDecl();
3584 EnclosingDecl->setInvalidDecl();
Chris Lattner82625602007-01-24 02:26:21 +00003585 continue;
3586 }
Chris Lattner720a0542007-01-25 00:44:24 +00003587 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00003588 if (Record)
3589 Record->setHasFlexibleArrayMember(true);
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00003590 }
Chris Lattner720a0542007-01-25 00:44:24 +00003591 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3592 /// field of another structure or the element of an array.
Chris Lattner0fd893e2007-07-31 21:33:24 +00003593 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner720a0542007-01-25 00:44:24 +00003594 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3595 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003596 if (Record && Record->isUnion()) {
Chris Lattner41943152007-01-25 04:52:46 +00003597 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00003598 } else {
3599 // If this is a struct/class and this is not the last element, reject
3600 // it. Note that GCC supports variable sized arrays in the middle of
3601 // structures.
3602 if (i != NumFields-1) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003603 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003604 << FD->getDeclName();
Steve Naroffdb47ee22007-09-14 22:20:54 +00003605 FD->setInvalidDecl();
3606 EnclosingDecl->setInvalidDecl();
Chris Lattner720a0542007-01-25 00:44:24 +00003607 continue;
3608 }
Chris Lattner720a0542007-01-25 00:44:24 +00003609 // We support flexible arrays at the end of structs in other structs
3610 // as an extension.
Chris Lattner651d42d2008-11-20 06:38:18 +00003611 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003612 << FD->getDeclName();
Fariborz Jahanian67341402007-10-04 00:45:27 +00003613 if (Record)
Fariborz Jahanianaefb2302007-09-14 16:27:55 +00003614 Record->setHasFlexibleArrayMember(true);
Chris Lattner720a0542007-01-25 00:44:24 +00003615 }
3616 }
3617 }
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00003618 /// A field cannot be an Objective-c object
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003619 if (FDTy->isObjCInterfaceType()) {
Chris Lattner651d42d2008-11-20 06:38:18 +00003620 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnere3d20d92008-11-23 21:45:46 +00003621 << FD->getDeclName();
Fariborz Jahanianecfe4f12007-10-12 22:10:42 +00003622 FD->setInvalidDecl();
3623 EnclosingDecl->setInvalidDecl();
3624 continue;
3625 }
Chris Lattner82625602007-01-24 02:26:21 +00003626 // Keep track of the number of named members.
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003627 if (FD->getIdentifier())
Chris Lattner82625602007-01-24 02:26:21 +00003628 ++NumNamedMembers;
Chris Lattnerbdf8b8d2007-01-24 02:11:17 +00003629 }
Sebastian Redlbaad4e72009-01-05 20:52:13 +00003630
Chris Lattner82625602007-01-24 02:26:21 +00003631 // Okay, we successfully defined 'Record'.
Chris Lattner622c1932008-02-06 00:51:33 +00003632 if (Record) {
Douglas Gregor91f84212008-12-11 16:49:14 +00003633 Record->completeDefinition(Context);
Chris Lattner622c1932008-02-06 00:51:33 +00003634 } else {
Chris Lattner9413a012008-02-05 22:40:55 +00003635 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian02225532008-12-13 20:28:25 +00003636 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner9413a012008-02-05 22:40:55 +00003637 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniana599c132008-12-16 01:08:35 +00003638 // Must enforce the rule that ivars in the base classes may not be
3639 // duplicates.
Fariborz Jahanian4496c0f2008-12-17 22:21:44 +00003640 if (ID->getSuperClass()) {
3641 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3642 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3643 ObjCIvarDecl* Ivar = (*IVI);
3644 IdentifierInfo *II = Ivar->getIdentifier();
3645 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3646 if (prevIvar) {
3647 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor82ac25e2009-01-08 20:45:30 +00003648 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahaniana599c132008-12-16 01:08:35 +00003649 }
Fariborz Jahanian4496c0f2008-12-17 22:21:44 +00003650 }
Fariborz Jahaniana599c132008-12-16 01:08:35 +00003651 }
Fariborz Jahanian02225532008-12-13 20:28:25 +00003652 }
Chris Lattner9413a012008-02-05 22:40:55 +00003653 else if (ObjCImplementationDecl *IMPDecl =
3654 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003655 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3656 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian95b60762007-10-31 18:48:14 +00003657 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian2a4dd312007-09-26 18:27:25 +00003658 }
Fariborz Jahanianf3287bf2007-09-14 21:08:27 +00003659 }
Daniel Dunbar325601a2008-10-03 17:33:35 +00003660
3661 if (Attr)
3662 ProcessDeclAttributeList(Record, Attr);
Chris Lattner1300fb92007-01-23 23:42:53 +00003663}
3664
Steve Naroff30d242c2007-09-15 18:49:24 +00003665Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4ef40012007-06-11 01:28:17 +00003666 DeclTy *lastEnumConst,
Chris Lattnerc1915e22007-01-25 07:29:02 +00003667 SourceLocation IdLoc, IdentifierInfo *Id,
Chris Lattner4ef40012007-06-11 01:28:17 +00003668 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnerc5ffed42008-04-04 06:12:32 +00003669 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4ef40012007-06-11 01:28:17 +00003670 EnumConstantDecl *LastEnumConst =
3671 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3672 Expr *Val = static_cast<Expr*>(val);
Chris Lattner8116d1b2007-01-25 22:38:29 +00003673
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003674 // The scope passed in may not be a decl scope. Zip up the scope tree until
3675 // we find one that is.
Douglas Gregor45a33ec2009-01-12 18:45:55 +00003676 S = getNonFieldDeclScope(S);
Chris Lattner1a76a3c2007-08-26 06:24:45 +00003677
Chris Lattner8116d1b2007-01-25 22:38:29 +00003678 // Verify that there isn't already something declared with this name in this
3679 // scope.
Douglas Gregor2ada0482009-02-04 17:27:36 +00003680 NamedDecl *PrevDecl = LookupName(S, Id, LookupOrdinaryName);
Douglas Gregor5daeee22008-12-08 18:40:42 +00003681 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor5101c242008-12-05 18:15:24 +00003682 // Maybe we will complain about the shadowed template parameter.
3683 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3684 // Just pretend that we didn't see the previous declaration.
3685 PrevDecl = 0;
3686 }
3687
3688 if (PrevDecl) {
Argyrios Kyrtzidisbd259982008-07-16 21:01:53 +00003689 // When in C++, we may get a TagDecl with the same name; in this case the
3690 // enum constant will 'hide' the tag.
3691 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3692 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis5b144d52008-09-09 21:18:04 +00003693 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner8116d1b2007-01-25 22:38:29 +00003694 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003695 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner8116d1b2007-01-25 22:38:29 +00003696 else
Chris Lattner4bd8dd82008-11-19 08:23:25 +00003697 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner0369c572008-11-23 23:12:31 +00003698 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Ted Kremenek5a201952009-02-07 01:47:29 +00003699 Val->Destroy(Context);
Chris Lattner8116d1b2007-01-25 22:38:29 +00003700 return 0;
3701 }
3702 }
Chris Lattner4ef40012007-06-11 01:28:17 +00003703
Chris Lattner23b7eb62007-06-15 23:05:46 +00003704 llvm::APSInt EnumVal(32);
Chris Lattner4ef40012007-06-11 01:28:17 +00003705 QualType EltTy;
3706 if (Val) {
Chris Lattner0515e4b2007-08-27 21:16:18 +00003707 // Make sure to promote the operand type to int.
3708 UsualUnaryConversions(Val);
3709
Chris Lattner4ef40012007-06-11 01:28:17 +00003710 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3711 SourceLocation ExpLoc;
Anders Carlsson1aa67922008-12-05 16:33:57 +00003712 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00003713 Val->Destroy(Context);
Chris Lattnerf283a372007-08-27 17:37:24 +00003714 Val = 0; // Just forget about it.
Chris Lattnerc92bc4c2007-08-29 16:03:41 +00003715 } else {
3716 EltTy = Val->getType();
Chris Lattner4ef40012007-06-11 01:28:17 +00003717 }
Chris Lattnerf283a372007-08-27 17:37:24 +00003718 }
3719
3720 if (!Val) {
3721 if (LastEnumConst) {
3722 // Assign the last value + 1.
3723 EnumVal = LastEnumConst->getInitVal();
3724 ++EnumVal;
Chris Lattner0515e4b2007-08-27 21:16:18 +00003725
3726 // Check for overflow on increment.
3727 if (EnumVal < LastEnumConst->getInitVal())
3728 Diag(IdLoc, diag::warn_enum_value_overflow);
3729
Chris Lattnerf283a372007-08-27 17:37:24 +00003730 EltTy = LastEnumConst->getType();
3731 } else {
3732 // First value, set to zero.
3733 EltTy = Context.IntTy;
Chris Lattner37e05872008-03-05 18:54:05 +00003734 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerf283a372007-08-27 17:37:24 +00003735 }
Steve Naroff63969212007-05-07 21:22:42 +00003736 }
Chris Lattner4ef40012007-06-11 01:28:17 +00003737
Chris Lattnera7b32872008-03-15 06:12:44 +00003738 EnumConstantDecl *New =
Chris Lattnerc5ffed42008-04-04 06:12:32 +00003739 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003740 Val, EnumVal);
Chris Lattner8116d1b2007-01-25 22:38:29 +00003741
3742 // Register this decl in the current scope stack.
Argyrios Kyrtzidisb8a49202008-04-12 00:47:19 +00003743 PushOnScopeChains(New, S);
Douglas Gregor2f521192008-12-17 02:04:30 +00003744
Chris Lattner8116d1b2007-01-25 22:38:29 +00003745 return New;
Chris Lattnerc1915e22007-01-25 07:29:02 +00003746}
3747
Steve Narofff960c0b2008-08-07 14:08:16 +00003748// FIXME: For consistency with ActOnFields(), we should have the parser
3749// pass in the source location for the left/right braces.
Steve Naroff30d242c2007-09-15 18:49:24 +00003750void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattnerc1915e22007-01-25 07:29:02 +00003751 DeclTy **Elements, unsigned NumElements) {
3752 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor07665a62009-01-05 19:45:36 +00003753 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattnerc1915e22007-01-25 07:29:02 +00003754
Chris Lattner67933c02007-08-28 05:10:31 +00003755 // TODO: If the result value doesn't fit in an int, it must be a long or long
3756 // long value. ISO C does not support this, but GCC does as an extension,
3757 // emit a warning.
Chris Lattner37e05872008-03-05 18:54:05 +00003758 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner67933c02007-08-28 05:10:31 +00003759
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003760 // Verify that all the values are okay, compute the size of the values, and
3761 // reverse the list.
3762 unsigned NumNegativeBits = 0;
3763 unsigned NumPositiveBits = 0;
3764
3765 // Keep track of whether all elements have type int.
3766 bool AllElementsInt = true;
3767
Chris Lattnerc1915e22007-01-25 07:29:02 +00003768 for (unsigned i = 0; i != NumElements; ++i) {
3769 EnumConstantDecl *ECD =
3770 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3771 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00003772
3773 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnerbf478cb2007-08-28 05:27:00 +00003774 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner77683132008-02-26 00:33:57 +00003775 assert(InitVal.getBitWidth() >= IntWidth &&
3776 "Should have promoted value to int");
Chris Lattnerbf478cb2007-08-28 05:27:00 +00003777 if (InitVal.getBitWidth() > IntWidth) {
3778 llvm::APSInt V(InitVal);
3779 V.trunc(IntWidth);
3780 V.extend(InitVal.getBitWidth());
3781 if (V != InitVal)
Chris Lattner651d42d2008-11-20 06:38:18 +00003782 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3783 << InitVal.toString(10);
Chris Lattnerbf478cb2007-08-28 05:27:00 +00003784 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003785
3786 // Keep track of the size of positive and negative values.
Chris Lattner77683132008-02-26 00:33:57 +00003787 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner49f980c2008-01-14 21:47:29 +00003788 NumPositiveBits = std::max(NumPositiveBits,
3789 (unsigned)InitVal.getActiveBits());
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003790 else
Chris Lattner49f980c2008-01-14 21:47:29 +00003791 NumNegativeBits = std::max(NumNegativeBits,
3792 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4ef40012007-06-11 01:28:17 +00003793
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003794 // Keep track of whether every enum element has type int (very commmon).
3795 if (AllElementsInt)
3796 AllElementsInt = ECD->getType() == Context.IntTy;
Chris Lattnerc1915e22007-01-25 07:29:02 +00003797 }
3798
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003799 // Figure out the type that should be used for this enum.
3800 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3801 QualType BestType;
Chris Lattner3a370bf2007-08-29 17:31:48 +00003802 unsigned BestWidth;
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003803
3804 if (NumNegativeBits) {
3805 // If there is a negative value, figure out the smallest integer type (of
3806 // int/long/longlong) that fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00003807 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003808 BestType = Context.IntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00003809 BestWidth = IntWidth;
3810 } else {
Chris Lattner37e05872008-03-05 18:54:05 +00003811 BestWidth = Context.Target.getLongWidth();
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00003812
Chris Lattner3a370bf2007-08-29 17:31:48 +00003813 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003814 BestType = Context.LongTy;
3815 else {
Chris Lattner37e05872008-03-05 18:54:05 +00003816 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek1daa3cf2007-12-12 22:39:36 +00003817
Chris Lattner3a370bf2007-08-29 17:31:48 +00003818 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003819 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3820 BestType = Context.LongLongTy;
3821 }
3822 }
3823 } else {
3824 // If there is no negative value, figure out which of uint, ulong, ulonglong
3825 // fits.
Chris Lattner3a370bf2007-08-29 17:31:48 +00003826 if (NumPositiveBits <= IntWidth) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003827 BestType = Context.UnsignedIntTy;
Chris Lattner3a370bf2007-08-29 17:31:48 +00003828 BestWidth = IntWidth;
3829 } else if (NumPositiveBits <=
Chris Lattner37e05872008-03-05 18:54:05 +00003830 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003831 BestType = Context.UnsignedLongTy;
Chris Lattner37e05872008-03-05 18:54:05 +00003832 } else {
3833 BestWidth = Context.Target.getLongLongWidth();
Chris Lattner3a370bf2007-08-29 17:31:48 +00003834 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003835 "How could an initializer get larger than ULL?");
3836 BestType = Context.UnsignedLongLongTy;
3837 }
3838 }
3839
Chris Lattner3a370bf2007-08-29 17:31:48 +00003840 // Loop over all of the enumerator constants, changing their types to match
3841 // the type of the enum if needed.
3842 for (unsigned i = 0; i != NumElements; ++i) {
3843 EnumConstantDecl *ECD =
3844 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3845 if (!ECD) continue; // Already issued a diagnostic.
3846
3847 // Standard C says the enumerators have int type, but we allow, as an
3848 // extension, the enumerators to be larger than int size. If each
3849 // enumerator value fits in an int, type it as an int, otherwise type it the
3850 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3851 // that X has type 'int', not 'unsigned'.
Chris Lattner77683132008-02-26 00:33:57 +00003852 if (ECD->getType() == Context.IntTy) {
3853 // Make sure the init value is signed.
3854 llvm::APSInt IV = ECD->getInitVal();
3855 IV.setIsSigned(true);
3856 ECD->setInitVal(IV);
Douglas Gregor1d248c52008-12-12 02:00:36 +00003857
3858 if (getLangOptions().CPlusPlus)
3859 // C++ [dcl.enum]p4: Following the closing brace of an
3860 // enum-specifier, each enumerator has the type of its
3861 // enumeration.
3862 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00003863 continue; // Already int type.
Chris Lattner77683132008-02-26 00:33:57 +00003864 }
Chris Lattner3a370bf2007-08-29 17:31:48 +00003865
3866 // Determine whether the value fits into an int.
3867 llvm::APSInt InitVal = ECD->getInitVal();
3868 bool FitsInInt;
3869 if (InitVal.isUnsigned() || !InitVal.isNegative())
3870 FitsInInt = InitVal.getActiveBits() < IntWidth;
3871 else
3872 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3873
3874 // If it fits into an integer type, force it. Otherwise force it to match
3875 // the enum decl type.
3876 QualType NewTy;
3877 unsigned NewWidth;
3878 bool NewSign;
3879 if (FitsInInt) {
3880 NewTy = Context.IntTy;
3881 NewWidth = IntWidth;
3882 NewSign = true;
3883 } else if (ECD->getType() == BestType) {
3884 // Already the right type!
Douglas Gregor1d248c52008-12-12 02:00:36 +00003885 if (getLangOptions().CPlusPlus)
3886 // C++ [dcl.enum]p4: Following the closing brace of an
3887 // enum-specifier, each enumerator has the type of its
3888 // enumeration.
3889 ECD->setType(EnumType);
Chris Lattner3a370bf2007-08-29 17:31:48 +00003890 continue;
3891 } else {
3892 NewTy = BestType;
3893 NewWidth = BestWidth;
3894 NewSign = BestType->isSignedIntegerType();
3895 }
3896
3897 // Adjust the APSInt value.
3898 InitVal.extOrTrunc(NewWidth);
3899 InitVal.setIsSigned(NewSign);
3900 ECD->setInitVal(InitVal);
3901
3902 // Adjust the Expr initializer and type.
Chris Lattnere53c0362009-01-15 19:19:42 +00003903 if (ECD->getInitExpr())
Ted Kremenek5a201952009-02-07 01:47:29 +00003904 ECD->setInitExpr(new (Context) ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3905 /*isLvalue=*/false));
Douglas Gregor1d248c52008-12-12 02:00:36 +00003906 if (getLangOptions().CPlusPlus)
3907 // C++ [dcl.enum]p4: Following the closing brace of an
3908 // enum-specifier, each enumerator has the type of its
3909 // enumeration.
3910 ECD->setType(EnumType);
3911 else
3912 ECD->setType(NewTy);
Chris Lattner3a370bf2007-08-29 17:31:48 +00003913 }
Chris Lattnerb8a501c2007-08-28 06:15:15 +00003914
Douglas Gregor91f84212008-12-11 16:49:14 +00003915 Enum->completeDefinition(Context, BestType);
Chris Lattnerc1915e22007-01-25 07:29:02 +00003916}
Chris Lattner1300fb92007-01-23 23:42:53 +00003917
Anders Carlsson5c6c0592008-02-08 00:33:21 +00003918Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redlc675bab2008-12-13 16:23:55 +00003919 ExprArg expr) {
3920 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3921
Douglas Gregor6e6ad602009-01-20 01:17:11 +00003922 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlsson5c6c0592008-02-08 00:33:21 +00003923}
3924
Douglas Gregor29ff7d02008-12-16 22:23:02 +00003925
Daniel Dunbar54603742008-10-14 05:35:18 +00003926void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3927 ExprTy *alignment, SourceLocation PragmaLoc,
3928 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3929 Expr *Alignment = static_cast<Expr *>(alignment);
3930
3931 // If specified then alignment must be a "small" power of two.
3932 unsigned AlignmentVal = 0;
3933 if (Alignment) {
3934 llvm::APSInt Val;
3935 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3936 !Val.isPowerOf2() ||
3937 Val.getZExtValue() > 16) {
3938 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
Ted Kremenek5a201952009-02-07 01:47:29 +00003939 Alignment->Destroy(Context);
Daniel Dunbar54603742008-10-14 05:35:18 +00003940 return; // Ignore
3941 }
3942
3943 AlignmentVal = (unsigned) Val.getZExtValue();
3944 }
3945
3946 switch (Kind) {
3947 case Action::PPK_Default: // pack([n])
3948 PackContext.setAlignment(AlignmentVal);
3949 break;
3950
3951 case Action::PPK_Show: // pack(show)
3952 // Show the current alignment, making sure to show the right value
3953 // for the default.
3954 AlignmentVal = PackContext.getAlignment();
3955 // FIXME: This should come from the target.
3956 if (AlignmentVal == 0)
3957 AlignmentVal = 8;
Chris Lattnerf76c09d2008-11-19 07:25:44 +00003958 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar54603742008-10-14 05:35:18 +00003959 break;
3960
3961 case Action::PPK_Push: // pack(push [, id] [, [n])
3962 PackContext.push(Name);
3963 // Set the new alignment if specified.
3964 if (Alignment)
3965 PackContext.setAlignment(AlignmentVal);
3966 break;
3967
3968 case Action::PPK_Pop: // pack(pop [, id] [, n])
3969 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3970 // "#pragma pack(pop, identifier, n) is undefined"
3971 if (Alignment && Name)
3972 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3973
3974 // Do the pop.
3975 if (!PackContext.pop(Name)) {
3976 // If a name was specified then failure indicates the name
3977 // wasn't found. Otherwise failure indicates the stack was
3978 // empty.
Chris Lattner651d42d2008-11-20 06:38:18 +00003979 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3980 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar54603742008-10-14 05:35:18 +00003981
3982 // FIXME: Warn about popping named records as MSVC does.
3983 } else {
3984 // Pop succeeded, set the new alignment if specified.
3985 if (Alignment)
3986 PackContext.setAlignment(AlignmentVal);
3987 }
3988 break;
3989
3990 default:
3991 assert(0 && "Invalid #pragma pack kind.");
3992 }
3993}
3994
3995bool PragmaPackStack::pop(IdentifierInfo *Name) {
3996 if (Stack.empty())
3997 return false;
3998
3999 // If name is empty just pop top.
4000 if (!Name) {
4001 Alignment = Stack.back().first;
4002 Stack.pop_back();
4003 return true;
4004 }
4005
4006 // Otherwise, find the named record.
4007 for (unsigned i = Stack.size(); i != 0; ) {
4008 --i;
Daniel Dunbaraf7efa62008-11-19 10:32:38 +00004009 if (Stack[i].second == Name) {
Daniel Dunbar54603742008-10-14 05:35:18 +00004010 // Found it, pop up to and including this record.
4011 Alignment = Stack[i].first;
4012 Stack.erase(Stack.begin() + i, Stack.end());
4013 return true;
4014 }
4015 }
4016
4017 return false;
4018}