blob: 77f99e848f19dcd78f4d2934914921749a4bc930 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Chris Lattner20c6b3b2009-01-27 18:30:58 +000021#include "clang/Basic/DiagnosticSema.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
Douglas Gregor6ed40e32008-12-23 21:05:05 +000029#include <algorithm>
30#include <functional>
Douglas Gregore267ff32008-12-11 20:41:00 +000031
Reid Spencer5f016e22007-07-11 17:01:13 +000032using namespace clang;
33
Steve Naroffb43a50f2009-01-28 19:39:02 +000034Sema::TypeTy *Sema::getTypeName(IdentifierInfo &II, Scope *S,
35 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
Steve Naroff3e8ffd22009-01-29 00:07:50 +000037
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000038 if (SS) {
39 if (SS->isInvalid())
40 return 0;
41 DC = static_cast<DeclContext*>(SS->getScopeRep());
42 }
Steve Naroff3e8ffd22009-01-29 00:07:50 +000043 LookupResult Result = DC ?
44 LookupDeclInContext(&II, Decl::IDNS_Ordinary, DC) :
45 LookupDeclInScope(&II, Decl::IDNS_Ordinary, S);
46
Douglas Gregor7176fff2009-01-15 00:26:24 +000047 Decl *IIDecl = 0;
48 switch (Result.getKind()) {
49 case LookupResult::NotFound:
50 case LookupResult::FoundOverloaded:
51 case LookupResult::AmbiguousBaseSubobjectTypes:
52 case LookupResult::AmbiguousBaseSubobjects:
53 // FIXME: In the event of an ambiguous lookup, we could visit all of
54 // the entities found to determine whether they are all types. This
55 // might provide better diagnostics.
56 return 0;
57
58 case LookupResult::Found:
59 IIDecl = Result.getAsDecl();
60 break;
61 }
62
63 if (isa<TypedefDecl>(IIDecl) ||
64 isa<ObjCInterfaceDecl>(IIDecl) ||
65 isa<TagDecl>(IIDecl) ||
66 isa<TemplateTypeParmDecl>(IIDecl))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000067 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000068 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000069}
70
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000071DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000072 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000073 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000074 if (MD->isOutOfLineDefinition())
75 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000076
77 // A C++ inline method is parsed *after* the topmost class it was declared in
78 // is fully parsed (it's "complete").
79 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000080 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000081 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
82 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000083 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000084 DC = RD;
85
86 // Return the declaration context of the topmost class the inline method is
87 // declared in.
88 return DC;
89 }
90
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000091 if (isa<ObjCMethodDecl>(DC))
92 return Context.getTranslationUnitDecl();
93
Douglas Gregor4afa39d2009-01-20 01:17:11 +000094 if (Decl *D = dyn_cast<Decl>(DC))
95 return D->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000096
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000097 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000098}
99
Douglas Gregor44b43212008-12-11 16:49:14 +0000100void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000101 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +0000102 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +0000103 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +0000104 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000105}
106
Chris Lattnerb048c982008-04-06 04:47:34 +0000107void Sema::PopDeclContext() {
108 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +0000109
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000110 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +0000111}
112
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000113/// Add this decl to the scope shadowed decl chains.
114void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +0000115 // Move up the scope chain until we find the nearest enclosing
116 // non-transparent context. The declaration will be introduced into this
117 // scope.
118 while (S->getEntity() &&
119 ((DeclContext *)S->getEntity())->isTransparentContext())
120 S = S->getParent();
121
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000122 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000123
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000124 // Add scoped declarations into their context, so that they can be
125 // found later. Declarations without a context won't be inserted
126 // into any context.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000127 CurContext->addDecl(D);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000128
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000129 // C++ [basic.scope]p4:
130 // -- exactly one declaration shall declare a class name or
131 // enumeration name that is not a typedef name and the other
132 // declarations shall all refer to the same object or
133 // enumerator, or all refer to functions and function templates;
134 // in this case the class name or enumeration name is hidden.
135 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
136 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000137 if (CurContext->getLookupContext()
138 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000139 // We're pushing the tag into the current context, which might
140 // require some reshuffling in the identifier resolver.
141 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000142 I = IdResolver.begin(TD->getDeclName(), CurContext,
143 false/*LookInParentCtx*/),
144 IEnd = IdResolver.end();
145 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
146 NamedDecl *PrevDecl = *I;
147 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
148 PrevDecl = *I, ++I) {
149 if (TD->declarationReplaces(*I)) {
150 // This is a redeclaration. Remove it from the chain and
151 // break out, so that we'll add in the shadowed
152 // declaration.
153 S->RemoveDecl(*I);
154 if (PrevDecl == *I) {
155 IdResolver.RemoveDecl(*I);
156 IdResolver.AddDecl(TD);
157 return;
158 } else {
159 IdResolver.RemoveDecl(*I);
160 break;
161 }
162 }
163 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000164
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000165 // There is already a declaration with the same name in the same
166 // scope, which is not a tag declaration. It must be found
167 // before we find the new declaration, so insert the new
168 // declaration at the end of the chain.
169 IdResolver.AddShadowedDecl(TD, PrevDecl);
170
171 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000172 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000174 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000175 // We are pushing the name of a function, which might be an
176 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000177 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000178 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000179 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000180 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000181 false/*LookInParentCtx*/),
182 IdResolver.end(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000183 std::bind1st(std::mem_fun(&NamedDecl::declarationReplaces),
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000184 FD));
185 if (Redecl != IdResolver.end()) {
186 // There is already a declaration of a function on our
187 // IdResolver chain. Replace it with this declaration.
188 S->RemoveDecl(*Redecl);
189 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000190 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000191 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000192
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000193 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000194}
195
Steve Naroffb216c882007-10-09 22:01:59 +0000196void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000197 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000198 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
199 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000200
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
202 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000203 Decl *TmpD = static_cast<Decl*>(*I);
204 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000205
Douglas Gregor44b43212008-12-11 16:49:14 +0000206 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
207 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000208
Douglas Gregor44b43212008-12-11 16:49:14 +0000209 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000210
Douglas Gregor44b43212008-12-11 16:49:14 +0000211 // Remove this name from our lexical scope.
212 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 }
214}
215
Steve Naroffe8043c32008-04-01 23:04:06 +0000216/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
217/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000218ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000219 // The third "scope" argument is 0 since we aren't enabling lazy built-in
220 // creation from this context.
Steve Naroff3e8ffd22009-01-29 00:07:50 +0000221 Decl *IDecl = LookupDeclInScope(Id, Decl::IDNS_Ordinary, 0);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000222
Steve Naroffb327ce02008-04-02 14:35:35 +0000223 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000224}
225
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000226/// getNonFieldDeclScope - Retrieves the innermost scope, starting
227/// from S, where a non-field would be declared. This routine copes
228/// with the difference between C and C++ scoping rules in structs and
229/// unions. For example, the following code is well-formed in C but
230/// ill-formed in C++:
231/// @code
232/// struct S6 {
233/// enum { BAR } e;
234/// };
235///
236/// void test_S6() {
237/// struct S6 a;
238/// a.e = BAR;
239/// }
240/// @endcode
241/// For the declaration of BAR, this routine will return a different
242/// scope. The scope S will be the scope of the unnamed enumeration
243/// within S6. In C++, this routine will return the scope associated
244/// with S6, because the enumeration's scope is a transparent
245/// context but structures can contain non-field names. In C, this
246/// routine will return the translation unit scope, since the
247/// enumeration's scope is a transparent context and structures cannot
248/// contain non-field names.
249Scope *Sema::getNonFieldDeclScope(Scope *S) {
250 while (((S->getFlags() & Scope::DeclScope) == 0) ||
251 (S->getEntity() &&
252 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
253 (S->isClassScope() && !getLangOptions().CPlusPlus))
254 S = S->getParent();
255 return S;
256}
257
Steve Naroff3e8ffd22009-01-29 00:07:50 +0000258/// LookupDeclInScope - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000259/// namespace. NamespaceNameOnly - during lookup only namespace names
260/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
261/// 'When looking up a namespace-name in a using-directive or
262/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000263///
264/// Note: The use of this routine is deprecated. Please use
265/// LookupName, LookupQualifiedName, or LookupParsedName instead.
266Sema::LookupResult
Steve Naroff3e8ffd22009-01-29 00:07:50 +0000267Sema::LookupDeclInScope(DeclarationName Name, unsigned NSI, Scope *S,
268 bool LookInParent) {
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000269 LookupCriteria::NameKind Kind;
270 if (NSI == Decl::IDNS_Ordinary) {
Steve Naroff133147d2009-01-28 16:09:22 +0000271 Kind = LookupCriteria::Ordinary;
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000272 } else if (NSI == Decl::IDNS_Tag)
273 Kind = LookupCriteria::Tag;
Chris Lattner95d58f32009-01-16 19:44:00 +0000274 else {
275 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000276 Kind = LookupCriteria::Member;
Chris Lattner95d58f32009-01-16 19:44:00 +0000277 }
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000278 // Unqualified lookup
279 return LookupName(S, Name,
280 LookupCriteria(Kind, !LookInParent,
281 getLangOptions().CPlusPlus));
Reid Spencer5f016e22007-07-11 17:01:13 +0000282}
283
Steve Naroff3e8ffd22009-01-29 00:07:50 +0000284Sema::LookupResult
285Sema::LookupDeclInContext(DeclarationName Name, unsigned NSI,
286 const DeclContext *LookupCtx,
287 bool LookInParent) {
288 assert(LookupCtx && "LookupDeclInContext(): Missing DeclContext");
289 LookupCriteria::NameKind Kind;
290 if (NSI == Decl::IDNS_Ordinary) {
291 Kind = LookupCriteria::Ordinary;
292 } else if (NSI == Decl::IDNS_Tag)
293 Kind = LookupCriteria::Tag;
294 else {
295 assert(NSI == Decl::IDNS_Member &&"Unable to grok LookupDecl NSI argument");
296 Kind = LookupCriteria::Member;
297 }
298 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
299 LookupCriteria(Kind, !LookInParent,
300 getLangOptions().CPlusPlus));
301}
302
Chris Lattner95e2c712008-05-05 22:18:14 +0000303void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000304 if (!Context.getBuiltinVaListType().isNull())
305 return;
306
307 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff3e8ffd22009-01-29 00:07:50 +0000308 Decl *VaDecl = LookupDeclInScope(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000309 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000310 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
311}
312
Reid Spencer5f016e22007-07-11 17:01:13 +0000313/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
314/// lazily create a decl for it.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000315NamedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
316 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000317 Builtin::ID BID = (Builtin::ID)bid;
318
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000319 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000320 InitBuiltinVaListType();
321
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000322 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000323 FunctionDecl *New = FunctionDecl::Create(Context,
324 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000325 SourceLocation(), II, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000326 FunctionDecl::Extern, false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000327
Chris Lattner95e2c712008-05-05 22:18:14 +0000328 // Create Decl objects for each parameter, adding them to the
329 // FunctionDecl.
330 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
331 llvm::SmallVector<ParmVarDecl*, 16> Params;
332 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
333 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000334 FT->getArgType(i), VarDecl::None, 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000335 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000336 }
337
338
339
Chris Lattner7f925cc2008-04-11 07:00:53 +0000340 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000341 // FIXME: This is hideous. We need to teach PushOnScopeChains to
342 // relate Scopes to DeclContexts, and probably eliminate CurContext
343 // entirely, but we're not there yet.
344 DeclContext *SavedContext = CurContext;
345 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000346 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000347 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000348 return New;
349}
350
Sebastian Redlc42e1182008-11-11 11:37:55 +0000351/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
352/// everything from the standard library is defined.
353NamespaceDecl *Sema::GetStdNamespace() {
354 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000355 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000356 DeclContext *Global = Context.getTranslationUnitDecl();
Steve Naroff3e8ffd22009-01-29 00:07:50 +0000357 Decl *Std = LookupDeclInContext(StdIdent, Decl::IDNS_Ordinary, Global);
Sebastian Redlc42e1182008-11-11 11:37:55 +0000358 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
359 }
360 return StdNamespace;
361}
362
Reid Spencer5f016e22007-07-11 17:01:13 +0000363/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
364/// and scope as a previous declaration 'Old'. Figure out how to resolve this
365/// situation, merging decls or emitting diagnostics as appropriate.
366///
Steve Naroffe8043c32008-04-01 23:04:06 +0000367TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000368 bool objc_types = false;
Steve Naroff2b255c42008-09-09 14:32:20 +0000369 // Allow multiple definitions for ObjC built-in typedefs.
370 // FIXME: Verify the underlying types are equivalent!
371 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000372 const IdentifierInfo *TypeID = New->getIdentifier();
373 switch (TypeID->getLength()) {
374 default: break;
375 case 2:
376 if (!TypeID->isStr("id"))
377 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000378 Context.setObjCIdType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000379 objc_types = true;
380 break;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000381 case 5:
382 if (!TypeID->isStr("Class"))
383 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000384 Context.setObjCClassType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000385 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000386 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000387 case 3:
388 if (!TypeID->isStr("SEL"))
389 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000390 Context.setObjCSelType(New);
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000391 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000392 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000393 case 8:
394 if (!TypeID->isStr("Protocol"))
395 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000396 Context.setObjCProtoType(New->getUnderlyingType());
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000397 objc_types = true;
Steve Naroff2b255c42008-09-09 14:32:20 +0000398 return New;
399 }
400 // Fall through - the typedef name was not a builtin type.
401 }
Douglas Gregor66973122009-01-28 17:15:10 +0000402 // Verify the old decl was also a type.
403 TypeDecl *Old = dyn_cast<TypeDecl>(OldD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000404 if (!Old) {
Douglas Gregor66973122009-01-28 17:15:10 +0000405 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000406 << New->getDeclName();
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000407 if (!objc_types)
408 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000409 return New;
410 }
Douglas Gregor66973122009-01-28 17:15:10 +0000411
412 // Determine the "old" type we'll use for checking and diagnostics.
413 QualType OldType;
414 if (TypedefDecl *OldTypedef = dyn_cast<TypedefDecl>(Old))
415 OldType = OldTypedef->getUnderlyingType();
416 else
417 OldType = Context.getTypeDeclType(Old);
418
Chris Lattner99cb9972008-07-25 18:44:27 +0000419 // If the typedef types are not identical, reject them in all languages and
420 // with any extensions enabled.
Douglas Gregor66973122009-01-28 17:15:10 +0000421
422 if (OldType != New->getUnderlyingType() &&
423 Context.getCanonicalType(OldType) !=
Chris Lattner99cb9972008-07-25 18:44:27 +0000424 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000425 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Douglas Gregor66973122009-01-28 17:15:10 +0000426 << New->getUnderlyingType() << OldType;
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000427 if (!objc_types)
428 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000429 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000430 }
Fariborz Jahanianc55a2402009-01-16 19:58:32 +0000431 if (objc_types) return New;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000432 if (getLangOptions().Microsoft) return New;
433
Douglas Gregorbbe27432008-11-21 16:29:06 +0000434 // C++ [dcl.typedef]p2:
435 // In a given non-class scope, a typedef specifier can be used to
436 // redefine the name of any type declared in that scope to refer
437 // to the type to which it already refers.
438 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
439 return New;
440
441 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000442 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
443 // *either* declaration is in a system header. The code below implements
444 // this adhoc compatibility rule. FIXME: The following code will not
445 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000446 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
447 SourceManager &SrcMgr = Context.getSourceManager();
448 if (SrcMgr.isInSystemHeader(Old->getLocation()))
449 return New;
450 if (SrcMgr.isInSystemHeader(New->getLocation()))
451 return New;
452 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000453
Chris Lattner08631c52008-11-23 21:45:46 +0000454 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000455 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 return New;
457}
458
Chris Lattner6b6b5372008-06-26 18:38:35 +0000459/// DeclhasAttr - returns true if decl Declaration already has the target
460/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000461static bool DeclHasAttr(const Decl *decl, const Attr *target) {
462 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
463 if (attr->getKind() == target->getKind())
464 return true;
465
466 return false;
467}
468
469/// MergeAttributes - append attributes from the Old decl to the New one.
470static void MergeAttributes(Decl *New, Decl *Old) {
471 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
472
Chris Lattnerddee4232008-03-03 03:28:21 +0000473 while (attr) {
474 tmp = attr;
475 attr = attr->getNext();
476
477 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000478 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000479 New->addAttr(tmp);
480 } else {
481 tmp->setNext(0);
482 delete(tmp);
483 }
484 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000485
486 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000487}
488
Chris Lattner04421082008-04-08 04:40:51 +0000489/// MergeFunctionDecl - We just parsed a function 'New' from
490/// declarator D which has the same name and scope as a previous
491/// declaration 'Old'. Figure out how to resolve this situation,
492/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000493/// Redeclaration will be set true if this New is a redeclaration OldD.
494///
495/// In C++, New and Old must be declarations that are not
496/// overloaded. Use IsOverload to determine whether New and Old are
497/// overloaded, and to select the Old declaration that New should be
498/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000499FunctionDecl *
500Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000501 assert(!isa<OverloadedFunctionDecl>(OldD) &&
502 "Cannot merge with an overloaded function declaration");
503
Douglas Gregorf0097952008-04-21 02:02:58 +0000504 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 // Verify the old decl was also a function.
506 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
507 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000508 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000509 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000510 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 return New;
512 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000513
514 // Determine whether the previous declaration was a definition,
515 // implicit declaration, or a declaration.
516 diag::kind PrevDiag;
517 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000518 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000519 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000520 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000521 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000522 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000523
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000524 QualType OldQType = Context.getCanonicalType(Old->getType());
525 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000526
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000527 if (getLangOptions().CPlusPlus) {
528 // (C++98 13.1p2):
529 // Certain function declarations cannot be overloaded:
530 // -- Function declarations that differ only in the return type
531 // cannot be overloaded.
532 QualType OldReturnType
533 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
534 QualType NewReturnType
535 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
536 if (OldReturnType != NewReturnType) {
537 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
538 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000539 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000540 return New;
541 }
542
543 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
544 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
545 if (OldMethod && NewMethod) {
546 // -- Member function declarations with the same name and the
547 // same parameter types cannot be overloaded if any of them
548 // is a static member function declaration.
549 if (OldMethod->isStatic() || NewMethod->isStatic()) {
550 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
551 Diag(Old->getLocation(), PrevDiag);
552 return New;
553 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000554
555 // C++ [class.mem]p1:
556 // [...] A member shall not be declared twice in the
557 // member-specification, except that a nested class or member
558 // class template can be declared and then later defined.
559 if (OldMethod->getLexicalDeclContext() ==
560 NewMethod->getLexicalDeclContext()) {
561 unsigned NewDiag;
562 if (isa<CXXConstructorDecl>(OldMethod))
563 NewDiag = diag::err_constructor_redeclared;
564 else if (isa<CXXDestructorDecl>(NewMethod))
565 NewDiag = diag::err_destructor_redeclared;
566 else if (isa<CXXConversionDecl>(NewMethod))
567 NewDiag = diag::err_conv_function_redeclared;
568 else
569 NewDiag = diag::err_member_redeclared;
570
571 Diag(New->getLocation(), NewDiag);
572 Diag(Old->getLocation(), PrevDiag);
573 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000574 }
575
576 // (C++98 8.3.5p3):
577 // All declarations for a function shall agree exactly in both the
578 // return type and the parameter-type-list.
579 if (OldQType == NewQType) {
580 // We have a redeclaration.
581 MergeAttributes(New, Old);
582 Redeclaration = true;
583 return MergeCXXFunctionDecl(New, Old);
584 }
585
586 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000587 }
Chris Lattner04421082008-04-08 04:40:51 +0000588
589 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000590 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000591 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000592 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000593 MergeAttributes(New, Old);
594 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000595 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000596 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000597
Steve Naroff837618c2008-01-16 15:01:34 +0000598 // A function that has already been declared has been redeclared or defined
599 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000600
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
602 // TODO: This is totally simplistic. It should handle merging functions
603 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000604 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000605 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000606 return New;
607}
608
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000609/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000610static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000611 if (VD->isFileVarDecl())
612 return (!VD->getInit() &&
613 (VD->getStorageClass() == VarDecl::None ||
614 VD->getStorageClass() == VarDecl::Static));
615 return false;
616}
617
618/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
619/// when dealing with C "tentative" external object definitions (C99 6.9.2).
620void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
621 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000622 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000623
Douglas Gregore21b9942009-01-07 16:34:42 +0000624 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000625 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000626 for (IdentifierResolver::iterator
627 I = IdResolver.begin(VD->getIdentifier(),
628 VD->getDeclContext(), false/*LookInParentCtx*/),
629 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000630 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000631 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
632
Steve Narofff855e6f2008-08-10 15:20:13 +0000633 // Handle the following case:
634 // int a[10];
635 // int a[]; - the code below makes sure we set the correct type.
636 // int a[11]; - this is an error, size isn't 10.
637 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
638 OldDecl->getType()->isConstantArrayType())
639 VD->setType(OldDecl->getType());
640
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000641 // Check for "tentative" definitions. We can't accomplish this in
642 // MergeVarDecl since the initializer hasn't been attached.
643 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
644 continue;
645
646 // Handle __private_extern__ just like extern.
647 if (OldDecl->getStorageClass() != VarDecl::Extern &&
648 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
649 VD->getStorageClass() != VarDecl::Extern &&
650 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000651 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000652 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000653 }
654 }
655 }
656}
657
Reid Spencer5f016e22007-07-11 17:01:13 +0000658/// MergeVarDecl - We just parsed a variable 'New' which has the same name
659/// and scope as a previous declaration 'Old'. Figure out how to resolve this
660/// situation, merging decls or emitting diagnostics as appropriate.
661///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000662/// Tentative definition rules (C99 6.9.2p2) are checked by
663/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
664/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000665///
Steve Naroffe8043c32008-04-01 23:04:06 +0000666VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 // Verify the old decl was also a variable.
668 VarDecl *Old = dyn_cast<VarDecl>(OldD);
669 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000670 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000671 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000672 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000673 return New;
674 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000675
676 MergeAttributes(New, Old);
677
Eli Friedman13ca96a2009-01-24 23:49:55 +0000678 // Merge the types
679 QualType MergedT = Context.mergeTypes(New->getType(), Old->getType());
680 if (MergedT.isNull()) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000681 Diag(New->getLocation(), diag::err_redefinition_different_type)
682 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000683 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000684 return New;
685 }
Eli Friedman13ca96a2009-01-24 23:49:55 +0000686 New->setType(MergedT);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000687 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
688 if (New->getStorageClass() == VarDecl::Static &&
689 (Old->getStorageClass() == VarDecl::None ||
690 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000691 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000692 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000693 return New;
694 }
695 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
696 if (New->getStorageClass() != VarDecl::Static &&
697 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000698 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000699 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000700 return New;
701 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000702 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
703 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000704 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000705 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000706 }
707 return New;
708}
709
Chris Lattner04421082008-04-08 04:40:51 +0000710/// CheckParmsForFunctionDef - Check that the parameters of the given
711/// function are appropriate for the definition of a function. This
712/// takes care of any checks that cannot be performed on the
713/// declaration itself, e.g., that the types of each of the function
714/// parameters are complete.
715bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
716 bool HasInvalidParm = false;
717 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
718 ParmVarDecl *Param = FD->getParamDecl(p);
719
720 // C99 6.7.5.3p4: the parameters in a parameter type list in a
721 // function declarator that is part of a function definition of
722 // that function shall not have incomplete type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +0000723 if (!Param->isInvalidDecl() &&
724 DiagnoseIncompleteType(Param->getLocation(), Param->getType(),
725 diag::err_typecheck_decl_incomplete_type)) {
Chris Lattner04421082008-04-08 04:40:51 +0000726 Param->setInvalidDecl();
727 HasInvalidParm = true;
728 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000729
730 // C99 6.9.1p5: If the declarator includes a parameter type list, the
731 // declaration of each parameter shall include an identifier.
732 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
733 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000734 }
735
736 return HasInvalidParm;
737}
738
Reid Spencer5f016e22007-07-11 17:01:13 +0000739/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
740/// no declarator (e.g. "struct foo;") is parsed.
741Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000742 TagDecl *Tag
743 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
744 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
745 if (!Record->getDeclName() && Record->isDefinition() &&
746 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
747 return BuildAnonymousStructOrUnion(S, DS, Record);
748
749 // Microsoft allows unnamed struct/union fields. Don't complain
750 // about them.
751 // FIXME: Should we support Microsoft's extensions in this area?
752 if (Record->getDeclName() && getLangOptions().Microsoft)
753 return Tag;
754 }
755
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000756 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000757 // Warn about typedefs of enums without names, since this is an
758 // extension in both Microsoft an GNU.
Douglas Gregor8158f692009-01-17 02:55:50 +0000759 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef &&
760 Tag && isa<EnumDecl>(Tag)) {
Douglas Gregor21282df2009-01-22 16:23:54 +0000761 Diag(DS.getSourceRange().getBegin(), diag::ext_typedef_without_a_name)
Douglas Gregoree159c12009-01-13 23:10:51 +0000762 << DS.getSourceRange();
763 return Tag;
764 }
765
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000766 // FIXME: This diagnostic is emitted even when various previous
767 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
768 // DeclSpec has no means of communicating this information, and the
769 // responsible parser functions are quite far apart.
770 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
771 << DS.getSourceRange();
772 return 0;
773 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000774
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000775 return Tag;
776}
777
778/// InjectAnonymousStructOrUnionMembers - Inject the members of the
779/// anonymous struct or union AnonRecord into the owning context Owner
780/// and scope S. This routine will be invoked just after we realize
781/// that an unnamed union or struct is actually an anonymous union or
782/// struct, e.g.,
783///
784/// @code
785/// union {
786/// int i;
787/// float f;
788/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
789/// // f into the surrounding scope.x
790/// @endcode
791///
792/// This routine is recursive, injecting the names of nested anonymous
793/// structs/unions into the owning context and scope as well.
794bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
795 RecordDecl *AnonRecord) {
796 bool Invalid = false;
797 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
798 FEnd = AnonRecord->field_end();
799 F != FEnd; ++F) {
800 if ((*F)->getDeclName()) {
Steve Naroff3e8ffd22009-01-29 00:07:50 +0000801 Decl *PrevDecl = LookupDeclInContext((*F)->getDeclName(),
802 Decl::IDNS_Ordinary, Owner, false);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000803 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
804 // C++ [class.union]p2:
805 // The names of the members of an anonymous union shall be
806 // distinct from the names of any other entity in the
807 // scope in which the anonymous union is declared.
808 unsigned diagKind
809 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
810 : diag::err_anonymous_struct_member_redecl;
811 Diag((*F)->getLocation(), diagKind)
812 << (*F)->getDeclName();
813 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
814 Invalid = true;
815 } else {
816 // C++ [class.union]p2:
817 // For the purpose of name lookup, after the anonymous union
818 // definition, the members of the anonymous union are
819 // considered to have been defined in the scope in which the
820 // anonymous union is declared.
Douglas Gregor40f4e692009-01-20 16:54:50 +0000821 Owner->makeDeclVisibleInContext(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000822 S->AddDecl(*F);
823 IdResolver.AddDecl(*F);
824 }
825 } else if (const RecordType *InnerRecordType
826 = (*F)->getType()->getAsRecordType()) {
827 RecordDecl *InnerRecord = InnerRecordType->getDecl();
828 if (InnerRecord->isAnonymousStructOrUnion())
829 Invalid = Invalid ||
830 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
831 }
832 }
833
834 return Invalid;
835}
836
837/// ActOnAnonymousStructOrUnion - Handle the declaration of an
838/// anonymous structure or union. Anonymous unions are a C++ feature
839/// (C++ [class.union]) and a GNU C extension; anonymous structures
840/// are a GNU C and GNU C++ extension.
841Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
842 RecordDecl *Record) {
843 DeclContext *Owner = Record->getDeclContext();
844
845 // Diagnose whether this anonymous struct/union is an extension.
846 if (Record->isUnion() && !getLangOptions().CPlusPlus)
847 Diag(Record->getLocation(), diag::ext_anonymous_union);
848 else if (!Record->isUnion())
849 Diag(Record->getLocation(), diag::ext_anonymous_struct);
850
851 // C and C++ require different kinds of checks for anonymous
852 // structs/unions.
853 bool Invalid = false;
854 if (getLangOptions().CPlusPlus) {
855 const char* PrevSpec = 0;
856 // C++ [class.union]p3:
857 // Anonymous unions declared in a named namespace or in the
858 // global namespace shall be declared static.
859 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
860 (isa<TranslationUnitDecl>(Owner) ||
861 (isa<NamespaceDecl>(Owner) &&
862 cast<NamespaceDecl>(Owner)->getDeclName()))) {
863 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
864 Invalid = true;
865
866 // Recover by adding 'static'.
867 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
868 }
869 // C++ [class.union]p3:
870 // A storage class is not allowed in a declaration of an
871 // anonymous union in a class scope.
872 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
873 isa<RecordDecl>(Owner)) {
874 Diag(DS.getStorageClassSpecLoc(),
875 diag::err_anonymous_union_with_storage_spec);
876 Invalid = true;
877
878 // Recover by removing the storage specifier.
879 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
880 PrevSpec);
881 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000882
883 // C++ [class.union]p2:
884 // The member-specification of an anonymous union shall only
885 // define non-static data members. [Note: nested types and
886 // functions cannot be declared within an anonymous union. ]
887 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
888 MemEnd = Record->decls_end();
889 Mem != MemEnd; ++Mem) {
890 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
891 // C++ [class.union]p3:
892 // An anonymous union shall not have private or protected
893 // members (clause 11).
894 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
895 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
896 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
897 Invalid = true;
898 }
899 } else if ((*Mem)->isImplicit()) {
900 // Any implicit members are fine.
901 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
902 if (!MemRecord->isAnonymousStructOrUnion() &&
903 MemRecord->getDeclName()) {
904 // This is a nested type declaration.
905 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
906 << (int)Record->isUnion();
907 Invalid = true;
908 }
909 } else {
910 // We have something that isn't a non-static data
911 // member. Complain about it.
912 unsigned DK = diag::err_anonymous_record_bad_member;
913 if (isa<TypeDecl>(*Mem))
914 DK = diag::err_anonymous_record_with_type;
915 else if (isa<FunctionDecl>(*Mem))
916 DK = diag::err_anonymous_record_with_function;
917 else if (isa<VarDecl>(*Mem))
918 DK = diag::err_anonymous_record_with_static;
919 Diag((*Mem)->getLocation(), DK)
920 << (int)Record->isUnion();
921 Invalid = true;
922 }
923 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000924 } else {
925 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000926 if (Record->isUnion() && !Owner->isRecord()) {
927 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
928 << (int)getLangOptions().CPlusPlus;
929 Invalid = true;
930 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000931 }
932
933 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000934 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
935 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000936 Invalid = true;
937 }
938
939 // Create a declaration for this anonymous struct/union.
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000940 NamedDecl *Anon = 0;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000941 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
942 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
943 /*IdentifierInfo=*/0,
944 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000945 /*BitWidth=*/0, /*Mutable=*/false);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000946 Anon->setAccess(AS_public);
947 if (getLangOptions().CPlusPlus)
948 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000949 } else {
950 VarDecl::StorageClass SC;
951 switch (DS.getStorageClassSpec()) {
952 default: assert(0 && "Unknown storage class!");
953 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
954 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
955 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
956 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
957 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
958 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
959 case DeclSpec::SCS_mutable:
960 // mutable can only appear on non-static class members, so it's always
961 // an error here
962 Diag(Record->getLocation(), diag::err_mutable_nonmember);
963 Invalid = true;
964 SC = VarDecl::None;
965 break;
966 }
967
968 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
969 /*IdentifierInfo=*/0,
970 Context.getTypeDeclType(Record),
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000971 SC, DS.getSourceRange().getBegin());
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000972 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000973 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000974
975 // Add the anonymous struct/union object to the current
976 // context. We'll be referencing this object when we refer to one of
977 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000978 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000979
980 // Inject the members of the anonymous struct/union into the owning
981 // context and into the identifier resolver chain for name lookup
982 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000983 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
984 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000985
986 // Mark this as an anonymous struct/union type. Note that we do not
987 // do this until after we have already checked and injected the
988 // members of this anonymous struct/union type, because otherwise
989 // the members could be injected twice: once by DeclContext when it
990 // builds its lookup table, and once by
991 // InjectAnonymousStructOrUnionMembers.
992 Record->setAnonymousStructOrUnion(true);
993
994 if (Invalid)
995 Anon->setInvalidDecl();
996
997 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000998}
999
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001000bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
1001 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +00001002 // Get the type before calling CheckSingleAssignmentConstraints(), since
1003 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +00001004 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +00001005
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001006 if (getLangOptions().CPlusPlus) {
1007 // FIXME: I dislike this error message. A lot.
1008 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
1009 return Diag(Init->getSourceRange().getBegin(),
1010 diag::err_typecheck_convert_incompatible)
1011 << DeclType << Init->getType() << "initializing"
1012 << Init->getSourceRange();
1013
1014 return false;
1015 }
Douglas Gregor45920e82008-12-19 17:40:08 +00001016
Chris Lattner5cf216b2008-01-04 18:04:52 +00001017 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
1018 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
1019 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +00001020}
1021
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001022bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001023 const ArrayType *AT = Context.getAsArrayType(DeclT);
1024
1025 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001026 // C99 6.7.8p14. We have an array of character type with unknown size
1027 // being initialized to a string literal.
1028 llvm::APSInt ConstVal(32);
1029 ConstVal = strLiteral->getByteLength() + 1;
1030 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +00001031 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001032 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001033 } else {
1034 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001035 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001036 // FIXME: Avoid truncation for 64-bit length strings.
1037 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001038 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001039 diag::warn_initializer_string_for_char_array_too_long)
1040 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001041 }
1042 // Set type from "char *" to "constant array of char".
1043 strLiteral->setType(DeclT);
1044 // For now, we always return false (meaning success).
1045 return false;
1046}
1047
1048StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001049 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001050 if (AT && AT->getElementType()->isCharType()) {
Anders Carlsson91b9f202009-01-24 17:47:50 +00001051 return dyn_cast<StringLiteral>(Init->IgnoreParens());
Steve Naroffa9960332008-01-25 00:51:06 +00001052 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001053 return 0;
1054}
1055
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001056bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1057 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001058 DeclarationName InitEntity,
1059 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001060 if (DeclType->isDependentType() || Init->isTypeDependent())
1061 return false;
1062
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001063 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001064 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001065 // (8.3.2), shall be initialized by an object, or function, of
1066 // type T or by an object that can be converted into a T.
1067 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001068 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001069
Steve Naroffca107302008-01-21 23:53:58 +00001070 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1071 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001072 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001073 return Diag(InitLoc, diag::err_variable_object_no_init)
1074 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001075
Steve Naroff2fdc3742007-12-10 22:44:33 +00001076 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1077 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001078 // FIXME: Handle wide strings
1079 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1080 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001081
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001082 // C++ [dcl.init]p14:
1083 // -- If the destination type is a (possibly cv-qualified) class
1084 // type:
1085 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1086 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1087 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1088
1089 // -- If the initialization is direct-initialization, or if it is
1090 // copy-initialization where the cv-unqualified version of the
1091 // source type is the same class as, or a derived class of, the
1092 // class of the destination, constructors are considered.
1093 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1094 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1095 CXXConstructorDecl *Constructor
1096 = PerformInitializationByConstructor(DeclType, &Init, 1,
1097 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001098 InitEntity,
1099 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001100 return Constructor == 0;
1101 }
1102
1103 // -- Otherwise (i.e., for the remaining copy-initialization
1104 // cases), user-defined conversion sequences that can
1105 // convert from the source type to the destination type or
1106 // (when a conversion function is used) to a derived class
1107 // thereof are enumerated as described in 13.3.1.4, and the
1108 // best one is chosen through overload resolution
1109 // (13.3). If the conversion cannot be done or is
1110 // ambiguous, the initialization is ill-formed. The
1111 // function selected is called with the initializer
1112 // expression as its argument; if the function is a
1113 // constructor, the call initializes a temporary of the
1114 // destination type.
1115 // FIXME: We're pretending to do copy elision here; return to
1116 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001117 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001118 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001119
Douglas Gregor61366e92008-12-24 00:01:03 +00001120 if (InitEntity)
1121 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1122 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1123 << Init->getType() << Init->getSourceRange();
1124 else
1125 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1126 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1127 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001128 }
1129
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001130 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001131 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001132 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1133 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001134
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001135 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001136 } else if (getLangOptions().CPlusPlus) {
1137 // C++ [dcl.init]p14:
1138 // [...] If the class is an aggregate (8.5.1), and the initializer
1139 // is a brace-enclosed list, see 8.5.1.
1140 //
1141 // Note: 8.5.1 is handled below; here, we diagnose the case where
1142 // we have an initializer list and a destination type that is not
1143 // an aggregate.
1144 // FIXME: In C++0x, this is yet another form of initialization.
1145 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1146 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1147 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001148 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001149 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001150 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001151 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001152
Douglas Gregorc34ee5e2009-01-29 00:45:39 +00001153 bool hadError = CheckInitList(InitList, DeclType);
1154 Init = InitList;
1155 return hadError;
Steve Narofff0090632007-09-02 02:04:30 +00001156}
1157
Douglas Gregor10bd3682008-11-17 22:58:34 +00001158/// GetNameForDeclarator - Determine the full declaration name for the
1159/// given Declarator.
1160DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1161 switch (D.getKind()) {
1162 case Declarator::DK_Abstract:
1163 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1164 return DeclarationName();
1165
1166 case Declarator::DK_Normal:
1167 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1168 return DeclarationName(D.getIdentifier());
1169
1170 case Declarator::DK_Constructor: {
1171 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1172 Ty = Context.getCanonicalType(Ty);
1173 return Context.DeclarationNames.getCXXConstructorName(Ty);
1174 }
1175
1176 case Declarator::DK_Destructor: {
1177 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1178 Ty = Context.getCanonicalType(Ty);
1179 return Context.DeclarationNames.getCXXDestructorName(Ty);
1180 }
1181
1182 case Declarator::DK_Conversion: {
1183 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1184 Ty = Context.getCanonicalType(Ty);
1185 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1186 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001187
1188 case Declarator::DK_Operator:
1189 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1190 return Context.DeclarationNames.getCXXOperatorName(
1191 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001192 }
1193
1194 assert(false && "Unknown name kind");
1195 return DeclarationName();
1196}
1197
Douglas Gregor584049d2008-12-15 23:53:10 +00001198/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1199/// functions Declaration and Definition are "nearly" matching. This
1200/// heuristic is used to improve diagnostics in the case where an
1201/// out-of-line member function definition doesn't match any
1202/// declaration within the class.
1203static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1204 FunctionDecl *Declaration,
1205 FunctionDecl *Definition) {
1206 if (Declaration->param_size() != Definition->param_size())
1207 return false;
1208 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1209 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1210 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1211
1212 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1213 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1214 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1215 return false;
1216 }
1217
1218 return true;
1219}
1220
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001221Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001222Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1223 bool IsFunctionDefinition) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001224 NamedDecl *LastDeclarator = dyn_cast_or_null<NamedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001225 DeclarationName Name = GetNameForDeclarator(D);
1226
Chris Lattnere80a59c2007-07-25 00:24:17 +00001227 // All of these full declarators require an identifier. If it doesn't have
1228 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001229 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001230 if (!D.getInvalidType()) // Reject this if we think it is valid.
1231 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001232 diag::err_declarator_need_ident)
1233 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001234 return 0;
1235 }
1236
Chris Lattner31e05722007-08-26 06:24:45 +00001237 // The scope passed in may not be a decl scope. Zip up the scope tree until
1238 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001239 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1240 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001241 S = S->getParent();
1242
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001243 DeclContext *DC;
1244 Decl *PrevDecl;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001245 NamedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001246 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001247
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001248 // See if this is a redefinition of a variable in the same scope.
1249 if (!D.getCXXScopeSpec().isSet()) {
1250 DC = CurContext;
Steve Naroff3e8ffd22009-01-29 00:07:50 +00001251 PrevDecl = LookupDeclInScope(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001252 } else { // Something like "int foo::x;"
1253 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Steve Naroff3e8ffd22009-01-29 00:07:50 +00001254 PrevDecl = DC ? LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC)
1255 : LookupDeclInScope(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001256
1257 // C++ 7.3.1.2p2:
1258 // Members (including explicit specializations of templates) of a named
1259 // namespace can also be defined outside that namespace by explicit
1260 // qualification of the name being defined, provided that the entity being
1261 // defined was already declared in the namespace and the definition appears
1262 // after the point of declaration in a namespace that encloses the
1263 // declarations namespace.
1264 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001265 // Note that we only check the context at this point. We don't yet
1266 // have enough information to make sure that PrevDecl is actually
1267 // the declaration we want to match. For example, given:
1268 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001269 // class X {
1270 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001271 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001272 // };
1273 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001274 // void X::f(int) { } // ill-formed
1275 //
1276 // In this case, PrevDecl will point to the overload set
1277 // containing the two f's declared in X, but neither of them
1278 // matches.
1279 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001280 // The qualifying scope doesn't enclose the original declaration.
1281 // Emit diagnostic based on current scope.
1282 SourceLocation L = D.getIdentifierLoc();
1283 SourceRange R = D.getCXXScopeSpec().getRange();
1284 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001285 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001286 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001287 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001288 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001289 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001290 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001291 }
1292 }
1293
Douglas Gregorf57172b2008-12-08 18:40:42 +00001294 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001295 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001296 InvalidDecl = InvalidDecl
1297 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001298 // Just pretend that we didn't see the previous declaration.
1299 PrevDecl = 0;
1300 }
1301
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001302 // In C++, the previous declaration we find might be a tag type
1303 // (class or enum). In this case, the new declaration will hide the
Douglas Gregor66973122009-01-28 17:15:10 +00001304 // tag type. Note that this does does not apply if we're declaring a
1305 // typedef (C++ [dcl.typedef]p4).
1306 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag &&
1307 D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef)
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001308 PrevDecl = 0;
1309
Chris Lattner41af0932007-11-14 06:34:38 +00001310 QualType R = GetTypeForDeclarator(D, S);
1311 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1312
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001314 New = ActOnTypedefDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1315 InvalidDecl);
Chris Lattner41af0932007-11-14 06:34:38 +00001316 } else if (R.getTypePtr()->isFunctionType()) {
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001317 New = ActOnFunctionDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1318 IsFunctionDefinition, InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001319 } else {
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001320 New = ActOnVariableDeclarator(S, D, DC, R, LastDeclarator, PrevDecl,
1321 InvalidDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001322 }
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001323
1324 if (New == 0)
1325 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00001326
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001327 // Set the lexical context. If the declarator has a C++ scope specifier, the
1328 // lexical context will be different from the semantic context.
1329 New->setLexicalDeclContext(CurContext);
1330
Reid Spencer5f016e22007-07-11 17:01:13 +00001331 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001332 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001333 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001334 // If any semantic error occurred, mark the decl as invalid.
1335 if (D.getInvalidType() || InvalidDecl)
1336 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001337
1338 return New;
1339}
1340
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001341NamedDecl*
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001342Sema::ActOnTypedefDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001343 QualType R, Decl* LastDeclarator,
Zhongxing Xud5ed8c32009-01-16 03:34:13 +00001344 Decl* PrevDecl, bool& InvalidDecl) {
1345 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1346 if (D.getCXXScopeSpec().isSet()) {
1347 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1348 << D.getCXXScopeSpec().getRange();
1349 InvalidDecl = true;
1350 // Pretend we didn't see the scope specifier.
1351 DC = 0;
1352 }
1353
1354 // Check that there are no default arguments (C++ only).
1355 if (getLangOptions().CPlusPlus)
1356 CheckExtraCXXDefaultArguments(D);
1357
1358 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
1359 if (!NewTD) return 0;
1360
1361 // Handle attributes prior to checking for duplicates in MergeVarDecl
1362 ProcessDeclAttributes(NewTD, D);
1363 // Merge the decl with the existing one if appropriate. If the decl is
1364 // in an outer scope, it isn't the same thing.
1365 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1366 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1367 if (NewTD == 0) return 0;
1368 }
1369
1370 if (S->getFnParent() == 0) {
1371 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1372 // then it shall have block scope.
1373 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
1374 if (NewTD->getUnderlyingType()->isVariableArrayType())
1375 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1376 else
1377 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1378
1379 InvalidDecl = true;
1380 }
1381 }
1382 return NewTD;
1383}
1384
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001385NamedDecl*
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001386Sema::ActOnVariableDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001387 QualType R, Decl* LastDeclarator,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001388 Decl* PrevDecl, bool& InvalidDecl) {
1389 DeclarationName Name = GetNameForDeclarator(D);
1390
1391 // Check that there are no default arguments (C++ only).
1392 if (getLangOptions().CPlusPlus)
1393 CheckExtraCXXDefaultArguments(D);
1394
1395 if (R.getTypePtr()->isObjCInterfaceType()) {
1396 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1397 << D.getIdentifier();
1398 InvalidDecl = true;
1399 }
1400
1401 VarDecl *NewVD;
1402 VarDecl::StorageClass SC;
1403 switch (D.getDeclSpec().getStorageClassSpec()) {
1404 default: assert(0 && "Unknown storage class!");
1405 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1406 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1407 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1408 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1409 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1410 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
1411 case DeclSpec::SCS_mutable:
1412 // mutable can only appear on non-static class members, so it's always
1413 // an error here
1414 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1415 InvalidDecl = true;
1416 SC = VarDecl::None;
1417 break;
1418 }
1419
1420 IdentifierInfo *II = Name.getAsIdentifierInfo();
1421 if (!II) {
1422 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1423 << Name.getAsString();
1424 return 0;
1425 }
1426
1427 if (DC->isRecord()) {
1428 // This is a static data member for a C++ class.
1429 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
1430 D.getIdentifierLoc(), II,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001431 R);
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001432 } else {
1433 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
1434 if (S->getFnParent() == 0) {
1435 // C99 6.9p2: The storage-class specifiers auto and register shall not
1436 // appear in the declaration specifiers in an external declaration.
1437 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1438 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
1439 InvalidDecl = true;
1440 }
1441 }
1442 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001443 II, R, SC,
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001444 // FIXME: Move to DeclGroup...
1445 D.getDeclSpec().getSourceRange().getBegin());
1446 NewVD->setThreadSpecified(ThreadSpecified);
1447 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001448 NewVD->setNextDeclarator(LastDeclarator);
1449
Zhongxing Xucb8f4f12009-01-16 02:36:34 +00001450 // Handle attributes prior to checking for duplicates in MergeVarDecl
1451 ProcessDeclAttributes(NewVD, D);
1452
1453 // Handle GNU asm-label extension (encoded as an attribute).
1454 if (Expr *E = (Expr*) D.getAsmLabel()) {
1455 // The parser guarantees this is a string.
1456 StringLiteral *SE = cast<StringLiteral>(E);
1457 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1458 SE->getByteLength())));
1459 }
1460
1461 // Emit an error if an address space was applied to decl with local storage.
1462 // This includes arrays of objects with address space qualifiers, but not
1463 // automatic variables that point to other address spaces.
1464 // ISO/IEC TR 18037 S5.1.2
1465 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1466 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1467 InvalidDecl = true;
1468 }
1469 // Merge the decl with the existing one if appropriate. If the decl is
1470 // in an outer scope, it isn't the same thing.
1471 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
1472 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1473 // The user tried to define a non-static data member
1474 // out-of-line (C++ [dcl.meaning]p1).
1475 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1476 << D.getCXXScopeSpec().getRange();
1477 NewVD->Destroy(Context);
1478 return 0;
1479 }
1480
1481 NewVD = MergeVarDecl(NewVD, PrevDecl);
1482 if (NewVD == 0) return 0;
1483
1484 if (D.getCXXScopeSpec().isSet()) {
1485 // No previous declaration in the qualifying scope.
1486 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1487 << Name << D.getCXXScopeSpec().getRange();
1488 InvalidDecl = true;
1489 }
1490 }
1491 return NewVD;
1492}
1493
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001494NamedDecl*
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001495Sema::ActOnFunctionDeclarator(Scope* S, Declarator& D, DeclContext* DC,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001496 QualType R, Decl *LastDeclarator,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001497 Decl* PrevDecl, bool IsFunctionDefinition,
1498 bool& InvalidDecl) {
1499 assert(R.getTypePtr()->isFunctionType());
1500
1501 DeclarationName Name = GetNameForDeclarator(D);
1502 FunctionDecl::StorageClass SC = FunctionDecl::None;
1503 switch (D.getDeclSpec().getStorageClassSpec()) {
1504 default: assert(0 && "Unknown storage class!");
1505 case DeclSpec::SCS_auto:
1506 case DeclSpec::SCS_register:
1507 case DeclSpec::SCS_mutable:
1508 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
1509 InvalidDecl = true;
1510 break;
1511 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1512 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1513 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
1514 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
1515 }
1516
1517 bool isInline = D.getDeclSpec().isInlineSpecified();
1518 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
1519 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1520
1521 FunctionDecl *NewFD;
1522 if (D.getKind() == Declarator::DK_Constructor) {
1523 // This is a C++ constructor declaration.
1524 assert(DC->isRecord() &&
1525 "Constructors can only be declared in a member context");
1526
1527 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
1528
1529 // Create the new declaration
1530 NewFD = CXXConstructorDecl::Create(Context,
1531 cast<CXXRecordDecl>(DC),
1532 D.getIdentifierLoc(), Name, R,
1533 isExplicit, isInline,
1534 /*isImplicitlyDeclared=*/false);
1535
1536 if (InvalidDecl)
1537 NewFD->setInvalidDecl();
1538 } else if (D.getKind() == Declarator::DK_Destructor) {
1539 // This is a C++ destructor declaration.
1540 if (DC->isRecord()) {
1541 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
1542
1543 NewFD = CXXDestructorDecl::Create(Context,
1544 cast<CXXRecordDecl>(DC),
1545 D.getIdentifierLoc(), Name, R,
1546 isInline,
1547 /*isImplicitlyDeclared=*/false);
1548
1549 if (InvalidDecl)
1550 NewFD->setInvalidDecl();
1551 } else {
1552 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1553
1554 // Create a FunctionDecl to satisfy the function definition parsing
1555 // code path.
1556 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001557 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001558 // FIXME: Move to DeclGroup...
1559 D.getDeclSpec().getSourceRange().getBegin());
1560 InvalidDecl = true;
1561 NewFD->setInvalidDecl();
1562 }
1563 } else if (D.getKind() == Declarator::DK_Conversion) {
1564 if (!DC->isRecord()) {
1565 Diag(D.getIdentifierLoc(),
1566 diag::err_conv_function_not_member);
1567 return 0;
1568 } else {
1569 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
1570
1571 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
1572 D.getIdentifierLoc(), Name, R,
1573 isInline, isExplicit);
1574
1575 if (InvalidDecl)
1576 NewFD->setInvalidDecl();
1577 }
1578 } else if (DC->isRecord()) {
1579 // This is a C++ method declaration.
1580 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
1581 D.getIdentifierLoc(), Name, R,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001582 (SC == FunctionDecl::Static), isInline);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001583 } else {
1584 NewFD = FunctionDecl::Create(Context, DC,
1585 D.getIdentifierLoc(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001586 Name, R, SC, isInline,
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001587 // FIXME: Move to DeclGroup...
1588 D.getDeclSpec().getSourceRange().getBegin());
1589 }
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001590 NewFD->setNextDeclarator(LastDeclarator);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001591
1592 // Set the lexical context. If the declarator has a C++
1593 // scope specifier, the lexical context will be different
1594 // from the semantic context.
1595 NewFD->setLexicalDeclContext(CurContext);
1596
1597 // Handle GNU asm-label extension (encoded as an attribute).
1598 if (Expr *E = (Expr*) D.getAsmLabel()) {
1599 // The parser guarantees this is a string.
1600 StringLiteral *SE = cast<StringLiteral>(E);
1601 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1602 SE->getByteLength())));
1603 }
1604
1605 // Copy the parameter declarations from the declarator D to
1606 // the function declaration NewFD, if they are available.
1607 if (D.getNumTypeObjects() > 0) {
1608 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1609
1610 // Create Decl objects for each parameter, adding them to the
1611 // FunctionDecl.
1612 llvm::SmallVector<ParmVarDecl*, 16> Params;
1613
1614 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1615 // function that takes no arguments, not a function that takes a
1616 // single void argument.
1617 // We let through "const void" here because Sema::GetTypeForDeclarator
1618 // already checks for that case.
1619 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1620 FTI.ArgInfo[0].Param &&
1621 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1622 // empty arg list, don't push any params.
1623 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1624
1625 // In C++, the empty parameter-type-list must be spelled "void"; a
1626 // typedef of void is not permitted.
1627 if (getLangOptions().CPlusPlus &&
1628 Param->getType().getUnqualifiedType() != Context.VoidTy) {
1629 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1630 }
1631 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
1632 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1633 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1634 }
1635
1636 NewFD->setParams(Context, &Params[0], Params.size());
1637 } else if (R->getAsTypedefType()) {
1638 // When we're declaring a function with a typedef, as in the
1639 // following example, we'll need to synthesize (unnamed)
1640 // parameters for use in the declaration.
1641 //
1642 // @code
1643 // typedef void fn(int);
1644 // fn f;
1645 // @endcode
1646 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1647 if (!FT) {
1648 // This is a typedef of a function with no prototype, so we
1649 // don't need to do anything.
1650 } else if ((FT->getNumArgs() == 0) ||
1651 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1652 FT->getArgType(0)->isVoidType())) {
1653 // This is a zero-argument function. We don't need to do anything.
1654 } else {
1655 // Synthesize a parameter for each argument type.
1656 llvm::SmallVector<ParmVarDecl*, 16> Params;
1657 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1658 ArgType != FT->arg_type_end(); ++ArgType) {
1659 Params.push_back(ParmVarDecl::Create(Context, DC,
1660 SourceLocation(), 0,
1661 *ArgType, VarDecl::None,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001662 0));
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001663 }
1664
1665 NewFD->setParams(Context, &Params[0], Params.size());
1666 }
1667 }
1668
1669 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1670 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
1671 else if (isa<CXXDestructorDecl>(NewFD)) {
1672 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1673 Record->setUserDeclaredDestructor(true);
1674 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1675 // user-defined destructor.
1676 Record->setPOD(false);
1677 } else if (CXXConversionDecl *Conversion =
1678 dyn_cast<CXXConversionDecl>(NewFD))
1679 ActOnConversionDeclarator(Conversion);
1680
1681 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1682 if (NewFD->isOverloadedOperator() &&
1683 CheckOverloadedOperatorDeclaration(NewFD))
1684 NewFD->setInvalidDecl();
1685
1686 // Merge the decl with the existing one if appropriate. Since C functions
1687 // are in a flat namespace, make sure we consider decls in outer scopes.
1688 if (PrevDecl &&
1689 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
1690 bool Redeclaration = false;
1691
1692 // If C++, determine whether NewFD is an overload of PrevDecl or
1693 // a declaration that requires merging. If it's an overload,
1694 // there's no more work to do here; we'll just add the new
1695 // function to the scope.
1696 OverloadedFunctionDecl::function_iterator MatchedDecl;
1697 if (!getLangOptions().CPlusPlus ||
1698 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1699 Decl *OldDecl = PrevDecl;
1700
1701 // If PrevDecl was an overloaded function, extract the
1702 // FunctionDecl that matched.
1703 if (isa<OverloadedFunctionDecl>(PrevDecl))
1704 OldDecl = *MatchedDecl;
1705
1706 // NewFD and PrevDecl represent declarations that need to be
1707 // merged.
1708 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1709
1710 if (NewFD == 0) return 0;
1711 if (Redeclaration) {
1712 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1713
1714 // An out-of-line member function declaration must also be a
1715 // definition (C++ [dcl.meaning]p1).
1716 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1717 !InvalidDecl) {
1718 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1719 << D.getCXXScopeSpec().getRange();
1720 NewFD->setInvalidDecl();
1721 }
1722 }
1723 }
1724
1725 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1726 // The user tried to provide an out-of-line definition for a
1727 // member function, but there was no such member function
1728 // declared (C++ [class.mfct]p2). For example:
1729 //
1730 // class X {
1731 // void f() const;
1732 // };
1733 //
1734 // void X::f() { } // ill-formed
1735 //
1736 // Complain about this problem, and attempt to suggest close
1737 // matches (e.g., those that differ only in cv-qualifiers and
1738 // whether the parameter types are references).
1739 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1740 << cast<CXXRecordDecl>(DC)->getDeclName()
1741 << D.getCXXScopeSpec().getRange();
1742 InvalidDecl = true;
1743
Steve Naroff3e8ffd22009-01-29 00:07:50 +00001744 PrevDecl = LookupDeclInContext(Name, Decl::IDNS_Ordinary, DC);
Zhongxing Xu416fcaf2009-01-16 01:13:29 +00001745 if (!PrevDecl) {
1746 // Nothing to suggest.
1747 } else if (OverloadedFunctionDecl *Ovl
1748 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1749 for (OverloadedFunctionDecl::function_iterator
1750 Func = Ovl->function_begin(),
1751 FuncEnd = Ovl->function_end();
1752 Func != FuncEnd; ++Func) {
1753 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1754 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1755
1756 }
1757 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1758 // Suggest this no matter how mismatched it is; it's the only
1759 // thing we have.
1760 unsigned diag;
1761 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1762 diag = diag::note_member_def_close_match;
1763 else if (Method->getBody())
1764 diag = diag::note_previous_definition;
1765 else
1766 diag = diag::note_previous_declaration;
1767 Diag(Method->getLocation(), diag);
1768 }
1769
1770 PrevDecl = 0;
1771 }
1772 }
1773 // Handle attributes. We need to have merged decls when handling attributes
1774 // (for example to check for conflicts, etc).
1775 ProcessDeclAttributes(NewFD, D);
1776
1777 if (getLangOptions().CPlusPlus) {
1778 // In C++, check default arguments now that we have merged decls.
1779 CheckCXXDefaultArguments(NewFD);
1780
1781 // An out-of-line member function declaration must also be a
1782 // definition (C++ [dcl.meaning]p1).
1783 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
1784 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1785 << D.getCXXScopeSpec().getRange();
1786 InvalidDecl = true;
1787 }
1788 }
1789 return NewFD;
1790}
1791
Steve Naroff6594a702008-10-27 11:34:16 +00001792void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001793 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1794 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001795}
1796
Eli Friedmanc594b322008-05-20 13:48:25 +00001797bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1798 switch (Init->getStmtClass()) {
1799 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001800 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001801 return true;
1802 case Expr::ParenExprClass: {
1803 const ParenExpr* PE = cast<ParenExpr>(Init);
1804 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1805 }
1806 case Expr::CompoundLiteralExprClass:
1807 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001808 case Expr::DeclRefExprClass:
1809 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001810 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001811 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1812 if (VD->hasGlobalStorage())
1813 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001814 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001815 return true;
1816 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001817 if (isa<FunctionDecl>(D))
1818 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001819 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001820 return true;
1821 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001822 case Expr::MemberExprClass: {
1823 const MemberExpr *M = cast<MemberExpr>(Init);
1824 if (M->isArrow())
1825 return CheckAddressConstantExpression(M->getBase());
1826 return CheckAddressConstantExpressionLValue(M->getBase());
1827 }
1828 case Expr::ArraySubscriptExprClass: {
1829 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1830 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1831 return CheckAddressConstantExpression(ASE->getBase()) ||
1832 CheckArithmeticConstantExpression(ASE->getIdx());
1833 }
1834 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001835 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001836 return false;
1837 case Expr::UnaryOperatorClass: {
1838 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1839
1840 // C99 6.6p9
1841 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001842 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001843
Steve Naroff6594a702008-10-27 11:34:16 +00001844 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001845 return true;
1846 }
1847 }
1848}
1849
1850bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1851 switch (Init->getStmtClass()) {
1852 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001853 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001854 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001855 case Expr::ParenExprClass:
1856 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001857 case Expr::StringLiteralClass:
1858 case Expr::ObjCStringLiteralClass:
1859 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001860 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001861 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001862 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1863 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1864 Builtin::BI__builtin___CFStringMakeConstantString)
1865 return false;
1866
Steve Naroff6594a702008-10-27 11:34:16 +00001867 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001868 return true;
1869
Eli Friedmanc594b322008-05-20 13:48:25 +00001870 case Expr::UnaryOperatorClass: {
1871 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1872
1873 // C99 6.6p9
1874 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1875 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1876
1877 if (Exp->getOpcode() == UnaryOperator::Extension)
1878 return CheckAddressConstantExpression(Exp->getSubExpr());
1879
Steve Naroff6594a702008-10-27 11:34:16 +00001880 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001881 return true;
1882 }
1883 case Expr::BinaryOperatorClass: {
1884 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1885 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1886
1887 Expr *PExp = Exp->getLHS();
1888 Expr *IExp = Exp->getRHS();
1889 if (IExp->getType()->isPointerType())
1890 std::swap(PExp, IExp);
1891
1892 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1893 return CheckAddressConstantExpression(PExp) ||
1894 CheckArithmeticConstantExpression(IExp);
1895 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001896 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001897 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001898 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001899 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1900 // Check for implicit promotion
1901 if (SubExpr->getType()->isFunctionType() ||
1902 SubExpr->getType()->isArrayType())
1903 return CheckAddressConstantExpressionLValue(SubExpr);
1904 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001905
1906 // Check for pointer->pointer cast
1907 if (SubExpr->getType()->isPointerType())
1908 return CheckAddressConstantExpression(SubExpr);
1909
Eli Friedmanc3f07642008-08-25 20:46:57 +00001910 if (SubExpr->getType()->isIntegralType()) {
1911 // Check for the special-case of a pointer->int->pointer cast;
1912 // this isn't standard, but some code requires it. See
1913 // PR2720 for an example.
1914 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1915 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1916 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1917 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1918 if (IntWidth >= PointerWidth) {
1919 return CheckAddressConstantExpression(SubCast->getSubExpr());
1920 }
1921 }
1922 }
1923 }
1924 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001925 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001926 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001927
Steve Naroff6594a702008-10-27 11:34:16 +00001928 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001929 return true;
1930 }
1931 case Expr::ConditionalOperatorClass: {
1932 // FIXME: Should we pedwarn here?
1933 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1934 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001935 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001936 return true;
1937 }
1938 if (CheckArithmeticConstantExpression(Exp->getCond()))
1939 return true;
1940 if (Exp->getLHS() &&
1941 CheckAddressConstantExpression(Exp->getLHS()))
1942 return true;
1943 return CheckAddressConstantExpression(Exp->getRHS());
1944 }
1945 case Expr::AddrLabelExprClass:
1946 return false;
1947 }
1948}
1949
Eli Friedman4caf0552008-06-09 05:05:07 +00001950static const Expr* FindExpressionBaseAddress(const Expr* E);
1951
1952static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1953 switch (E->getStmtClass()) {
1954 default:
1955 return E;
1956 case Expr::ParenExprClass: {
1957 const ParenExpr* PE = cast<ParenExpr>(E);
1958 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1959 }
1960 case Expr::MemberExprClass: {
1961 const MemberExpr *M = cast<MemberExpr>(E);
1962 if (M->isArrow())
1963 return FindExpressionBaseAddress(M->getBase());
1964 return FindExpressionBaseAddressLValue(M->getBase());
1965 }
1966 case Expr::ArraySubscriptExprClass: {
1967 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1968 return FindExpressionBaseAddress(ASE->getBase());
1969 }
1970 case Expr::UnaryOperatorClass: {
1971 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1972
1973 if (Exp->getOpcode() == UnaryOperator::Deref)
1974 return FindExpressionBaseAddress(Exp->getSubExpr());
1975
1976 return E;
1977 }
1978 }
1979}
1980
1981static const Expr* FindExpressionBaseAddress(const Expr* E) {
1982 switch (E->getStmtClass()) {
1983 default:
1984 return E;
1985 case Expr::ParenExprClass: {
1986 const ParenExpr* PE = cast<ParenExpr>(E);
1987 return FindExpressionBaseAddress(PE->getSubExpr());
1988 }
1989 case Expr::UnaryOperatorClass: {
1990 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1991
1992 // C99 6.6p9
1993 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1994 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1995
1996 if (Exp->getOpcode() == UnaryOperator::Extension)
1997 return FindExpressionBaseAddress(Exp->getSubExpr());
1998
1999 return E;
2000 }
2001 case Expr::BinaryOperatorClass: {
2002 const BinaryOperator *Exp = cast<BinaryOperator>(E);
2003
2004 Expr *PExp = Exp->getLHS();
2005 Expr *IExp = Exp->getRHS();
2006 if (IExp->getType()->isPointerType())
2007 std::swap(PExp, IExp);
2008
2009 return FindExpressionBaseAddress(PExp);
2010 }
2011 case Expr::ImplicitCastExprClass: {
2012 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
2013
2014 // Check for implicit promotion
2015 if (SubExpr->getType()->isFunctionType() ||
2016 SubExpr->getType()->isArrayType())
2017 return FindExpressionBaseAddressLValue(SubExpr);
2018
2019 // Check for pointer->pointer cast
2020 if (SubExpr->getType()->isPointerType())
2021 return FindExpressionBaseAddress(SubExpr);
2022
2023 // We assume that we have an arithmetic expression here;
2024 // if we don't, we'll figure it out later
2025 return 0;
2026 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002027 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00002028 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
2029
2030 // Check for pointer->pointer cast
2031 if (SubExpr->getType()->isPointerType())
2032 return FindExpressionBaseAddress(SubExpr);
2033
2034 // We assume that we have an arithmetic expression here;
2035 // if we don't, we'll figure it out later
2036 return 0;
2037 }
2038 }
2039}
2040
Anders Carlsson51fe9962008-11-22 21:04:56 +00002041bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00002042 switch (Init->getStmtClass()) {
2043 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002044 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002045 return true;
2046 case Expr::ParenExprClass: {
2047 const ParenExpr* PE = cast<ParenExpr>(Init);
2048 return CheckArithmeticConstantExpression(PE->getSubExpr());
2049 }
2050 case Expr::FloatingLiteralClass:
2051 case Expr::IntegerLiteralClass:
2052 case Expr::CharacterLiteralClass:
2053 case Expr::ImaginaryLiteralClass:
2054 case Expr::TypesCompatibleExprClass:
2055 case Expr::CXXBoolLiteralExprClass:
2056 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00002057 case Expr::CallExprClass:
2058 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002059 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002060
2061 // Allow any constant foldable calls to builtins.
2062 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00002063 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002064
Steve Naroff6594a702008-10-27 11:34:16 +00002065 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002066 return true;
2067 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00002068 case Expr::DeclRefExprClass:
2069 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00002070 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
2071 if (isa<EnumConstantDecl>(D))
2072 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002073 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002074 return true;
2075 }
2076 case Expr::CompoundLiteralExprClass:
2077 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2078 // but vectors are allowed to be magic.
2079 if (Init->getType()->isVectorType())
2080 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002081 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002082 return true;
2083 case Expr::UnaryOperatorClass: {
2084 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2085
2086 switch (Exp->getOpcode()) {
2087 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2088 // See C99 6.6p3.
2089 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002090 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002091 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002092 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002093 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2094 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002095 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002096 return true;
2097 case UnaryOperator::Extension:
2098 case UnaryOperator::LNot:
2099 case UnaryOperator::Plus:
2100 case UnaryOperator::Minus:
2101 case UnaryOperator::Not:
2102 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2103 }
2104 }
Sebastian Redl05189992008-11-11 17:56:53 +00002105 case Expr::SizeOfAlignOfExprClass: {
2106 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002107 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002108 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002109 return false;
2110 // alignof always evaluates to a constant.
2111 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002112 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002113 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002114 return true;
2115 }
2116 return false;
2117 }
2118 case Expr::BinaryOperatorClass: {
2119 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2120
2121 if (Exp->getLHS()->getType()->isArithmeticType() &&
2122 Exp->getRHS()->getType()->isArithmeticType()) {
2123 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2124 CheckArithmeticConstantExpression(Exp->getRHS());
2125 }
2126
Eli Friedman4caf0552008-06-09 05:05:07 +00002127 if (Exp->getLHS()->getType()->isPointerType() &&
2128 Exp->getRHS()->getType()->isPointerType()) {
2129 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2130 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2131
2132 // Only allow a null (constant integer) base; we could
2133 // allow some additional cases if necessary, but this
2134 // is sufficient to cover offsetof-like constructs.
2135 if (!LHSBase && !RHSBase) {
2136 return CheckAddressConstantExpression(Exp->getLHS()) ||
2137 CheckAddressConstantExpression(Exp->getRHS());
2138 }
2139 }
2140
Steve Naroff6594a702008-10-27 11:34:16 +00002141 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002142 return true;
2143 }
2144 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002145 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002146 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002147 if (SubExpr->getType()->isArithmeticType())
2148 return CheckArithmeticConstantExpression(SubExpr);
2149
Eli Friedmanb529d832008-09-02 09:37:00 +00002150 if (SubExpr->getType()->isPointerType()) {
2151 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2152 // If the pointer has a null base, this is an offsetof-like construct
2153 if (!Base)
2154 return CheckAddressConstantExpression(SubExpr);
2155 }
2156
Steve Naroff6594a702008-10-27 11:34:16 +00002157 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002158 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002159 }
2160 case Expr::ConditionalOperatorClass: {
2161 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002162
2163 // If GNU extensions are disabled, we require all operands to be arithmetic
2164 // constant expressions.
2165 if (getLangOptions().NoExtensions) {
2166 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2167 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2168 CheckArithmeticConstantExpression(Exp->getRHS());
2169 }
2170
2171 // Otherwise, we have to emulate some of the behavior of fold here.
2172 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2173 // because it can constant fold things away. To retain compatibility with
2174 // GCC code, we see if we can fold the condition to a constant (which we
2175 // should always be able to do in theory). If so, we only require the
2176 // specified arm of the conditional to be a constant. This is a horrible
2177 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002178 Expr::EvalResult EvalResult;
2179 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2180 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002181 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002182 // won't be able to either. Use it to emit the diagnostic though.
2183 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002184 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002185 return Res;
2186 }
2187
2188 // Verify that the side following the condition is also a constant.
2189 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002190 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002191 std::swap(TrueSide, FalseSide);
2192
2193 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002194 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002195
2196 // Okay, the evaluated side evaluates to a constant, so we accept this.
2197 // Check to see if the other side is obviously not a constant. If so,
2198 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002199 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002200 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002201 diag::ext_typecheck_expression_not_constant_but_accepted)
2202 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002203 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002204 }
2205 }
2206}
2207
2208bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Douglas Gregor05c13a32009-01-22 00:58:24 +00002209 if (DesignatedInitExpr *DIE = dyn_cast<DesignatedInitExpr>(Init))
2210 Init = DIE->getInit();
2211
Nuno Lopes9a979c32008-07-07 16:46:50 +00002212 Init = Init->IgnoreParens();
2213
Nate Begeman59b5da62009-01-18 03:20:47 +00002214 if (Init->isEvaluatable(Context))
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002215 return false;
2216
Eli Friedmanc594b322008-05-20 13:48:25 +00002217 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2218 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2219 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2220
Nuno Lopes9a979c32008-07-07 16:46:50 +00002221 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2222 return CheckForConstantInitializer(e->getInitializer(), DclT);
2223
Eli Friedmanc594b322008-05-20 13:48:25 +00002224 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2225 unsigned numInits = Exp->getNumInits();
2226 for (unsigned i = 0; i < numInits; i++) {
2227 // FIXME: Need to get the type of the declaration for C++,
2228 // because it could be a reference?
Douglas Gregor4c678342009-01-28 21:54:33 +00002229
2230 // Implicitly-generated value initializations are okay.
2231 if (isa<CXXZeroInitValueExpr>(Exp->getInit(i)) &&
2232 cast<CXXZeroInitValueExpr>(Exp->getInit(i))->isImplicit())
2233 continue;
2234
Eli Friedmanc594b322008-05-20 13:48:25 +00002235 if (CheckForConstantInitializer(Exp->getInit(i),
2236 Exp->getInit(i)->getType()))
2237 return true;
2238 }
2239 return false;
2240 }
2241
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002242 // FIXME: We can probably remove some of this code below, now that
2243 // Expr::Evaluate is doing the heavy lifting for scalars.
2244
Eli Friedmanc594b322008-05-20 13:48:25 +00002245 if (Init->isNullPointerConstant(Context))
2246 return false;
2247 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002248 QualType InitTy = Context.getCanonicalType(Init->getType())
2249 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002250 if (InitTy == Context.BoolTy) {
2251 // Special handling for pointers implicitly cast to bool;
2252 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2253 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2254 Expr* SubE = ICE->getSubExpr();
2255 if (SubE->getType()->isPointerType() ||
2256 SubE->getType()->isArrayType() ||
2257 SubE->getType()->isFunctionType()) {
2258 return CheckAddressConstantExpression(Init);
2259 }
2260 }
2261 } else if (InitTy->isIntegralType()) {
2262 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002263 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002264 SubE = CE->getSubExpr();
2265 // Special check for pointer cast to int; we allow as an extension
2266 // an address constant cast to an integer if the integer
2267 // is of an appropriate width (this sort of code is apparently used
2268 // in some places).
2269 // FIXME: Add pedwarn?
2270 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2271 if (SubE && (SubE->getType()->isPointerType() ||
2272 SubE->getType()->isArrayType() ||
2273 SubE->getType()->isFunctionType())) {
2274 unsigned IntWidth = Context.getTypeSize(Init->getType());
2275 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2276 if (IntWidth >= PointerWidth)
2277 return CheckAddressConstantExpression(Init);
2278 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002279 }
2280
2281 return CheckArithmeticConstantExpression(Init);
2282 }
2283
2284 if (Init->getType()->isPointerType())
2285 return CheckAddressConstantExpression(Init);
2286
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002287 // An array type at the top level that isn't an init-list must
2288 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002289 if (Init->getType()->isArrayType())
2290 return false;
2291
Nuno Lopes73419bf2008-09-01 18:42:41 +00002292 if (Init->getType()->isFunctionType())
2293 return false;
2294
Steve Naroff8af6a452008-10-02 17:12:56 +00002295 // Allow block exprs at top level.
2296 if (Init->getType()->isBlockPointerType())
2297 return false;
Nuno Lopes6ed2ef82009-01-15 16:44:45 +00002298
2299 // GCC cast to union extension
2300 // note: the validity of the cast expr is checked by CheckCastTypes()
2301 if (CastExpr *C = dyn_cast<CastExpr>(Init)) {
2302 QualType T = C->getType();
2303 return T->isUnionType() && CheckForConstantInitializer(C->getSubExpr(), T);
2304 }
2305
Steve Naroff6594a702008-10-27 11:34:16 +00002306 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002307 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002308}
2309
Sebastian Redl798d1192008-12-13 16:23:55 +00002310void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002311 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2312}
2313
2314/// AddInitializerToDecl - Adds the initializer Init to the
2315/// declaration dcl. If DirectInit is true, this is C++ direct
2316/// initialization rather than copy initialization.
2317void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002318 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002319 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002320 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002321
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002322 // If there is no declaration, there was an error parsing it. Just ignore
2323 // the initializer.
2324 if (RealDecl == 0) {
2325 delete Init;
2326 return;
2327 }
Steve Naroffbb204692007-09-12 14:07:44 +00002328
Steve Naroff410e3e22007-09-12 20:13:48 +00002329 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2330 if (!VDecl) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002331 Diag(RealDecl->getLocation(), diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002332 RealDecl->setInvalidDecl();
2333 return;
2334 }
Steve Naroffbb204692007-09-12 14:07:44 +00002335 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002336 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002337 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002338 if (VDecl->isBlockVarDecl()) {
2339 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002340 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002341 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002342 VDecl->setInvalidDecl();
2343 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002344 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002345 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002346 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002347
2348 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2349 if (!getLangOptions().CPlusPlus) {
2350 if (SC == VarDecl::Static) // C99 6.7.8p4.
2351 CheckForConstantInitializer(Init, DclT);
2352 }
Steve Naroffbb204692007-09-12 14:07:44 +00002353 }
Steve Naroff248a7532008-04-15 22:42:06 +00002354 } else if (VDecl->isFileVarDecl()) {
2355 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002356 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002357 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002358 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002359 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002360 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002361
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002362 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2363 if (!getLangOptions().CPlusPlus) {
2364 // C99 6.7.8p4. All file scoped initializers need to be constant.
2365 CheckForConstantInitializer(Init, DclT);
2366 }
Steve Naroffbb204692007-09-12 14:07:44 +00002367 }
2368 // If the type changed, it means we had an incomplete type that was
2369 // completed by the initializer. For example:
2370 // int ary[] = { 1, 3, 5 };
2371 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002372 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002373 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002374 Init->setType(DclT);
2375 }
Steve Naroffbb204692007-09-12 14:07:44 +00002376
2377 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002378 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002379 return;
2380}
2381
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002382void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2383 Decl *RealDecl = static_cast<Decl *>(dcl);
2384
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002385 // If there is no declaration, there was an error parsing it. Just ignore it.
2386 if (RealDecl == 0)
2387 return;
2388
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002389 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2390 QualType Type = Var->getType();
2391 // C++ [dcl.init.ref]p3:
2392 // The initializer can be omitted for a reference only in a
2393 // parameter declaration (8.3.5), in the declaration of a
2394 // function return type, in the declaration of a class member
2395 // within its class declaration (9.2), and where the extern
2396 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002397 if (Type->isReferenceType() &&
2398 Var->getStorageClass() != VarDecl::Extern &&
2399 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002400 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002401 << Var->getDeclName()
2402 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002403 Var->setInvalidDecl();
2404 return;
2405 }
2406
2407 // C++ [dcl.init]p9:
2408 //
2409 // If no initializer is specified for an object, and the object
2410 // is of (possibly cv-qualified) non-POD class type (or array
2411 // thereof), the object shall be default-initialized; if the
2412 // object is of const-qualified type, the underlying class type
2413 // shall have a user-declared default constructor.
2414 if (getLangOptions().CPlusPlus) {
2415 QualType InitType = Type;
2416 if (const ArrayType *Array = Context.getAsArrayType(Type))
2417 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002418 if (Var->getStorageClass() != VarDecl::Extern &&
2419 Var->getStorageClass() != VarDecl::PrivateExtern &&
2420 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002421 const CXXConstructorDecl *Constructor
2422 = PerformInitializationByConstructor(InitType, 0, 0,
2423 Var->getLocation(),
2424 SourceRange(Var->getLocation(),
2425 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002426 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002427 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002428 if (!Constructor)
2429 Var->setInvalidDecl();
2430 }
2431 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002432
Douglas Gregor818ce482008-10-29 13:50:18 +00002433#if 0
2434 // FIXME: Temporarily disabled because we are not properly parsing
2435 // linkage specifications on declarations, e.g.,
2436 //
2437 // extern "C" const CGPoint CGPointerZero;
2438 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002439 // C++ [dcl.init]p9:
2440 //
2441 // If no initializer is specified for an object, and the
2442 // object is of (possibly cv-qualified) non-POD class type (or
2443 // array thereof), the object shall be default-initialized; if
2444 // the object is of const-qualified type, the underlying class
2445 // type shall have a user-declared default
2446 // constructor. Otherwise, if no initializer is specified for
2447 // an object, the object and its subobjects, if any, have an
2448 // indeterminate initial value; if the object or any of its
2449 // subobjects are of const-qualified type, the program is
2450 // ill-formed.
2451 //
2452 // This isn't technically an error in C, so we don't diagnose it.
2453 //
2454 // FIXME: Actually perform the POD/user-defined default
2455 // constructor check.
2456 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002457 Context.getCanonicalType(Type).isConstQualified() &&
2458 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002459 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2460 << Var->getName()
2461 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002462#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002463 }
2464}
2465
Reid Spencer5f016e22007-07-11 17:01:13 +00002466/// The declarators are chained together backwards, reverse the list.
2467Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2468 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002469 Decl *GroupDecl = static_cast<Decl*>(group);
2470 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002471 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002472
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002473 Decl *Group = dyn_cast<Decl>(GroupDecl);
2474 Decl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002475 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002477 else { // reverse the list.
2478 while (Group) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002479 Decl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002480 Group->setNextDeclarator(NewGroup);
2481 NewGroup = Group;
2482 Group = Next;
2483 }
2484 }
2485 // Perform semantic analysis that depends on having fully processed both
2486 // the declarator and initializer.
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002487 for (Decl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002488 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2489 if (!IDecl)
2490 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002491 QualType T = IDecl->getType();
2492
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002493 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002494 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002495
2496 // FIXME: This won't give the correct result for
2497 // int a[10][n];
2498 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002499 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002500 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2501 SizeRange;
2502
Eli Friedmanc5773c42008-02-15 18:16:39 +00002503 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002504 } else {
2505 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2506 // static storage duration, it shall not have a variable length array.
2507 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002508 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2509 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002510 IDecl->setInvalidDecl();
2511 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002512 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2513 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002514 IDecl->setInvalidDecl();
2515 }
2516 }
2517 } else if (T->isVariablyModifiedType()) {
2518 if (IDecl->isFileVarDecl()) {
2519 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2520 IDecl->setInvalidDecl();
2521 } else {
2522 if (IDecl->getStorageClass() == VarDecl::Extern) {
2523 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2524 IDecl->setInvalidDecl();
2525 }
Steve Naroffbb204692007-09-12 14:07:44 +00002526 }
2527 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002528
Steve Naroffbb204692007-09-12 14:07:44 +00002529 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2530 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002531 if (IDecl->isBlockVarDecl() &&
2532 IDecl->getStorageClass() != VarDecl::Extern) {
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002533 if (!IDecl->isInvalidDecl() &&
2534 DiagnoseIncompleteType(IDecl->getLocation(), T,
2535 diag::err_typecheck_decl_incomplete_type))
Steve Naroffbb204692007-09-12 14:07:44 +00002536 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002537 }
2538 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2539 // object that has file scope without an initializer, and without a
2540 // storage-class specifier or with the storage-class specifier "static",
2541 // constitutes a tentative definition. Note: A tentative definition with
2542 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002543 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002544 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002545 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2546 // array to be completed. Don't issue a diagnostic.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00002547 } else if (!IDecl->isInvalidDecl() &&
2548 DiagnoseIncompleteType(IDecl->getLocation(), T,
2549 diag::err_typecheck_decl_incomplete_type))
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002550 // C99 6.9.2p3: If the declaration of an identifier for an object is
2551 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2552 // declared type shall not be an incomplete type.
Steve Naroffbb204692007-09-12 14:07:44 +00002553 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00002554 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002555 if (IDecl->isFileVarDecl())
2556 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002557 }
2558 return NewGroup;
2559}
Steve Naroffe1223f72007-08-28 03:03:08 +00002560
Chris Lattner04421082008-04-08 04:40:51 +00002561/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2562/// to introduce parameters into function prototype scope.
2563Sema::DeclTy *
2564Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002565 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002566
Chris Lattner04421082008-04-08 04:40:51 +00002567 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002568 VarDecl::StorageClass StorageClass = VarDecl::None;
2569 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2570 StorageClass = VarDecl::Register;
2571 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002572 Diag(DS.getStorageClassSpecLoc(),
2573 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002574 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002575 }
2576 if (DS.isThreadSpecified()) {
2577 Diag(DS.getThreadSpecLoc(),
2578 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002579 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002580 }
2581
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002582 // Check that there are no default arguments inside the type of this
2583 // parameter (C++ only).
2584 if (getLangOptions().CPlusPlus)
2585 CheckExtraCXXDefaultArguments(D);
2586
Chris Lattner04421082008-04-08 04:40:51 +00002587 // In this context, we *do not* check D.getInvalidType(). If the declarator
2588 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2589 // though it will not reflect the user specified type.
2590 QualType parmDeclType = GetTypeForDeclarator(D, S);
2591
2592 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2593
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2595 // Can this happen for params? We already checked that they don't conflict
2596 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002597 IdentifierInfo *II = D.getIdentifier();
Chris Lattnercf79b012009-01-21 02:38:50 +00002598 if (II) {
Steve Naroff3e8ffd22009-01-29 00:07:50 +00002599 if (Decl *PrevDecl = LookupDeclInScope(II, Decl::IDNS_Ordinary, S)) {
Chris Lattnercf79b012009-01-21 02:38:50 +00002600 if (PrevDecl->isTemplateParameter()) {
2601 // Maybe we will complain about the shadowed template parameter.
2602 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2603 // Just pretend that we didn't see the previous declaration.
2604 PrevDecl = 0;
2605 } else if (S->isDeclScope(PrevDecl)) {
2606 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002607
Chris Lattnercf79b012009-01-21 02:38:50 +00002608 // Recover by removing the name
2609 II = 0;
2610 D.SetIdentifier(0, D.getIdentifierLoc());
2611 }
Chris Lattner04421082008-04-08 04:40:51 +00002612 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002613 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002614
2615 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2616 // Doing the promotion here has a win and a loss. The win is the type for
2617 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2618 // code generator). The loss is the orginal type isn't preserved. For example:
2619 //
2620 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2621 // int blockvardecl[5];
2622 // sizeof(parmvardecl); // size == 4
2623 // sizeof(blockvardecl); // size == 20
2624 // }
2625 //
2626 // For expressions, all implicit conversions are captured using the
2627 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2628 //
2629 // FIXME: If a source translation tool needs to see the original type, then
2630 // we need to consider storing both types (in ParmVarDecl)...
2631 //
Chris Lattnere6327742008-04-02 05:18:44 +00002632 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002633 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002634 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002635 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002636 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002637
Chris Lattner04421082008-04-08 04:40:51 +00002638 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2639 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002640 parmDeclType, StorageClass,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002641 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002642
Chris Lattner04421082008-04-08 04:40:51 +00002643 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002644 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002645
Douglas Gregor584049d2008-12-15 23:53:10 +00002646 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2647 if (D.getCXXScopeSpec().isSet()) {
2648 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2649 << D.getCXXScopeSpec().getRange();
2650 New->setInvalidDecl();
2651 }
2652
Douglas Gregor44b43212008-12-11 16:49:14 +00002653 // Add the parameter declaration into this scope.
2654 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002655 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002656 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002657
Chris Lattner3ff30c82008-06-29 00:02:00 +00002658 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002659 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002660
Reid Spencer5f016e22007-07-11 17:01:13 +00002661}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002662
Douglas Gregorbe109b32009-01-23 16:23:13 +00002663void Sema::ActOnFinishKNRParamDeclarations(Scope *S, Declarator &D) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2665 "Not a function declarator!");
2666 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002667
Reid Spencer5f016e22007-07-11 17:01:13 +00002668 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2669 // for a K&R function.
2670 if (!FTI.hasPrototype) {
2671 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002672 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002673 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2674 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002675 // Implicitly declare the argument as type 'int' for lack of a better
2676 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002677 DeclSpec DS;
2678 const char* PrevSpec; // unused
2679 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2680 PrevSpec);
2681 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2682 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
Douglas Gregorbe109b32009-01-23 16:23:13 +00002683 FTI.ArgInfo[i].Param = ActOnParamDeclarator(S, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 }
2685 }
Douglas Gregorbe109b32009-01-23 16:23:13 +00002686 }
2687}
2688
2689Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
2690 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
2691 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2692 "Not a function declarator!");
2693 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
2694
2695 if (FTI.hasPrototype) {
Chris Lattner04421082008-04-08 04:40:51 +00002696 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002697 }
2698
Douglas Gregor584049d2008-12-15 23:53:10 +00002699 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002700
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002701 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002702 ActOnDeclarator(ParentScope, D, 0,
2703 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002704}
2705
2706Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2707 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002708 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002709
2710 // See if this is a redefinition.
2711 const FunctionDecl *Definition;
2712 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002713 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002714 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002715 }
2716
Douglas Gregor44b43212008-12-11 16:49:14 +00002717 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002718
Chris Lattner04421082008-04-08 04:40:51 +00002719 // Check the validity of our function parameters
2720 CheckParmsForFunctionDef(FD);
2721
2722 // Introduce our parameters into the function scope
2723 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2724 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002725 Param->setOwningFunction(FD);
2726
Chris Lattner04421082008-04-08 04:40:51 +00002727 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002728 if (Param->getIdentifier())
2729 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002730 }
Chris Lattner04421082008-04-08 04:40:51 +00002731
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002732 // Checking attributes of current function definition
2733 // dllimport attribute.
2734 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2735 // dllimport attribute cannot be applied to definition.
2736 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2737 Diag(FD->getLocation(),
2738 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2739 << "dllimport";
2740 FD->setInvalidDecl();
2741 return FD;
2742 } else {
2743 // If a symbol previously declared dllimport is later defined, the
2744 // attribute is ignored in subsequent references, and a warning is
2745 // emitted.
2746 Diag(FD->getLocation(),
2747 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2748 << FD->getNameAsCString() << "dllimport";
2749 }
2750 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002751 return FD;
2752}
2753
Sebastian Redl798d1192008-12-13 16:23:55 +00002754Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002755 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002756 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002757 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002758 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002759 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002760 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002761 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002762 } else
2763 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002764 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002765 // Verify and clean out per-function state.
2766
2767 // Check goto/label use.
2768 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2769 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2770 // Verify that we have no forward references left. If so, there was a goto
2771 // or address of a label taken, but no definition of it. Label fwd
2772 // definitions are indicated with a null substmt.
2773 if (I->second->getSubStmt() == 0) {
2774 LabelStmt *L = I->second;
2775 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002776 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002777
2778 // At this point, we have gotos that use the bogus label. Stitch it into
2779 // the function body so that they aren't leaked and that the AST is well
2780 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002781 if (Body) {
2782 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002783 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002784 } else {
2785 // The whole function wasn't parsed correctly, just delete this.
2786 delete L;
2787 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 }
2789 }
2790 LabelMap.clear();
2791
Steve Naroffd6d054d2007-11-11 23:20:51 +00002792 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002793}
2794
Reid Spencer5f016e22007-07-11 17:01:13 +00002795/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2796/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002797NamedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2798 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002799 // Extension in C99. Legal in C90, but warn about it.
2800 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002801 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002802 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002803 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002804
2805 // FIXME: handle stuff like:
2806 // void foo() { extern float X(); }
2807 // void bar() { X(); } <-- implicit decl for X in another scope.
2808
2809 // Set a Declarator for the implicit definition: int foo();
2810 const char *Dummy;
2811 DeclSpec DS;
2812 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2813 Error = Error; // Silence warning.
2814 assert(!Error && "Error setting up implicit decl!");
2815 Declarator D(DS, Declarator::BlockContext);
Chris Lattner5af2f352009-01-20 19:11:22 +00002816 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc, D));
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 D.SetIdentifier(&II, Loc);
2818
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002819 // Insert this function into translation-unit scope.
2820
2821 DeclContext *PrevDC = CurContext;
2822 CurContext = Context.getTranslationUnitDecl();
2823
Steve Naroffe2ef8152008-04-04 14:32:09 +00002824 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002825 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002826 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002827
2828 CurContext = PrevDC;
2829
Steve Naroffe2ef8152008-04-04 14:32:09 +00002830 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002831}
2832
2833
Chris Lattner41af0932007-11-14 06:34:38 +00002834TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002835 Decl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002837 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002838
2839 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002840 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2841 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002842 D.getIdentifier(),
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002843 T);
2844 NewTD->setNextDeclarator(LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002845 if (D.getInvalidType())
2846 NewTD->setInvalidDecl();
2847 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002848}
2849
Steve Naroff08d92e42007-09-15 18:49:24 +00002850/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002851/// former case, Name will be non-null. In the later case, Name will be null.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002852/// TagSpec indicates what kind of tag this is. TK indicates whether this is a
Reid Spencer5f016e22007-07-11 17:01:13 +00002853/// reference/declaration/definition of a tag.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002854Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagSpec, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002855 SourceLocation KWLoc, const CXXScopeSpec &SS,
2856 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002857 AttributeList *Attr,
2858 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002859 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002860 assert((Name != 0 || TK == TK_Definition) &&
2861 "Nameless record must be a definition!");
2862
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002863 TagDecl::TagKind Kind;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002864 switch (TagSpec) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002865 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002866 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2867 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2868 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2869 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 }
2871
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002872 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002873 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002874 DeclContext *LexicalContext = CurContext;
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002875 Decl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002876
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002877 bool Invalid = false;
2878
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002879 if (Name && SS.isNotEmpty()) {
2880 // We have a nested-name tag ('struct foo::bar').
2881
2882 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002883 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002884 Name = 0;
2885 goto CreateNewDecl;
2886 }
2887
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002888 DC = static_cast<DeclContext*>(SS.getScopeRep());
2889 // Look-up name inside 'foo::'.
Steve Naroff3e8ffd22009-01-29 00:07:50 +00002890 PrevDecl = dyn_cast_or_null<TagDecl>(
2891 LookupDeclInContext(Name, Decl::IDNS_Tag, DC).getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002892
2893 // A tag 'foo::bar' must already exist.
2894 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002895 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002896 Name = 0;
2897 goto CreateNewDecl;
2898 }
Chris Lattnercf79b012009-01-21 02:38:50 +00002899 } else if (Name) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002900 // If this is a named struct, check to see if there was a previous forward
2901 // declaration or definition.
Steve Naroff3e8ffd22009-01-29 00:07:50 +00002902 PrevDecl = dyn_cast_or_null<NamedDecl>(LookupDeclInScope(Name,
2903 Decl::IDNS_Tag,S)
Chris Lattnercf79b012009-01-21 02:38:50 +00002904 .getAsDecl());
Douglas Gregor72de6672009-01-08 20:45:30 +00002905
2906 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2907 // FIXME: This makes sure that we ignore the contexts associated
2908 // with C structs, unions, and enums when looking for a matching
2909 // tag declaration or definition. See the similar lookup tweak
2910 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002911 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2912 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002913 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002914 }
2915
Douglas Gregorf57172b2008-12-08 18:40:42 +00002916 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002917 // Maybe we will complain about the shadowed template parameter.
2918 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2919 // Just pretend that we didn't see the previous declaration.
2920 PrevDecl = 0;
2921 }
2922
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002923 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002924 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002925 // If this is a use of a previous tag, or if the tag is already declared
2926 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002927 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002928 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002929 // Make sure that this wasn't declared as an enum and now used as a
2930 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002931 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002932 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002933 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002934 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002935 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002936 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002937 Invalid = true;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002938 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002939 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002940
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002941 // FIXME: In the future, return a variant or some other clue
2942 // for the consumer of this Decl to know it doesn't own it.
2943 // For our current ASTs this shouldn't be a problem, but will
2944 // need to be changed with DeclGroups.
2945 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002946 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002947
2948 // Diagnose attempts to redefine a tag.
2949 if (TK == TK_Definition) {
2950 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2951 Diag(NameLoc, diag::err_redefinition) << Name;
2952 Diag(Def->getLocation(), diag::note_previous_definition);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002953 // If this is a redefinition, recover by making this
2954 // struct be anonymous, which will make any later
2955 // references get the previous definition.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002956 Name = 0;
2957 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002958 Invalid = true;
2959 } else {
2960 // If the type is currently being defined, complain
2961 // about a nested redefinition.
2962 TagType *Tag = cast<TagType>(Context.getTagDeclType(PrevTagDecl));
2963 if (Tag->isBeingDefined()) {
2964 Diag(NameLoc, diag::err_nested_redefinition) << Name;
2965 Diag(PrevTagDecl->getLocation(),
2966 diag::note_previous_definition);
2967 Name = 0;
2968 PrevDecl = 0;
2969 Invalid = true;
2970 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002971 }
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002972
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002973 // Okay, this is definition of a previously declared or referenced
2974 // tag PrevDecl. We're going to create a new Decl for it.
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002975 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002976 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002977 // If we get here we have (another) forward declaration or we
2978 // have a definition. Just create a new decl.
2979 } else {
2980 // If we get here, this is a definition of a new tag type in a nested
2981 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2982 // new decl/type. We set PrevDecl to NULL so that the entities
2983 // have distinct types.
2984 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002985 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002986 // If we get here, we're going to create a new Decl. If PrevDecl
2987 // is non-NULL, it's a definition of the tag declared by
2988 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002989 } else {
Douglas Gregor66973122009-01-28 17:15:10 +00002990 // PrevDecl is a namespace, template, or anything else
2991 // that lives in the IDNS_Tag identifier namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002992 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002993 // The tag name clashes with a namespace name, issue an error and
2994 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002995 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002996 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002997 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002998 PrevDecl = 0;
Douglas Gregor0b7a1582009-01-17 00:42:38 +00002999 Invalid = true;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003000 } else {
3001 // The existing declaration isn't relevant to us; we're in a
3002 // new scope, so clear out the previous declaration.
3003 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00003004 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003005 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003006 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
3007 (Kind != TagDecl::TK_enum)) {
3008 // C++ [basic.scope.pdecl]p5:
3009 // -- for an elaborated-type-specifier of the form
3010 //
3011 // class-key identifier
3012 //
3013 // if the elaborated-type-specifier is used in the
3014 // decl-specifier-seq or parameter-declaration-clause of a
3015 // function defined in namespace scope, the identifier is
3016 // declared as a class-name in the namespace that contains
3017 // the declaration; otherwise, except as a friend
3018 // declaration, the identifier is declared in the smallest
3019 // non-class, non-function-prototype scope that contains the
3020 // declaration.
3021 //
3022 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
3023 // C structs and unions.
3024
3025 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003026 // FIXME: We would like to maintain the current DeclContext as the
3027 // lexical context,
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003028 while (DC->isRecord())
3029 DC = DC->getParent();
3030 LexicalContext = DC;
3031
3032 // Find the scope where we'll be declaring the tag.
3033 while (S->isClassScope() ||
3034 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003035 ((S->getFlags() & Scope::DeclScope) == 0) ||
3036 (S->getEntity() &&
3037 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003038 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00003040
Chris Lattnercc98eac2008-12-17 07:13:27 +00003041CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00003042
3043 // If there is an identifier, use the location of the identifier as the
3044 // location of the decl, otherwise use the location of the struct/union
3045 // keyword.
3046 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
3047
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003048 // Otherwise, create a new declaration. If there is a previous
3049 // declaration of the same entity, the two will be linked via
3050 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00003051 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00003052
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003053 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003054 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3055 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003056 New = EnumDecl::Create(Context, DC, Loc, Name,
3057 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003058 // If this is an undefined enum, warn.
3059 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003060 } else {
3061 // struct/union/class
3062
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
3064 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003065 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00003066 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003067 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
3068 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003069 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003070 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
3071 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003072 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003073
3074 if (Kind != TagDecl::TK_enum) {
3075 // Handle #pragma pack: if the #pragma pack stack has non-default
3076 // alignment, make up a packed attribute for this decl. These
3077 // attributes are checked when the ASTContext lays out the
3078 // structure.
3079 //
3080 // It is important for implementing the correct semantics that this
3081 // happen here (in act on tag decl). The #pragma pack stack is
3082 // maintained as a result of parser callbacks which can occur at
3083 // many points during the parsing of a struct declaration (because
3084 // the #pragma tokens are effectively skipped over during the
3085 // parsing of the struct).
3086 if (unsigned Alignment = PackContext.getAlignment())
3087 New->addAttr(new PackedAttr(Alignment * 8));
3088 }
3089
Douglas Gregor66973122009-01-28 17:15:10 +00003090 if (getLangOptions().CPlusPlus && SS.isEmpty() && Name && !Invalid) {
3091 // C++ [dcl.typedef]p3:
3092 // [...] Similarly, in a given scope, a class or enumeration
3093 // shall not be declared with the same name as a typedef-name
3094 // that is declared in that scope and refers to a type other
3095 // than the class or enumeration itself.
3096 LookupResult Lookup = LookupName(S, Name,
3097 LookupCriteria(LookupCriteria::Ordinary,
3098 true, true));
3099 TypedefDecl *PrevTypedef = 0;
3100 if (Lookup.getKind() == LookupResult::Found)
3101 PrevTypedef = dyn_cast<TypedefDecl>(Lookup.getAsDecl());
3102
3103 if (PrevTypedef && isDeclInScope(PrevTypedef, SearchDC, S) &&
3104 Context.getCanonicalType(Context.getTypeDeclType(PrevTypedef)) !=
3105 Context.getCanonicalType(Context.getTypeDeclType(New))) {
3106 Diag(Loc, diag::err_tag_definition_of_typedef)
3107 << Context.getTypeDeclType(New)
3108 << PrevTypedef->getUnderlyingType();
3109 Diag(PrevTypedef->getLocation(), diag::note_previous_definition);
3110 Invalid = true;
3111 }
3112 }
3113
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003114 if (Invalid)
3115 New->setInvalidDecl();
3116
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003117 if (Attr)
3118 ProcessDeclAttributeList(New, Attr);
3119
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003120 // If we're declaring or defining a tag in function prototype scope
3121 // in C, note that this type can only be used within the function.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003122 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
3123 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
3124
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003125 // Set the lexical context. If the tag has a C++ scope specifier, the
3126 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003127 New->setLexicalDeclContext(LexicalContext);
Douglas Gregor0b7a1582009-01-17 00:42:38 +00003128
3129 if (TK == TK_Definition)
3130 New->startDefinition();
Reid Spencer5f016e22007-07-11 17:01:13 +00003131
3132 // If this has an identifier, add it to the scope stack.
3133 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003134 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003135
3136 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00003137 if (LexicalContext != CurContext) {
3138 // FIXME: PushOnScopeChains should not rely on CurContext!
3139 DeclContext *OldContext = CurContext;
3140 CurContext = LexicalContext;
3141 PushOnScopeChains(New, S);
3142 CurContext = OldContext;
3143 } else
3144 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00003145 } else {
Douglas Gregor482b77d2009-01-12 23:27:07 +00003146 LexicalContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00003147 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003148
Reid Spencer5f016e22007-07-11 17:01:13 +00003149 return New;
3150}
3151
Douglas Gregor72de6672009-01-08 20:45:30 +00003152void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3153 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3154
3155 // Enter the tag context.
3156 PushDeclContext(S, Tag);
3157
3158 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3159 FieldCollector->StartClass();
3160
3161 if (Record->getIdentifier()) {
3162 // C++ [class]p2:
3163 // [...] The class-name is also inserted into the scope of the
3164 // class itself; this is known as the injected-class-name. For
3165 // purposes of access checking, the injected-class-name is treated
3166 // as if it were a public member name.
3167 RecordDecl *InjectedClassName
3168 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3169 CurContext, Record->getLocation(),
3170 Record->getIdentifier(), Record);
3171 InjectedClassName->setImplicit();
3172 PushOnScopeChains(InjectedClassName, S);
3173 }
3174 }
3175}
3176
3177void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3178 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3179
3180 if (isa<CXXRecordDecl>(Tag))
3181 FieldCollector->FinishClass();
3182
3183 // Exit this scope of this tag's definition.
3184 PopDeclContext();
3185
3186 // Notify the consumer that we've defined a tag.
3187 Consumer.HandleTagDeclDefinition(Tag);
3188}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003189
Chris Lattner1d353ba2008-11-12 21:17:48 +00003190/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3191/// types into constant array types in certain situations which would otherwise
3192/// be errors (for GCC compatibility).
3193static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3194 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003195 // This method tries to turn a variable array into a constant
3196 // array even when the size isn't an ICE. This is necessary
3197 // for compatibility with code that depends on gcc's buggy
3198 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003199 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3200 if (!VLATy) return QualType();
3201
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003202 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003203 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003204 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003205 return QualType();
3206
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003207 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3208 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003209 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3210 return Context.getConstantArrayType(VLATy->getElementType(),
3211 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003212 return QualType();
3213}
3214
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003215bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003216 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003217 // FIXME: 6.7.2.1p4 - verify the field type.
3218
3219 llvm::APSInt Value;
3220 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3221 return true;
3222
Chris Lattnercd087072008-12-12 04:56:04 +00003223 // Zero-width bitfield is ok for anonymous field.
3224 if (Value == 0 && FieldName)
3225 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3226
3227 if (Value.isNegative())
3228 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003229
3230 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3231 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003232 if (TypeSize && Value.getZExtValue() > TypeSize)
3233 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3234 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003235
3236 return false;
3237}
3238
Steve Naroff08d92e42007-09-15 18:49:24 +00003239/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003240/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003241Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003242 SourceLocation DeclStart,
3243 Declarator &D, ExprTy *BitfieldWidth) {
3244 IdentifierInfo *II = D.getIdentifier();
3245 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003246 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003247 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003248 if (II) Loc = D.getIdentifierLoc();
3249
3250 // FIXME: Unnamed fields can be handled in various different ways, for
3251 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003252
Reid Spencer5f016e22007-07-11 17:01:13 +00003253 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003254 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3255 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003256
Reid Spencer5f016e22007-07-11 17:01:13 +00003257 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3258 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003259 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003260 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003261 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003262 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003263 T = FixedTy;
3264 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003265 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003266 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003267 InvalidDecl = true;
3268 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003269 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003270
3271 if (BitWidth) {
3272 if (VerifyBitField(Loc, II, T, BitWidth))
3273 InvalidDecl = true;
3274 } else {
3275 // Not a bitfield.
3276
3277 // validate II.
3278
3279 }
3280
Reid Spencer5f016e22007-07-11 17:01:13 +00003281 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003282 FieldDecl *NewFD;
3283
Douglas Gregor44b43212008-12-11 16:49:14 +00003284 NewFD = FieldDecl::Create(Context, Record,
3285 Loc, II, T, BitWidth,
3286 D.getDeclSpec().getStorageClassSpec() ==
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003287 DeclSpec::SCS_mutable);
Douglas Gregor44b43212008-12-11 16:49:14 +00003288
Douglas Gregor72de6672009-01-08 20:45:30 +00003289 if (II) {
3290 Decl *PrevDecl
Steve Naroff3e8ffd22009-01-29 00:07:50 +00003291 = LookupDeclInScope(II, Decl::IDNS_Member, S, false);
Douglas Gregor72de6672009-01-08 20:45:30 +00003292 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3293 && !isa<TagDecl>(PrevDecl)) {
3294 Diag(Loc, diag::err_duplicate_member) << II;
3295 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3296 NewFD->setInvalidDecl();
3297 Record->setInvalidDecl();
3298 }
3299 }
3300
Sebastian Redl64b45f72009-01-05 20:52:13 +00003301 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003302 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003303 if (!T->isPODType())
3304 cast<CXXRecordDecl>(Record)->setPOD(false);
3305 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003306
Chris Lattner3ff30c82008-06-29 00:02:00 +00003307 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003308
Steve Naroff5912a352007-08-28 20:14:24 +00003309 if (D.getInvalidType() || InvalidDecl)
3310 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003311
Douglas Gregor72de6672009-01-08 20:45:30 +00003312 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003313 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003314 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003315 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003316
Steve Naroff5912a352007-08-28 20:14:24 +00003317 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003318}
3319
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003320/// TranslateIvarVisibility - Translate visibility from a token ID to an
3321/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003322static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003323TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003324 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003325 default: assert(0 && "Unknown visitibility kind");
3326 case tok::objc_private: return ObjCIvarDecl::Private;
3327 case tok::objc_public: return ObjCIvarDecl::Public;
3328 case tok::objc_protected: return ObjCIvarDecl::Protected;
3329 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003330 }
3331}
3332
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003333/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3334/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003335Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003336 SourceLocation DeclStart,
3337 Declarator &D, ExprTy *BitfieldWidth,
3338 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003339
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003340 IdentifierInfo *II = D.getIdentifier();
3341 Expr *BitWidth = (Expr*)BitfieldWidth;
3342 SourceLocation Loc = DeclStart;
3343 if (II) Loc = D.getIdentifierLoc();
3344
3345 // FIXME: Unnamed fields can be handled in various different ways, for
3346 // example, unnamed unions inject all members into the struct namespace!
3347
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003348 QualType T = GetTypeForDeclarator(D, S);
3349 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3350 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003351
3352 if (BitWidth) {
3353 // TODO: Validate.
3354 //printf("WARNING: BITFIELDS IGNORED!\n");
3355
3356 // 6.7.2.1p3
3357 // 6.7.2.1p4
3358
3359 } else {
3360 // Not a bitfield.
3361
3362 // validate II.
3363
3364 }
3365
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003366 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3367 // than a variably modified type.
3368 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003369 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003370 InvalidDecl = true;
3371 }
3372
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003373 // Get the visibility (access control) for this ivar.
3374 ObjCIvarDecl::AccessControl ac =
3375 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3376 : ObjCIvarDecl::None;
3377
3378 // Construct the decl.
3379 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003380 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003381
Douglas Gregor72de6672009-01-08 20:45:30 +00003382 if (II) {
Steve Naroff3e8ffd22009-01-29 00:07:50 +00003383 Decl *PrevDecl = LookupDeclInScope(II, Decl::IDNS_Member, S, false);
Douglas Gregor72de6672009-01-08 20:45:30 +00003384 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3385 && !isa<TagDecl>(PrevDecl)) {
3386 Diag(Loc, diag::err_duplicate_member) << II;
3387 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3388 NewID->setInvalidDecl();
3389 }
3390 }
3391
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003392 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003393 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003394
3395 if (D.getInvalidType() || InvalidDecl)
3396 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003397
Douglas Gregor72de6672009-01-08 20:45:30 +00003398 if (II) {
3399 // FIXME: When interfaces are DeclContexts, we'll need to add
3400 // these to the interface.
3401 S->AddDecl(NewID);
3402 IdResolver.AddDecl(NewID);
3403 }
3404
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003405 return NewID;
3406}
3407
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003408void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003409 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003410 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003411 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003412 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003413 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3414 assert(EnclosingDecl && "missing record or interface decl");
3415 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3416
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 // Verify that all the fields are okay.
3418 unsigned NumNamedMembers = 0;
3419 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003420
Reid Spencer5f016e22007-07-11 17:01:13 +00003421 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003422 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3423 assert(FD && "missing field decl");
3424
Reid Spencer5f016e22007-07-11 17:01:13 +00003425 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003426 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003427
Douglas Gregor72de6672009-01-08 20:45:30 +00003428 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003429 // Remember all fields written by the user.
3430 RecFields.push_back(FD);
3431 }
Steve Narofff13271f2007-09-14 23:09:53 +00003432
Reid Spencer5f016e22007-07-11 17:01:13 +00003433 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003434 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003435 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003436 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003437 FD->setInvalidDecl();
3438 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003439 continue;
3440 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003441 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3442 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003443 if (!Record) { // Incomplete ivar type is always an error.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003444 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3445 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003446 FD->setInvalidDecl();
3447 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003448 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003449 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003450 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003451 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003452 !FDTy->isArrayType()) { //... may have incomplete array type.
Douglas Gregor4ec339f2009-01-19 19:26:10 +00003453 DiagnoseIncompleteType(FD->getLocation(), FD->getType(),
3454 diag::err_field_incomplete);
Steve Naroff74216642007-09-14 22:20:54 +00003455 FD->setInvalidDecl();
3456 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003457 continue;
3458 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003459 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003460 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003461 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003462 FD->setInvalidDecl();
3463 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003464 continue;
3465 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003466 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003467 if (Record)
3468 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003469 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003470 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3471 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003472 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003473 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3474 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003475 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003476 Record->setHasFlexibleArrayMember(true);
3477 } else {
3478 // If this is a struct/class and this is not the last element, reject
3479 // it. Note that GCC supports variable sized arrays in the middle of
3480 // structures.
3481 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003482 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003483 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003484 FD->setInvalidDecl();
3485 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003486 continue;
3487 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003488 // We support flexible arrays at the end of structs in other structs
3489 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003490 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003491 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003492 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003493 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003494 }
3495 }
3496 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003497 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003498 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003499 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003500 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003501 FD->setInvalidDecl();
3502 EnclosingDecl->setInvalidDecl();
3503 continue;
3504 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003505 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003506 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003507 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003508 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003509
Reid Spencer5f016e22007-07-11 17:01:13 +00003510 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003511 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003512 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003513 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003514 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003515 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003516 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003517 // Must enforce the rule that ivars in the base classes may not be
3518 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003519 if (ID->getSuperClass()) {
3520 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3521 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3522 ObjCIvarDecl* Ivar = (*IVI);
3523 IdentifierInfo *II = Ivar->getIdentifier();
3524 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3525 if (prevIvar) {
3526 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003527 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003528 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003529 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003530 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003531 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003532 else if (ObjCImplementationDecl *IMPDecl =
3533 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003534 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3535 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003536 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003537 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003538 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003539
3540 if (Attr)
3541 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003542}
3543
Steve Naroff08d92e42007-09-15 18:49:24 +00003544Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003545 DeclTy *lastEnumConst,
3546 SourceLocation IdLoc, IdentifierInfo *Id,
3547 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003548 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003549 EnumConstantDecl *LastEnumConst =
3550 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3551 Expr *Val = static_cast<Expr*>(val);
3552
Chris Lattner31e05722007-08-26 06:24:45 +00003553 // The scope passed in may not be a decl scope. Zip up the scope tree until
3554 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003555 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003556
Reid Spencer5f016e22007-07-11 17:01:13 +00003557 // Verify that there isn't already something declared with this name in this
3558 // scope.
Steve Naroff3e8ffd22009-01-29 00:07:50 +00003559 Decl *PrevDecl = LookupDeclInScope(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003560 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003561 // Maybe we will complain about the shadowed template parameter.
3562 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3563 // Just pretend that we didn't see the previous declaration.
3564 PrevDecl = 0;
3565 }
3566
3567 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003568 // When in C++, we may get a TagDecl with the same name; in this case the
3569 // enum constant will 'hide' the tag.
3570 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3571 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003572 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003573 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003574 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003575 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003576 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003577 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003578 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003579 return 0;
3580 }
3581 }
3582
3583 llvm::APSInt EnumVal(32);
3584 QualType EltTy;
3585 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003586 // Make sure to promote the operand type to int.
3587 UsualUnaryConversions(Val);
3588
Reid Spencer5f016e22007-07-11 17:01:13 +00003589 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3590 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003591 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003592 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003593 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003594 } else {
3595 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003596 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003597 }
3598
3599 if (!Val) {
3600 if (LastEnumConst) {
3601 // Assign the last value + 1.
3602 EnumVal = LastEnumConst->getInitVal();
3603 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003604
3605 // Check for overflow on increment.
3606 if (EnumVal < LastEnumConst->getInitVal())
3607 Diag(IdLoc, diag::warn_enum_value_overflow);
3608
Chris Lattnerb7416f92007-08-27 17:37:24 +00003609 EltTy = LastEnumConst->getType();
3610 } else {
3611 // First value, set to zero.
3612 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003613 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003614 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003615 }
3616
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003617 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003618 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003619 Val, EnumVal);
Reid Spencer5f016e22007-07-11 17:01:13 +00003620
3621 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003622 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003623
Reid Spencer5f016e22007-07-11 17:01:13 +00003624 return New;
3625}
3626
Steve Naroff02408c62008-08-07 14:08:16 +00003627// FIXME: For consistency with ActOnFields(), we should have the parser
3628// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003629void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003630 DeclTy **Elements, unsigned NumElements) {
3631 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003632 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003633
Chris Lattnere37f0be2007-08-28 05:10:31 +00003634 // TODO: If the result value doesn't fit in an int, it must be a long or long
3635 // long value. ISO C does not support this, but GCC does as an extension,
3636 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003637 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003638
Chris Lattnerac609682007-08-28 06:15:15 +00003639 // Verify that all the values are okay, compute the size of the values, and
3640 // reverse the list.
3641 unsigned NumNegativeBits = 0;
3642 unsigned NumPositiveBits = 0;
3643
3644 // Keep track of whether all elements have type int.
3645 bool AllElementsInt = true;
3646
Reid Spencer5f016e22007-07-11 17:01:13 +00003647 for (unsigned i = 0; i != NumElements; ++i) {
3648 EnumConstantDecl *ECD =
3649 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3650 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003651
3652 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003653 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003654 assert(InitVal.getBitWidth() >= IntWidth &&
3655 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003656 if (InitVal.getBitWidth() > IntWidth) {
3657 llvm::APSInt V(InitVal);
3658 V.trunc(IntWidth);
3659 V.extend(InitVal.getBitWidth());
3660 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003661 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3662 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003663 }
Chris Lattnerac609682007-08-28 06:15:15 +00003664
3665 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003666 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003667 NumPositiveBits = std::max(NumPositiveBits,
3668 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003669 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003670 NumNegativeBits = std::max(NumNegativeBits,
3671 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003672
Chris Lattnerac609682007-08-28 06:15:15 +00003673 // Keep track of whether every enum element has type int (very commmon).
3674 if (AllElementsInt)
3675 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003676 }
3677
Chris Lattnerac609682007-08-28 06:15:15 +00003678 // Figure out the type that should be used for this enum.
3679 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3680 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003681 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003682
3683 if (NumNegativeBits) {
3684 // If there is a negative value, figure out the smallest integer type (of
3685 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003686 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003687 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003688 BestWidth = IntWidth;
3689 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003690 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003691
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003692 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003693 BestType = Context.LongTy;
3694 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003695 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003696
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003697 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003698 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3699 BestType = Context.LongLongTy;
3700 }
3701 }
3702 } else {
3703 // If there is no negative value, figure out which of uint, ulong, ulonglong
3704 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003705 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003706 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003707 BestWidth = IntWidth;
3708 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003709 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003710 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003711 } else {
3712 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003713 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003714 "How could an initializer get larger than ULL?");
3715 BestType = Context.UnsignedLongLongTy;
3716 }
3717 }
3718
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003719 // Loop over all of the enumerator constants, changing their types to match
3720 // the type of the enum if needed.
3721 for (unsigned i = 0; i != NumElements; ++i) {
3722 EnumConstantDecl *ECD =
3723 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3724 if (!ECD) continue; // Already issued a diagnostic.
3725
3726 // Standard C says the enumerators have int type, but we allow, as an
3727 // extension, the enumerators to be larger than int size. If each
3728 // enumerator value fits in an int, type it as an int, otherwise type it the
3729 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3730 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003731 if (ECD->getType() == Context.IntTy) {
3732 // Make sure the init value is signed.
3733 llvm::APSInt IV = ECD->getInitVal();
3734 IV.setIsSigned(true);
3735 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003736
3737 if (getLangOptions().CPlusPlus)
3738 // C++ [dcl.enum]p4: Following the closing brace of an
3739 // enum-specifier, each enumerator has the type of its
3740 // enumeration.
3741 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003742 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003743 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003744
3745 // Determine whether the value fits into an int.
3746 llvm::APSInt InitVal = ECD->getInitVal();
3747 bool FitsInInt;
3748 if (InitVal.isUnsigned() || !InitVal.isNegative())
3749 FitsInInt = InitVal.getActiveBits() < IntWidth;
3750 else
3751 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3752
3753 // If it fits into an integer type, force it. Otherwise force it to match
3754 // the enum decl type.
3755 QualType NewTy;
3756 unsigned NewWidth;
3757 bool NewSign;
3758 if (FitsInInt) {
3759 NewTy = Context.IntTy;
3760 NewWidth = IntWidth;
3761 NewSign = true;
3762 } else if (ECD->getType() == BestType) {
3763 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003764 if (getLangOptions().CPlusPlus)
3765 // C++ [dcl.enum]p4: Following the closing brace of an
3766 // enum-specifier, each enumerator has the type of its
3767 // enumeration.
3768 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003769 continue;
3770 } else {
3771 NewTy = BestType;
3772 NewWidth = BestWidth;
3773 NewSign = BestType->isSignedIntegerType();
3774 }
3775
3776 // Adjust the APSInt value.
3777 InitVal.extOrTrunc(NewWidth);
3778 InitVal.setIsSigned(NewSign);
3779 ECD->setInitVal(InitVal);
3780
3781 // Adjust the Expr initializer and type.
Chris Lattner13fd4162009-01-15 19:19:42 +00003782 if (ECD->getInitExpr())
3783 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3784 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003785 if (getLangOptions().CPlusPlus)
3786 // C++ [dcl.enum]p4: Following the closing brace of an
3787 // enum-specifier, each enumerator has the type of its
3788 // enumeration.
3789 ECD->setType(EnumType);
3790 else
3791 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003792 }
Chris Lattnerac609682007-08-28 06:15:15 +00003793
Douglas Gregor44b43212008-12-11 16:49:14 +00003794 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003795}
3796
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003797Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003798 ExprArg expr) {
3799 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3800
Douglas Gregor4afa39d2009-01-20 01:17:11 +00003801 return FileScopeAsmDecl::Create(Context, CurContext, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003802}
3803
Douglas Gregorf44515a2008-12-16 22:23:02 +00003804
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003805void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3806 ExprTy *alignment, SourceLocation PragmaLoc,
3807 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3808 Expr *Alignment = static_cast<Expr *>(alignment);
3809
3810 // If specified then alignment must be a "small" power of two.
3811 unsigned AlignmentVal = 0;
3812 if (Alignment) {
3813 llvm::APSInt Val;
3814 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3815 !Val.isPowerOf2() ||
3816 Val.getZExtValue() > 16) {
3817 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3818 delete Alignment;
3819 return; // Ignore
3820 }
3821
3822 AlignmentVal = (unsigned) Val.getZExtValue();
3823 }
3824
3825 switch (Kind) {
3826 case Action::PPK_Default: // pack([n])
3827 PackContext.setAlignment(AlignmentVal);
3828 break;
3829
3830 case Action::PPK_Show: // pack(show)
3831 // Show the current alignment, making sure to show the right value
3832 // for the default.
3833 AlignmentVal = PackContext.getAlignment();
3834 // FIXME: This should come from the target.
3835 if (AlignmentVal == 0)
3836 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003837 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003838 break;
3839
3840 case Action::PPK_Push: // pack(push [, id] [, [n])
3841 PackContext.push(Name);
3842 // Set the new alignment if specified.
3843 if (Alignment)
3844 PackContext.setAlignment(AlignmentVal);
3845 break;
3846
3847 case Action::PPK_Pop: // pack(pop [, id] [, n])
3848 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3849 // "#pragma pack(pop, identifier, n) is undefined"
3850 if (Alignment && Name)
3851 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3852
3853 // Do the pop.
3854 if (!PackContext.pop(Name)) {
3855 // If a name was specified then failure indicates the name
3856 // wasn't found. Otherwise failure indicates the stack was
3857 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003858 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3859 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003860
3861 // FIXME: Warn about popping named records as MSVC does.
3862 } else {
3863 // Pop succeeded, set the new alignment if specified.
3864 if (Alignment)
3865 PackContext.setAlignment(AlignmentVal);
3866 }
3867 break;
3868
3869 default:
3870 assert(0 && "Invalid #pragma pack kind.");
3871 }
3872}
3873
3874bool PragmaPackStack::pop(IdentifierInfo *Name) {
3875 if (Stack.empty())
3876 return false;
3877
3878 // If name is empty just pop top.
3879 if (!Name) {
3880 Alignment = Stack.back().first;
3881 Stack.pop_back();
3882 return true;
3883 }
3884
3885 // Otherwise, find the named record.
3886 for (unsigned i = Stack.size(); i != 0; ) {
3887 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003888 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003889 // Found it, pop up to and including this record.
3890 Alignment = Stack[i].first;
3891 Stack.erase(Stack.begin() + i, Stack.end());
3892 return true;
3893 }
3894 }
3895
3896 return false;
3897}