blob: 5119388dbc714c8a7083c32caaed2ff8c11d3b72 [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"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.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
Douglas Gregor2def4832008-11-17 20:34:05 +000034Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000035 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000036 DeclContext *DC = 0;
37 if (SS) {
38 if (SS->isInvalid())
39 return 0;
40 DC = static_cast<DeclContext*>(SS->getScopeRep());
41 }
42 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000043
Douglas Gregor2ce52f32008-04-13 21:07:44 +000044 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
45 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000046 isa<TagDecl>(IIDecl) ||
47 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000048 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000049 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000050}
51
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000053 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000054 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000055 if (MD->isOutOfLineDefinition())
56 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000057
58 // A C++ inline method is parsed *after* the topmost class it was declared in
59 // is fully parsed (it's "complete").
60 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000061 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000062 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
63 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000064 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000065 DC = RD;
66
67 // Return the declaration context of the topmost class the inline method is
68 // declared in.
69 return DC;
70 }
71
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000072 if (isa<ObjCMethodDecl>(DC))
73 return Context.getTranslationUnitDecl();
74
75 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
76 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000078 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000079}
80
Douglas Gregor44b43212008-12-11 16:49:14 +000081void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000082 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000083 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000084 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000085 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Chris Lattnerb048c982008-04-06 04:47:34 +000088void Sema::PopDeclContext() {
89 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000090
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000091 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000092}
93
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Douglas Gregor074149e2009-01-05 19:45:36 +000096 // Move up the scope chain until we find the nearest enclosing
97 // non-transparent context. The declaration will be introduced into this
98 // scope.
99 while (S->getEntity() &&
100 ((DeclContext *)S->getEntity())->isTransparentContext())
101 S = S->getParent();
102
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000103 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000105 // Add scoped declarations into their context, so that they can be
106 // found later. Declarations without a context won't be inserted
107 // into any context.
108 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
Douglas Gregor482b77d2009-01-12 23:27:07 +0000109 CurContext->addDecl(SD);
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000110
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000111 // C++ [basic.scope]p4:
112 // -- exactly one declaration shall declare a class name or
113 // enumeration name that is not a typedef name and the other
114 // declarations shall all refer to the same object or
115 // enumerator, or all refer to functions and function templates;
116 // in this case the class name or enumeration name is hidden.
117 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
118 // We are pushing the name of a tag (enum or class).
Douglas Gregore21b9942009-01-07 16:34:42 +0000119 if (CurContext->getLookupContext()
120 == TD->getDeclContext()->getLookupContext()) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000121 // We're pushing the tag into the current context, which might
122 // require some reshuffling in the identifier resolver.
123 IdentifierResolver::iterator
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000124 I = IdResolver.begin(TD->getDeclName(), CurContext,
125 false/*LookInParentCtx*/),
126 IEnd = IdResolver.end();
127 if (I != IEnd && isDeclInScope(*I, CurContext, S)) {
128 NamedDecl *PrevDecl = *I;
129 for (; I != IEnd && isDeclInScope(*I, CurContext, S);
130 PrevDecl = *I, ++I) {
131 if (TD->declarationReplaces(*I)) {
132 // This is a redeclaration. Remove it from the chain and
133 // break out, so that we'll add in the shadowed
134 // declaration.
135 S->RemoveDecl(*I);
136 if (PrevDecl == *I) {
137 IdResolver.RemoveDecl(*I);
138 IdResolver.AddDecl(TD);
139 return;
140 } else {
141 IdResolver.RemoveDecl(*I);
142 break;
143 }
144 }
145 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000147 // There is already a declaration with the same name in the same
148 // scope, which is not a tag declaration. It must be found
149 // before we find the new declaration, so insert the new
150 // declaration at the end of the chain.
151 IdResolver.AddShadowedDecl(TD, PrevDecl);
152
153 return;
Douglas Gregor44b43212008-12-11 16:49:14 +0000154 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000155 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000156 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000157 // We are pushing the name of a function, which might be an
158 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000159 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregorce356072009-01-06 23:51:29 +0000160 DeclContext *DC = FD->getDeclContext()->getLookupContext();
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000161 IdentifierResolver::iterator Redecl
Douglas Gregor074149e2009-01-05 19:45:36 +0000162 = std::find_if(IdResolver.begin(FD->getDeclName(), DC,
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000163 false/*LookInParentCtx*/),
164 IdResolver.end(),
165 std::bind1st(std::mem_fun(&ScopedDecl::declarationReplaces),
166 FD));
167 if (Redecl != IdResolver.end()) {
168 // There is already a declaration of a function on our
169 // IdResolver chain. Replace it with this declaration.
170 S->RemoveDecl(*Redecl);
171 IdResolver.RemoveDecl(*Redecl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000172 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000173 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000174
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000175 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000176}
177
Steve Naroffb216c882007-10-09 22:01:59 +0000178void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000179 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000180 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
181 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
184 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000185 Decl *TmpD = static_cast<Decl*>(*I);
186 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000187
Douglas Gregor44b43212008-12-11 16:49:14 +0000188 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
189 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000190
Douglas Gregor44b43212008-12-11 16:49:14 +0000191 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000192
Douglas Gregor44b43212008-12-11 16:49:14 +0000193 // Remove this name from our lexical scope.
194 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 }
196}
197
Steve Naroffe8043c32008-04-01 23:04:06 +0000198/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
199/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000200ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000201 // The third "scope" argument is 0 since we aren't enabling lazy built-in
202 // creation from this context.
203 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000204
Steve Naroffb327ce02008-04-02 14:35:35 +0000205 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000206}
207
Douglas Gregor1a0d31a2009-01-12 18:45:55 +0000208/// getNonFieldDeclScope - Retrieves the innermost scope, starting
209/// from S, where a non-field would be declared. This routine copes
210/// with the difference between C and C++ scoping rules in structs and
211/// unions. For example, the following code is well-formed in C but
212/// ill-formed in C++:
213/// @code
214/// struct S6 {
215/// enum { BAR } e;
216/// };
217///
218/// void test_S6() {
219/// struct S6 a;
220/// a.e = BAR;
221/// }
222/// @endcode
223/// For the declaration of BAR, this routine will return a different
224/// scope. The scope S will be the scope of the unnamed enumeration
225/// within S6. In C++, this routine will return the scope associated
226/// with S6, because the enumeration's scope is a transparent
227/// context but structures can contain non-field names. In C, this
228/// routine will return the translation unit scope, since the
229/// enumeration's scope is a transparent context and structures cannot
230/// contain non-field names.
231Scope *Sema::getNonFieldDeclScope(Scope *S) {
232 while (((S->getFlags() & Scope::DeclScope) == 0) ||
233 (S->getEntity() &&
234 ((DeclContext *)S->getEntity())->isTransparentContext()) ||
235 (S->isClassScope() && !getLangOptions().CPlusPlus))
236 S = S->getParent();
237 return S;
238}
239
Steve Naroffe8043c32008-04-01 23:04:06 +0000240/// LookupDecl - Look up the inner-most declaration in the specified
Douglas Gregorf780abc2008-12-30 03:27:21 +0000241/// namespace. NamespaceNameOnly - during lookup only namespace names
242/// are considered as required in C++ [basic.lookup.udir] 3.4.6.p1
243/// 'When looking up a namespace-name in a using-directive or
244/// namespace-alias-definition, only namespace names are considered.'
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000245///
246/// Note: The use of this routine is deprecated. Please use
247/// LookupName, LookupQualifiedName, or LookupParsedName instead.
248Sema::LookupResult
249Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
250 const DeclContext *LookupCtx,
251 bool enableLazyBuiltinCreation,
252 bool LookInParent,
253 bool NamespaceNameOnly) {
254 LookupCriteria::NameKind Kind;
255 if (NSI == Decl::IDNS_Ordinary) {
256 if (NamespaceNameOnly)
257 Kind = LookupCriteria::Namespace;
258 else
259 Kind = LookupCriteria::Ordinary;
260 } else if (NSI == Decl::IDNS_Tag)
261 Kind = LookupCriteria::Tag;
262 else if (NSI == Decl::IDNS_Member)
263 Kind = LookupCriteria::Member;
264 else
265 assert(false && "Unable to grok LookupDecl NSI argument");
Chris Lattner7f925cc2008-04-11 07:00:53 +0000266
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000267 if (LookupCtx)
268 return LookupQualifiedName(const_cast<DeclContext *>(LookupCtx), Name,
269 LookupCriteria(Kind, !LookInParent,
270 getLangOptions().CPlusPlus));
Douglas Gregor72de6672009-01-08 20:45:30 +0000271
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000272 // Unqualified lookup
273 return LookupName(S, Name,
274 LookupCriteria(Kind, !LookInParent,
275 getLangOptions().CPlusPlus));
Reid Spencer5f016e22007-07-11 17:01:13 +0000276}
277
Chris Lattner95e2c712008-05-05 22:18:14 +0000278void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000279 if (!Context.getBuiltinVaListType().isNull())
280 return;
281
282 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000283 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000284 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000285 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
286}
287
Reid Spencer5f016e22007-07-11 17:01:13 +0000288/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
289/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000290ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
291 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000292 Builtin::ID BID = (Builtin::ID)bid;
293
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000294 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000295 InitBuiltinVaListType();
296
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000297 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000298 FunctionDecl *New = FunctionDecl::Create(Context,
299 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000300 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000301 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000302
Chris Lattner95e2c712008-05-05 22:18:14 +0000303 // Create Decl objects for each parameter, adding them to the
304 // FunctionDecl.
305 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
306 llvm::SmallVector<ParmVarDecl*, 16> Params;
307 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
308 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
309 FT->getArgType(i), VarDecl::None, 0,
310 0));
Ted Kremenekfc767612009-01-14 00:42:25 +0000311 New->setParams(Context, &Params[0], Params.size());
Chris Lattner95e2c712008-05-05 22:18:14 +0000312 }
313
314
315
Chris Lattner7f925cc2008-04-11 07:00:53 +0000316 // TUScope is the translation-unit scope to insert this function into.
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000317 // FIXME: This is hideous. We need to teach PushOnScopeChains to
318 // relate Scopes to DeclContexts, and probably eliminate CurContext
319 // entirely, but we're not there yet.
320 DeclContext *SavedContext = CurContext;
321 CurContext = Context.getTranslationUnitDecl();
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000322 PushOnScopeChains(New, TUScope);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +0000323 CurContext = SavedContext;
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 return New;
325}
326
Sebastian Redlc42e1182008-11-11 11:37:55 +0000327/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
328/// everything from the standard library is defined.
329NamespaceDecl *Sema::GetStdNamespace() {
330 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000331 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000332 DeclContext *Global = Context.getTranslationUnitDecl();
Douglas Gregoreb11cd02009-01-14 22:20:51 +0000333 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000334 0, Global, /*enableLazyBuiltinCreation=*/false);
335 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
336 }
337 return StdNamespace;
338}
339
Reid Spencer5f016e22007-07-11 17:01:13 +0000340/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
341/// and scope as a previous declaration 'Old'. Figure out how to resolve this
342/// situation, merging decls or emitting diagnostics as appropriate.
343///
Steve Naroffe8043c32008-04-01 23:04:06 +0000344TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000345 // Allow multiple definitions for ObjC built-in typedefs.
346 // FIXME: Verify the underlying types are equivalent!
347 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000348 const IdentifierInfo *TypeID = New->getIdentifier();
349 switch (TypeID->getLength()) {
350 default: break;
351 case 2:
352 if (!TypeID->isStr("id"))
353 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000354 Context.setObjCIdType(New);
355 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000356 case 5:
357 if (!TypeID->isStr("Class"))
358 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000359 Context.setObjCClassType(New);
360 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000361 case 3:
362 if (!TypeID->isStr("SEL"))
363 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000364 Context.setObjCSelType(New);
365 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000366 case 8:
367 if (!TypeID->isStr("Protocol"))
368 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000369 Context.setObjCProtoType(New->getUnderlyingType());
370 return New;
371 }
372 // Fall through - the typedef name was not a builtin type.
373 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000374 // Verify the old decl was also a typedef.
375 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
376 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000377 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000378 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000379 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 return New;
381 }
382
Chris Lattner99cb9972008-07-25 18:44:27 +0000383 // If the typedef types are not identical, reject them in all languages and
384 // with any extensions enabled.
385 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
386 Context.getCanonicalType(Old->getUnderlyingType()) !=
387 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000388 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000389 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000390 Diag(Old->getLocation(), diag::note_previous_definition);
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000391 return New;
Chris Lattner99cb9972008-07-25 18:44:27 +0000392 }
393
Eli Friedman54ecfce2008-06-11 06:20:39 +0000394 if (getLangOptions().Microsoft) return New;
395
Douglas Gregorbbe27432008-11-21 16:29:06 +0000396 // C++ [dcl.typedef]p2:
397 // In a given non-class scope, a typedef specifier can be used to
398 // redefine the name of any type declared in that scope to refer
399 // to the type to which it already refers.
400 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
401 return New;
402
403 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000404 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
405 // *either* declaration is in a system header. The code below implements
406 // this adhoc compatibility rule. FIXME: The following code will not
407 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000408 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
409 SourceManager &SrcMgr = Context.getSourceManager();
410 if (SrcMgr.isInSystemHeader(Old->getLocation()))
411 return New;
412 if (SrcMgr.isInSystemHeader(New->getLocation()))
413 return New;
414 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000415
Chris Lattner08631c52008-11-23 21:45:46 +0000416 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000417 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 return New;
419}
420
Chris Lattner6b6b5372008-06-26 18:38:35 +0000421/// DeclhasAttr - returns true if decl Declaration already has the target
422/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000423static bool DeclHasAttr(const Decl *decl, const Attr *target) {
424 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
425 if (attr->getKind() == target->getKind())
426 return true;
427
428 return false;
429}
430
431/// MergeAttributes - append attributes from the Old decl to the New one.
432static void MergeAttributes(Decl *New, Decl *Old) {
433 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
434
Chris Lattnerddee4232008-03-03 03:28:21 +0000435 while (attr) {
436 tmp = attr;
437 attr = attr->getNext();
438
439 if (!DeclHasAttr(New, tmp)) {
Anton Korobeynikov2f402702008-12-26 00:52:02 +0000440 tmp->setInherited(true);
Chris Lattnerddee4232008-03-03 03:28:21 +0000441 New->addAttr(tmp);
442 } else {
443 tmp->setNext(0);
444 delete(tmp);
445 }
446 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000447
448 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000449}
450
Chris Lattner04421082008-04-08 04:40:51 +0000451/// MergeFunctionDecl - We just parsed a function 'New' from
452/// declarator D which has the same name and scope as a previous
453/// declaration 'Old'. Figure out how to resolve this situation,
454/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000455/// Redeclaration will be set true if this New is a redeclaration OldD.
456///
457/// In C++, New and Old must be declarations that are not
458/// overloaded. Use IsOverload to determine whether New and Old are
459/// overloaded, and to select the Old declaration that New should be
460/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000461FunctionDecl *
462Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000463 assert(!isa<OverloadedFunctionDecl>(OldD) &&
464 "Cannot merge with an overloaded function declaration");
465
Douglas Gregorf0097952008-04-21 02:02:58 +0000466 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // Verify the old decl was also a function.
468 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
469 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000470 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000471 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000472 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 return New;
474 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000475
476 // Determine whether the previous declaration was a definition,
477 // implicit declaration, or a declaration.
478 diag::kind PrevDiag;
479 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000480 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000481 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000482 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000483 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000484 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000485
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000486 QualType OldQType = Context.getCanonicalType(Old->getType());
487 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000488
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000489 if (getLangOptions().CPlusPlus) {
490 // (C++98 13.1p2):
491 // Certain function declarations cannot be overloaded:
492 // -- Function declarations that differ only in the return type
493 // cannot be overloaded.
494 QualType OldReturnType
495 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
496 QualType NewReturnType
497 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
498 if (OldReturnType != NewReturnType) {
499 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
500 Diag(Old->getLocation(), PrevDiag);
Douglas Gregor3fc749d2008-12-23 00:26:44 +0000501 Redeclaration = true;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000502 return New;
503 }
504
505 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
506 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
507 if (OldMethod && NewMethod) {
508 // -- Member function declarations with the same name and the
509 // same parameter types cannot be overloaded if any of them
510 // is a static member function declaration.
511 if (OldMethod->isStatic() || NewMethod->isStatic()) {
512 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
513 Diag(Old->getLocation(), PrevDiag);
514 return New;
515 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000516
517 // C++ [class.mem]p1:
518 // [...] A member shall not be declared twice in the
519 // member-specification, except that a nested class or member
520 // class template can be declared and then later defined.
521 if (OldMethod->getLexicalDeclContext() ==
522 NewMethod->getLexicalDeclContext()) {
523 unsigned NewDiag;
524 if (isa<CXXConstructorDecl>(OldMethod))
525 NewDiag = diag::err_constructor_redeclared;
526 else if (isa<CXXDestructorDecl>(NewMethod))
527 NewDiag = diag::err_destructor_redeclared;
528 else if (isa<CXXConversionDecl>(NewMethod))
529 NewDiag = diag::err_conv_function_redeclared;
530 else
531 NewDiag = diag::err_member_redeclared;
532
533 Diag(New->getLocation(), NewDiag);
534 Diag(Old->getLocation(), PrevDiag);
535 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000536 }
537
538 // (C++98 8.3.5p3):
539 // All declarations for a function shall agree exactly in both the
540 // return type and the parameter-type-list.
541 if (OldQType == NewQType) {
542 // We have a redeclaration.
543 MergeAttributes(New, Old);
544 Redeclaration = true;
545 return MergeCXXFunctionDecl(New, Old);
546 }
547
548 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000549 }
Chris Lattner04421082008-04-08 04:40:51 +0000550
551 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000552 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000553 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000554 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000555 MergeAttributes(New, Old);
556 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000557 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000558 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000559
Steve Naroff837618c2008-01-16 15:01:34 +0000560 // A function that has already been declared has been redeclared or defined
561 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000562
Reid Spencer5f016e22007-07-11 17:01:13 +0000563 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
564 // TODO: This is totally simplistic. It should handle merging functions
565 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000566 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000567 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000568 return New;
569}
570
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000571/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000572static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000573 if (VD->isFileVarDecl())
574 return (!VD->getInit() &&
575 (VD->getStorageClass() == VarDecl::None ||
576 VD->getStorageClass() == VarDecl::Static));
577 return false;
578}
579
580/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
581/// when dealing with C "tentative" external object definitions (C99 6.9.2).
582void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
583 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000584 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000585
Douglas Gregore21b9942009-01-07 16:34:42 +0000586 // FIXME: I don't think this will actually see all of the
Douglas Gregor6ed40e32008-12-23 21:05:05 +0000587 // redefinitions. Can't we check this property on-the-fly?
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000588 for (IdentifierResolver::iterator
589 I = IdResolver.begin(VD->getIdentifier(),
590 VD->getDeclContext(), false/*LookInParentCtx*/),
591 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000592 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000593 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
594
Steve Narofff855e6f2008-08-10 15:20:13 +0000595 // Handle the following case:
596 // int a[10];
597 // int a[]; - the code below makes sure we set the correct type.
598 // int a[11]; - this is an error, size isn't 10.
599 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
600 OldDecl->getType()->isConstantArrayType())
601 VD->setType(OldDecl->getType());
602
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000603 // Check for "tentative" definitions. We can't accomplish this in
604 // MergeVarDecl since the initializer hasn't been attached.
605 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
606 continue;
607
608 // Handle __private_extern__ just like extern.
609 if (OldDecl->getStorageClass() != VarDecl::Extern &&
610 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
611 VD->getStorageClass() != VarDecl::Extern &&
612 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000613 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000614 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000615 }
616 }
617 }
618}
619
Reid Spencer5f016e22007-07-11 17:01:13 +0000620/// MergeVarDecl - We just parsed a variable 'New' which has the same name
621/// and scope as a previous declaration 'Old'. Figure out how to resolve this
622/// situation, merging decls or emitting diagnostics as appropriate.
623///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000624/// Tentative definition rules (C99 6.9.2p2) are checked by
625/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
626/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000627///
Steve Naroffe8043c32008-04-01 23:04:06 +0000628VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000629 // Verify the old decl was also a variable.
630 VarDecl *Old = dyn_cast<VarDecl>(OldD);
631 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000632 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000633 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000634 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000635 return New;
636 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000637
638 MergeAttributes(New, Old);
639
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000641 QualType OldCType = Context.getCanonicalType(Old->getType());
642 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000643 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Douglas Gregor6037fcb2009-01-09 19:42:16 +0000644 Diag(New->getLocation(), diag::err_redefinition_different_type)
645 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000646 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 return New;
648 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000649 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
650 if (New->getStorageClass() == VarDecl::Static &&
651 (Old->getStorageClass() == VarDecl::None ||
652 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000653 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000654 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000655 return New;
656 }
657 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
658 if (New->getStorageClass() != VarDecl::Static &&
659 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000660 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000661 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000662 return New;
663 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000664 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
665 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000666 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000667 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000668 }
669 return New;
670}
671
Chris Lattner04421082008-04-08 04:40:51 +0000672/// CheckParmsForFunctionDef - Check that the parameters of the given
673/// function are appropriate for the definition of a function. This
674/// takes care of any checks that cannot be performed on the
675/// declaration itself, e.g., that the types of each of the function
676/// parameters are complete.
677bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
678 bool HasInvalidParm = false;
679 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
680 ParmVarDecl *Param = FD->getParamDecl(p);
681
682 // C99 6.7.5.3p4: the parameters in a parameter type list in a
683 // function declarator that is part of a function definition of
684 // that function shall not have incomplete type.
685 if (Param->getType()->isIncompleteType() &&
686 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000687 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000688 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000689 Param->setInvalidDecl();
690 HasInvalidParm = true;
691 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000692
693 // C99 6.9.1p5: If the declarator includes a parameter type list, the
694 // declaration of each parameter shall include an identifier.
695 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
696 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000697 }
698
699 return HasInvalidParm;
700}
701
Reid Spencer5f016e22007-07-11 17:01:13 +0000702/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
703/// no declarator (e.g. "struct foo;") is parsed.
704Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000705 TagDecl *Tag
706 = dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
707 if (RecordDecl *Record = dyn_cast_or_null<RecordDecl>(Tag)) {
708 if (!Record->getDeclName() && Record->isDefinition() &&
709 DS.getStorageClassSpec() != DeclSpec::SCS_typedef)
710 return BuildAnonymousStructOrUnion(S, DS, Record);
711
712 // Microsoft allows unnamed struct/union fields. Don't complain
713 // about them.
714 // FIXME: Should we support Microsoft's extensions in this area?
715 if (Record->getDeclName() && getLangOptions().Microsoft)
716 return Tag;
717 }
718
Douglas Gregoree159c12009-01-13 23:10:51 +0000719 // Permit typedefs without declarators as a Microsoft extension.
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000720 if (!DS.isMissingDeclaratorOk()) {
Douglas Gregoree159c12009-01-13 23:10:51 +0000721 if (getLangOptions().Microsoft &&
722 DS.getStorageClassSpec() == DeclSpec::SCS_typedef) {
723 Diag(DS.getSourceRange().getBegin(), diag::ext_no_declarators)
724 << DS.getSourceRange();
725 return Tag;
726 }
727
Sebastian Redla4ed0d82008-12-28 15:28:59 +0000728 // FIXME: This diagnostic is emitted even when various previous
729 // errors occurred (see e.g. test/Sema/decl-invalid.c). However,
730 // DeclSpec has no means of communicating this information, and the
731 // responsible parser functions are quite far apart.
732 Diag(DS.getSourceRange().getBegin(), diag::err_no_declarators)
733 << DS.getSourceRange();
734 return 0;
735 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000736
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000737 return Tag;
738}
739
740/// InjectAnonymousStructOrUnionMembers - Inject the members of the
741/// anonymous struct or union AnonRecord into the owning context Owner
742/// and scope S. This routine will be invoked just after we realize
743/// that an unnamed union or struct is actually an anonymous union or
744/// struct, e.g.,
745///
746/// @code
747/// union {
748/// int i;
749/// float f;
750/// }; // InjectAnonymousStructOrUnionMembers called here to inject i and
751/// // f into the surrounding scope.x
752/// @endcode
753///
754/// This routine is recursive, injecting the names of nested anonymous
755/// structs/unions into the owning context and scope as well.
756bool Sema::InjectAnonymousStructOrUnionMembers(Scope *S, DeclContext *Owner,
757 RecordDecl *AnonRecord) {
758 bool Invalid = false;
759 for (RecordDecl::field_iterator F = AnonRecord->field_begin(),
760 FEnd = AnonRecord->field_end();
761 F != FEnd; ++F) {
762 if ((*F)->getDeclName()) {
763 Decl *PrevDecl = LookupDecl((*F)->getDeclName(), Decl::IDNS_Ordinary,
764 S, Owner, false, false, false);
765 if (PrevDecl && !isa<TagDecl>(PrevDecl)) {
766 // C++ [class.union]p2:
767 // The names of the members of an anonymous union shall be
768 // distinct from the names of any other entity in the
769 // scope in which the anonymous union is declared.
770 unsigned diagKind
771 = AnonRecord->isUnion()? diag::err_anonymous_union_member_redecl
772 : diag::err_anonymous_struct_member_redecl;
773 Diag((*F)->getLocation(), diagKind)
774 << (*F)->getDeclName();
775 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
776 Invalid = true;
777 } else {
778 // C++ [class.union]p2:
779 // For the purpose of name lookup, after the anonymous union
780 // definition, the members of the anonymous union are
781 // considered to have been defined in the scope in which the
782 // anonymous union is declared.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000783 Owner->insert(*F);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000784 S->AddDecl(*F);
785 IdResolver.AddDecl(*F);
786 }
787 } else if (const RecordType *InnerRecordType
788 = (*F)->getType()->getAsRecordType()) {
789 RecordDecl *InnerRecord = InnerRecordType->getDecl();
790 if (InnerRecord->isAnonymousStructOrUnion())
791 Invalid = Invalid ||
792 InjectAnonymousStructOrUnionMembers(S, Owner, InnerRecord);
793 }
794 }
795
796 return Invalid;
797}
798
799/// ActOnAnonymousStructOrUnion - Handle the declaration of an
800/// anonymous structure or union. Anonymous unions are a C++ feature
801/// (C++ [class.union]) and a GNU C extension; anonymous structures
802/// are a GNU C and GNU C++ extension.
803Sema::DeclTy *Sema::BuildAnonymousStructOrUnion(Scope *S, DeclSpec &DS,
804 RecordDecl *Record) {
805 DeclContext *Owner = Record->getDeclContext();
806
807 // Diagnose whether this anonymous struct/union is an extension.
808 if (Record->isUnion() && !getLangOptions().CPlusPlus)
809 Diag(Record->getLocation(), diag::ext_anonymous_union);
810 else if (!Record->isUnion())
811 Diag(Record->getLocation(), diag::ext_anonymous_struct);
812
813 // C and C++ require different kinds of checks for anonymous
814 // structs/unions.
815 bool Invalid = false;
816 if (getLangOptions().CPlusPlus) {
817 const char* PrevSpec = 0;
818 // C++ [class.union]p3:
819 // Anonymous unions declared in a named namespace or in the
820 // global namespace shall be declared static.
821 if (DS.getStorageClassSpec() != DeclSpec::SCS_static &&
822 (isa<TranslationUnitDecl>(Owner) ||
823 (isa<NamespaceDecl>(Owner) &&
824 cast<NamespaceDecl>(Owner)->getDeclName()))) {
825 Diag(Record->getLocation(), diag::err_anonymous_union_not_static);
826 Invalid = true;
827
828 // Recover by adding 'static'.
829 DS.SetStorageClassSpec(DeclSpec::SCS_static, SourceLocation(), PrevSpec);
830 }
831 // C++ [class.union]p3:
832 // A storage class is not allowed in a declaration of an
833 // anonymous union in a class scope.
834 else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified &&
835 isa<RecordDecl>(Owner)) {
836 Diag(DS.getStorageClassSpecLoc(),
837 diag::err_anonymous_union_with_storage_spec);
838 Invalid = true;
839
840 // Recover by removing the storage specifier.
841 DS.SetStorageClassSpec(DeclSpec::SCS_unspecified, SourceLocation(),
842 PrevSpec);
843 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000844
845 // C++ [class.union]p2:
846 // The member-specification of an anonymous union shall only
847 // define non-static data members. [Note: nested types and
848 // functions cannot be declared within an anonymous union. ]
849 for (DeclContext::decl_iterator Mem = Record->decls_begin(),
850 MemEnd = Record->decls_end();
851 Mem != MemEnd; ++Mem) {
852 if (FieldDecl *FD = dyn_cast<FieldDecl>(*Mem)) {
853 // C++ [class.union]p3:
854 // An anonymous union shall not have private or protected
855 // members (clause 11).
856 if (FD->getAccess() == AS_protected || FD->getAccess() == AS_private) {
857 Diag(FD->getLocation(), diag::err_anonymous_record_nonpublic_member)
858 << (int)Record->isUnion() << (int)(FD->getAccess() == AS_protected);
859 Invalid = true;
860 }
861 } else if ((*Mem)->isImplicit()) {
862 // Any implicit members are fine.
863 } else if (RecordDecl *MemRecord = dyn_cast<RecordDecl>(*Mem)) {
864 if (!MemRecord->isAnonymousStructOrUnion() &&
865 MemRecord->getDeclName()) {
866 // This is a nested type declaration.
867 Diag(MemRecord->getLocation(), diag::err_anonymous_record_with_type)
868 << (int)Record->isUnion();
869 Invalid = true;
870 }
871 } else {
872 // We have something that isn't a non-static data
873 // member. Complain about it.
874 unsigned DK = diag::err_anonymous_record_bad_member;
875 if (isa<TypeDecl>(*Mem))
876 DK = diag::err_anonymous_record_with_type;
877 else if (isa<FunctionDecl>(*Mem))
878 DK = diag::err_anonymous_record_with_function;
879 else if (isa<VarDecl>(*Mem))
880 DK = diag::err_anonymous_record_with_static;
881 Diag((*Mem)->getLocation(), DK)
882 << (int)Record->isUnion();
883 Invalid = true;
884 }
885 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000886 } else {
887 // FIXME: Check GNU C semantics
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000888 if (Record->isUnion() && !Owner->isRecord()) {
889 Diag(Record->getLocation(), diag::err_anonymous_union_not_member)
890 << (int)getLangOptions().CPlusPlus;
891 Invalid = true;
892 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000893 }
894
895 if (!Record->isUnion() && !Owner->isRecord()) {
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000896 Diag(Record->getLocation(), diag::err_anonymous_struct_not_member)
897 << (int)getLangOptions().CPlusPlus;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000898 Invalid = true;
899 }
900
901 // Create a declaration for this anonymous struct/union.
902 ScopedDecl *Anon = 0;
903 if (RecordDecl *OwningClass = dyn_cast<RecordDecl>(Owner)) {
904 Anon = FieldDecl::Create(Context, OwningClass, Record->getLocation(),
905 /*IdentifierInfo=*/0,
906 Context.getTypeDeclType(Record),
907 /*BitWidth=*/0, /*Mutable=*/false,
908 /*PrevDecl=*/0);
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000909 Anon->setAccess(AS_public);
910 if (getLangOptions().CPlusPlus)
911 FieldCollector->Add(cast<FieldDecl>(Anon));
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000912 } else {
913 VarDecl::StorageClass SC;
914 switch (DS.getStorageClassSpec()) {
915 default: assert(0 && "Unknown storage class!");
916 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
917 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
918 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
919 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
920 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
921 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
922 case DeclSpec::SCS_mutable:
923 // mutable can only appear on non-static class members, so it's always
924 // an error here
925 Diag(Record->getLocation(), diag::err_mutable_nonmember);
926 Invalid = true;
927 SC = VarDecl::None;
928 break;
929 }
930
931 Anon = VarDecl::Create(Context, Owner, Record->getLocation(),
932 /*IdentifierInfo=*/0,
933 Context.getTypeDeclType(Record),
934 SC, /*FIXME:LastDeclarator=*/0,
935 DS.getSourceRange().getBegin());
936 }
Douglas Gregor6b3945f2009-01-07 19:46:03 +0000937 Anon->setImplicit();
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000938
939 // Add the anonymous struct/union object to the current
940 // context. We'll be referencing this object when we refer to one of
941 // its members.
Douglas Gregor482b77d2009-01-12 23:27:07 +0000942 Owner->addDecl(Anon);
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000943
944 // Inject the members of the anonymous struct/union into the owning
945 // context and into the identifier resolver chain for name lookup
946 // purposes.
Douglas Gregor4920f1f2009-01-12 22:49:06 +0000947 if (InjectAnonymousStructOrUnionMembers(S, Owner, Record))
948 Invalid = true;
Douglas Gregorbcbffc42009-01-07 00:43:41 +0000949
950 // Mark this as an anonymous struct/union type. Note that we do not
951 // do this until after we have already checked and injected the
952 // members of this anonymous struct/union type, because otherwise
953 // the members could be injected twice: once by DeclContext when it
954 // builds its lookup table, and once by
955 // InjectAnonymousStructOrUnionMembers.
956 Record->setAnonymousStructOrUnion(true);
957
958 if (Invalid)
959 Anon->setInvalidDecl();
960
961 return Anon;
Reid Spencer5f016e22007-07-11 17:01:13 +0000962}
963
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000964bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType,
965 bool DirectInit) {
Steve Narofff0090632007-09-02 02:04:30 +0000966 // Get the type before calling CheckSingleAssignmentConstraints(), since
967 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000968 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000969
Douglas Gregor09f41cf2009-01-14 15:45:31 +0000970 if (getLangOptions().CPlusPlus) {
971 // FIXME: I dislike this error message. A lot.
972 if (PerformImplicitConversion(Init, DeclType, "initializing", DirectInit))
973 return Diag(Init->getSourceRange().getBegin(),
974 diag::err_typecheck_convert_incompatible)
975 << DeclType << Init->getType() << "initializing"
976 << Init->getSourceRange();
977
978 return false;
979 }
Douglas Gregor45920e82008-12-19 17:40:08 +0000980
Chris Lattner5cf216b2008-01-04 18:04:52 +0000981 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
982 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
983 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000984}
985
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000986bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000987 const ArrayType *AT = Context.getAsArrayType(DeclT);
988
989 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000990 // C99 6.7.8p14. We have an array of character type with unknown size
991 // being initialized to a string literal.
992 llvm::APSInt ConstVal(32);
993 ConstVal = strLiteral->getByteLength() + 1;
994 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000995 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000996 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000997 } else {
998 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000999 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001000 // FIXME: Avoid truncation for 64-bit length strings.
1001 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001002 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001003 diag::warn_initializer_string_for_char_array_too_long)
1004 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001005 }
1006 // Set type from "char *" to "constant array of char".
1007 strLiteral->setType(DeclT);
1008 // For now, we always return false (meaning success).
1009 return false;
1010}
1011
1012StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001013 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +00001014 if (AT && AT->getElementType()->isCharType()) {
1015 return dyn_cast<StringLiteral>(Init);
1016 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001017 return 0;
1018}
1019
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001020bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
1021 SourceLocation InitLoc,
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001022 DeclarationName InitEntity,
1023 bool DirectInit) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +00001024 if (DeclType->isDependentType() || Init->isTypeDependent())
1025 return false;
1026
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001027 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +00001028 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001029 // (8.3.2), shall be initialized by an object, or function, of
1030 // type T or by an object that can be converted into a T.
1031 if (DeclType->isReferenceType())
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001032 return CheckReferenceInit(Init, DeclType, 0, false, DirectInit);
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001033
Steve Naroffca107302008-01-21 23:53:58 +00001034 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
1035 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001036 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001037 return Diag(InitLoc, diag::err_variable_object_no_init)
1038 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +00001039
Steve Naroff2fdc3742007-12-10 22:44:33 +00001040 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
1041 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +00001042 // FIXME: Handle wide strings
1043 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
1044 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +00001045
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001046 // C++ [dcl.init]p14:
1047 // -- If the destination type is a (possibly cv-qualified) class
1048 // type:
1049 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
1050 QualType DeclTypeC = Context.getCanonicalType(DeclType);
1051 QualType InitTypeC = Context.getCanonicalType(Init->getType());
1052
1053 // -- If the initialization is direct-initialization, or if it is
1054 // copy-initialization where the cv-unqualified version of the
1055 // source type is the same class as, or a derived class of, the
1056 // class of the destination, constructors are considered.
1057 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
1058 IsDerivedFrom(InitTypeC, DeclTypeC)) {
1059 CXXConstructorDecl *Constructor
1060 = PerformInitializationByConstructor(DeclType, &Init, 1,
1061 InitLoc, Init->getSourceRange(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001062 InitEntity,
1063 DirectInit? IK_Direct : IK_Copy);
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001064 return Constructor == 0;
1065 }
1066
1067 // -- Otherwise (i.e., for the remaining copy-initialization
1068 // cases), user-defined conversion sequences that can
1069 // convert from the source type to the destination type or
1070 // (when a conversion function is used) to a derived class
1071 // thereof are enumerated as described in 13.3.1.4, and the
1072 // best one is chosen through overload resolution
1073 // (13.3). If the conversion cannot be done or is
1074 // ambiguous, the initialization is ill-formed. The
1075 // function selected is called with the initializer
1076 // expression as its argument; if the function is a
1077 // constructor, the call initializes a temporary of the
1078 // destination type.
1079 // FIXME: We're pretending to do copy elision here; return to
1080 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +00001081 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001082 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +00001083
Douglas Gregor61366e92008-12-24 00:01:03 +00001084 if (InitEntity)
1085 return Diag(InitLoc, diag::err_cannot_initialize_decl)
1086 << InitEntity << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1087 << Init->getType() << Init->getSourceRange();
1088 else
1089 return Diag(InitLoc, diag::err_cannot_initialize_decl_noname)
1090 << DeclType << (int)(Init->isLvalue(Context) == Expr::LV_Valid)
1091 << Init->getType() << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001092 }
1093
Steve Naroff1ac6fdd2008-09-29 20:07:05 +00001094 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +00001095 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001096 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
1097 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +00001098
Douglas Gregor09f41cf2009-01-14 15:45:31 +00001099 return CheckSingleInitializer(Init, DeclType, DirectInit);
Douglas Gregor64bffa92008-11-05 16:20:31 +00001100 } else if (getLangOptions().CPlusPlus) {
1101 // C++ [dcl.init]p14:
1102 // [...] If the class is an aggregate (8.5.1), and the initializer
1103 // is a brace-enclosed list, see 8.5.1.
1104 //
1105 // Note: 8.5.1 is handled below; here, we diagnose the case where
1106 // we have an initializer list and a destination type that is not
1107 // an aggregate.
1108 // FIXME: In C++0x, this is yet another form of initialization.
1109 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
1110 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
1111 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001112 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +00001113 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +00001114 }
Steve Naroff2fdc3742007-12-10 22:44:33 +00001115 }
Eli Friedmane6f058f2008-06-06 19:40:52 +00001116
Steve Naroff0cca7492008-05-01 22:18:59 +00001117 InitListChecker CheckInitList(this, InitList, DeclType);
1118 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +00001119}
1120
Douglas Gregor10bd3682008-11-17 22:58:34 +00001121/// GetNameForDeclarator - Determine the full declaration name for the
1122/// given Declarator.
1123DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
1124 switch (D.getKind()) {
1125 case Declarator::DK_Abstract:
1126 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
1127 return DeclarationName();
1128
1129 case Declarator::DK_Normal:
1130 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
1131 return DeclarationName(D.getIdentifier());
1132
1133 case Declarator::DK_Constructor: {
1134 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1135 Ty = Context.getCanonicalType(Ty);
1136 return Context.DeclarationNames.getCXXConstructorName(Ty);
1137 }
1138
1139 case Declarator::DK_Destructor: {
1140 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
1141 Ty = Context.getCanonicalType(Ty);
1142 return Context.DeclarationNames.getCXXDestructorName(Ty);
1143 }
1144
1145 case Declarator::DK_Conversion: {
1146 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
1147 Ty = Context.getCanonicalType(Ty);
1148 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
1149 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +00001150
1151 case Declarator::DK_Operator:
1152 assert(D.getIdentifier() == 0 && "operator names have no identifier");
1153 return Context.DeclarationNames.getCXXOperatorName(
1154 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001155 }
1156
1157 assert(false && "Unknown name kind");
1158 return DeclarationName();
1159}
1160
Douglas Gregor584049d2008-12-15 23:53:10 +00001161/// isNearlyMatchingMemberFunction - Determine whether the C++ member
1162/// functions Declaration and Definition are "nearly" matching. This
1163/// heuristic is used to improve diagnostics in the case where an
1164/// out-of-line member function definition doesn't match any
1165/// declaration within the class.
1166static bool isNearlyMatchingMemberFunction(ASTContext &Context,
1167 FunctionDecl *Declaration,
1168 FunctionDecl *Definition) {
1169 if (Declaration->param_size() != Definition->param_size())
1170 return false;
1171 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
1172 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
1173 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
1174
1175 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
1176 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
1177 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
1178 return false;
1179 }
1180
1181 return true;
1182}
1183
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001184Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +00001185Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
1186 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +00001187 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +00001188 DeclarationName Name = GetNameForDeclarator(D);
1189
Chris Lattnere80a59c2007-07-25 00:24:17 +00001190 // All of these full declarators require an identifier. If it doesn't have
1191 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001192 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +00001193 if (!D.getInvalidType()) // Reject this if we think it is valid.
1194 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +00001195 diag::err_declarator_need_ident)
1196 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +00001197 return 0;
1198 }
1199
Chris Lattner31e05722007-08-26 06:24:45 +00001200 // The scope passed in may not be a decl scope. Zip up the scope tree until
1201 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +00001202 while ((S->getFlags() & Scope::DeclScope) == 0 ||
1203 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +00001204 S = S->getParent();
1205
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001206 DeclContext *DC;
1207 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +00001208 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +00001209 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001210
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001211 // See if this is a redefinition of a variable in the same scope.
1212 if (!D.getCXXScopeSpec().isSet()) {
1213 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +00001214 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001215 } else { // Something like "int foo::x;"
1216 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +00001217 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001218
1219 // C++ 7.3.1.2p2:
1220 // Members (including explicit specializations of templates) of a named
1221 // namespace can also be defined outside that namespace by explicit
1222 // qualification of the name being defined, provided that the entity being
1223 // defined was already declared in the namespace and the definition appears
1224 // after the point of declaration in a namespace that encloses the
1225 // declarations namespace.
1226 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001227 // Note that we only check the context at this point. We don't yet
1228 // have enough information to make sure that PrevDecl is actually
1229 // the declaration we want to match. For example, given:
1230 //
Douglas Gregor9d350972008-12-12 08:25:50 +00001231 // class X {
1232 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +00001233 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +00001234 // };
1235 //
Douglas Gregor584049d2008-12-15 23:53:10 +00001236 // void X::f(int) { } // ill-formed
1237 //
1238 // In this case, PrevDecl will point to the overload set
1239 // containing the two f's declared in X, but neither of them
1240 // matches.
1241 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001242 // The qualifying scope doesn't enclose the original declaration.
1243 // Emit diagnostic based on current scope.
1244 SourceLocation L = D.getIdentifierLoc();
1245 SourceRange R = D.getCXXScopeSpec().getRange();
1246 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001247 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001248 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001249 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001250 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001251 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001252 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001253 }
1254 }
1255
Douglas Gregorf57172b2008-12-08 18:40:42 +00001256 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001257 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001258 InvalidDecl = InvalidDecl
1259 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001260 // Just pretend that we didn't see the previous declaration.
1261 PrevDecl = 0;
1262 }
1263
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001264 // In C++, the previous declaration we find might be a tag type
1265 // (class or enum). In this case, the new declaration will hide the
1266 // tag type.
1267 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1268 PrevDecl = 0;
1269
Chris Lattner41af0932007-11-14 06:34:38 +00001270 QualType R = GetTypeForDeclarator(D, S);
1271 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1272
Reid Spencer5f016e22007-07-11 17:01:13 +00001273 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001274 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1275 if (D.getCXXScopeSpec().isSet()) {
1276 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1277 << D.getCXXScopeSpec().getRange();
1278 InvalidDecl = true;
1279 // Pretend we didn't see the scope specifier.
1280 DC = 0;
1281 }
1282
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001283 // Check that there are no default arguments (C++ only).
1284 if (getLangOptions().CPlusPlus)
1285 CheckExtraCXXDefaultArguments(D);
1286
Chris Lattner41af0932007-11-14 06:34:38 +00001287 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001288 if (!NewTD) return 0;
1289
1290 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001291 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001292 // Merge the decl with the existing one if appropriate. If the decl is
1293 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001294 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001295 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1296 if (NewTD == 0) return 0;
1297 }
1298 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001299 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001300 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1301 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001302 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001303 if (NewTD->getUnderlyingType()->isVariableArrayType())
1304 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1305 else
1306 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1307
Steve Naroffd7444aa2007-08-31 17:20:07 +00001308 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001309 }
1310 }
Chris Lattner41af0932007-11-14 06:34:38 +00001311 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001312 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001313 switch (D.getDeclSpec().getStorageClassSpec()) {
1314 default: assert(0 && "Unknown storage class!");
Sebastian Redl64b45f72009-01-05 20:52:13 +00001315 case DeclSpec::SCS_auto:
Reid Spencer5f016e22007-07-11 17:01:13 +00001316 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001317 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001318 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001319 InvalidDecl = true;
1320 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001321 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1322 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1323 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001324 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001325 }
1326
Chris Lattnera98e58d2008-03-15 21:24:04 +00001327 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001328 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001329 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1330
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001331 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001332 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001333 // This is a C++ constructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001334 assert(DC->isRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001335 "Constructors can only be declared in a member context");
1336
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001337 InvalidDecl = InvalidDecl || CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001338
1339 // Create the new declaration
1340 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001341 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001342 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001343 isExplicit, isInline,
1344 /*isImplicitlyDeclared=*/false);
1345
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001346 if (InvalidDecl)
Douglas Gregor42a552f2008-11-05 20:51:48 +00001347 NewFD->setInvalidDecl();
1348 } else if (D.getKind() == Declarator::DK_Destructor) {
1349 // This is a C++ destructor declaration.
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001350 if (DC->isRecord()) {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001351 InvalidDecl = InvalidDecl || CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001352
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001353 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001354 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001355 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001356 isInline,
1357 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001358
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001359 if (InvalidDecl)
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001360 NewFD->setInvalidDecl();
1361 } else {
1362 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001363
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001364 // Create a FunctionDecl to satisfy the function definition parsing
1365 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001366 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001367 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001368 // FIXME: Move to DeclGroup...
1369 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001370 InvalidDecl = true;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001371 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001372 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001373 } else if (D.getKind() == Declarator::DK_Conversion) {
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001374 if (!DC->isRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001375 Diag(D.getIdentifierLoc(),
1376 diag::err_conv_function_not_member);
1377 return 0;
1378 } else {
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001379 InvalidDecl = InvalidDecl || CheckConversionDeclarator(D, R, SC);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001380
Douglas Gregor70316a02008-12-26 15:00:45 +00001381 NewFD = CXXConversionDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001382 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001383 isInline, isExplicit);
1384
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001385 if (InvalidDecl)
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001386 NewFD->setInvalidDecl();
1387 }
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001388 } else if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001389 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001390 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001391 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001392 (SC == FunctionDecl::Static), isInline,
1393 LastDeclarator);
1394 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001395 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001396 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001397 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001398 // FIXME: Move to DeclGroup...
1399 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001400 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001401
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001402 // Set the lexical context. If the declarator has a C++
1403 // scope specifier, the lexical context will be different
1404 // from the semantic context.
1405 NewFD->setLexicalDeclContext(CurContext);
1406
Daniel Dunbara80f8742008-08-05 01:35:17 +00001407 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001408 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001409 // The parser guarantees this is a string.
1410 StringLiteral *SE = cast<StringLiteral>(E);
1411 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1412 SE->getByteLength())));
1413 }
1414
Chris Lattner04421082008-04-08 04:40:51 +00001415 // Copy the parameter declarations from the declarator D to
1416 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001417 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001418 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1419
1420 // Create Decl objects for each parameter, adding them to the
1421 // FunctionDecl.
1422 llvm::SmallVector<ParmVarDecl*, 16> Params;
1423
1424 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1425 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001426 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001427 // We let through "const void" here because Sema::GetTypeForDeclarator
1428 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001429 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1430 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001431 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1432 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001433 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1434
Chris Lattnerdef026a2008-04-10 02:26:16 +00001435 // In C++, the empty parameter-type-list must be spelled "void"; a
1436 // typedef of void is not permitted.
1437 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001438 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001439 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1440 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001441 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001442 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1443 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1444 }
1445
Ted Kremenekfc767612009-01-14 00:42:25 +00001446 NewFD->setParams(Context, &Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001447 } else if (R->getAsTypedefType()) {
1448 // When we're declaring a function with a typedef, as in the
1449 // following example, we'll need to synthesize (unnamed)
1450 // parameters for use in the declaration.
1451 //
1452 // @code
1453 // typedef void fn(int);
1454 // fn f;
1455 // @endcode
1456 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1457 if (!FT) {
1458 // This is a typedef of a function with no prototype, so we
1459 // don't need to do anything.
1460 } else if ((FT->getNumArgs() == 0) ||
1461 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1462 FT->getArgType(0)->isVoidType())) {
1463 // This is a zero-argument function. We don't need to do anything.
1464 } else {
1465 // Synthesize a parameter for each argument type.
1466 llvm::SmallVector<ParmVarDecl*, 16> Params;
1467 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1468 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001469 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001470 SourceLocation(), 0,
1471 *ArgType, VarDecl::None,
1472 0, 0));
1473 }
1474
Ted Kremenekfc767612009-01-14 00:42:25 +00001475 NewFD->setParams(Context, &Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001476 }
Chris Lattner04421082008-04-08 04:40:51 +00001477 }
1478
Douglas Gregor72b505b2008-12-16 21:30:33 +00001479 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1480 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Sebastian Redl64b45f72009-01-05 20:52:13 +00001481 else if (isa<CXXDestructorDecl>(NewFD)) {
1482 CXXRecordDecl *Record = cast<CXXRecordDecl>(NewFD->getParent());
1483 Record->setUserDeclaredDestructor(true);
1484 // C++ [class]p4: A POD-struct is an aggregate class that has [...] no
1485 // user-defined destructor.
1486 Record->setPOD(false);
1487 } else if (CXXConversionDecl *Conversion =
1488 dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001489 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001490
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001491 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1492 if (NewFD->isOverloadedOperator() &&
1493 CheckOverloadedOperatorDeclaration(NewFD))
1494 NewFD->setInvalidDecl();
1495
Steve Naroffffce4d52008-01-09 23:34:55 +00001496 // Merge the decl with the existing one if appropriate. Since C functions
1497 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001498 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001499 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001500 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001501
1502 // If C++, determine whether NewFD is an overload of PrevDecl or
1503 // a declaration that requires merging. If it's an overload,
1504 // there's no more work to do here; we'll just add the new
1505 // function to the scope.
1506 OverloadedFunctionDecl::function_iterator MatchedDecl;
1507 if (!getLangOptions().CPlusPlus ||
1508 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1509 Decl *OldDecl = PrevDecl;
1510
1511 // If PrevDecl was an overloaded function, extract the
1512 // FunctionDecl that matched.
1513 if (isa<OverloadedFunctionDecl>(PrevDecl))
1514 OldDecl = *MatchedDecl;
1515
1516 // NewFD and PrevDecl represent declarations that need to be
1517 // merged.
1518 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1519
1520 if (NewFD == 0) return 0;
1521 if (Redeclaration) {
1522 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1523
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001524 // An out-of-line member function declaration must also be a
1525 // definition (C++ [dcl.meaning]p1).
1526 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1527 !InvalidDecl) {
1528 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1529 << D.getCXXScopeSpec().getRange();
1530 NewFD->setInvalidDecl();
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001531 }
1532 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001533 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001534
1535 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1536 // The user tried to provide an out-of-line definition for a
1537 // member function, but there was no such member function
1538 // declared (C++ [class.mfct]p2). For example:
1539 //
1540 // class X {
1541 // void f() const;
1542 // };
1543 //
1544 // void X::f() { } // ill-formed
1545 //
1546 // Complain about this problem, and attempt to suggest close
1547 // matches (e.g., those that differ only in cv-qualifiers and
1548 // whether the parameter types are references).
1549 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1550 << cast<CXXRecordDecl>(DC)->getDeclName()
1551 << D.getCXXScopeSpec().getRange();
1552 InvalidDecl = true;
1553
1554 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1555 if (!PrevDecl) {
1556 // Nothing to suggest.
1557 } else if (OverloadedFunctionDecl *Ovl
1558 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1559 for (OverloadedFunctionDecl::function_iterator
1560 Func = Ovl->function_begin(),
1561 FuncEnd = Ovl->function_end();
1562 Func != FuncEnd; ++Func) {
1563 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1564 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1565
1566 }
1567 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1568 // Suggest this no matter how mismatched it is; it's the only
1569 // thing we have.
1570 unsigned diag;
1571 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1572 diag = diag::note_member_def_close_match;
1573 else if (Method->getBody())
1574 diag = diag::note_previous_definition;
1575 else
1576 diag = diag::note_previous_declaration;
1577 Diag(Method->getLocation(), diag);
1578 }
1579
1580 PrevDecl = 0;
1581 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001582 }
Anton Korobeynikov2f402702008-12-26 00:52:02 +00001583 // Handle attributes. We need to have merged decls when handling attributes
1584 // (for example to check for conflicts, etc).
1585 ProcessDeclAttributes(NewFD, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001586 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001587
Douglas Gregor584049d2008-12-15 23:53:10 +00001588 if (getLangOptions().CPlusPlus) {
1589 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001590 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001591
1592 // An out-of-line member function declaration must also be a
1593 // definition (C++ [dcl.meaning]p1).
Douglas Gregor6ed40e32008-12-23 21:05:05 +00001594 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() && !InvalidDecl) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001595 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1596 << D.getCXXScopeSpec().getRange();
1597 InvalidDecl = true;
1598 }
1599 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001600 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001601 // Check that there are no default arguments (C++ only).
1602 if (getLangOptions().CPlusPlus)
1603 CheckExtraCXXDefaultArguments(D);
1604
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001605 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001606 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1607 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001608 InvalidDecl = true;
1609 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001610
1611 VarDecl *NewVD;
1612 VarDecl::StorageClass SC;
1613 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001614 default: assert(0 && "Unknown storage class!");
1615 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1616 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1617 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1618 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1619 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1620 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001621 case DeclSpec::SCS_mutable:
1622 // mutable can only appear on non-static class members, so it's always
1623 // an error here
1624 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1625 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001626 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001627 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001628 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001629
1630 IdentifierInfo *II = Name.getAsIdentifierInfo();
1631 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001632 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1633 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001634 return 0;
1635 }
1636
Douglas Gregorbcbffc42009-01-07 00:43:41 +00001637 if (DC->isRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001638 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001639 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001640 D.getIdentifierLoc(), II,
1641 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001642 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001643 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001644 if (S->getFnParent() == 0) {
1645 // C99 6.9p2: The storage-class specifiers auto and register shall not
1646 // appear in the declaration specifiers in an external declaration.
1647 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001648 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001649 InvalidDecl = true;
1650 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001651 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001652 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1653 II, R, SC, LastDeclarator,
1654 // FIXME: Move to DeclGroup...
1655 D.getDeclSpec().getSourceRange().getBegin());
1656 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001657 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001658 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001659 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001660
Daniel Dunbara735ad82008-08-06 00:03:29 +00001661 // Handle GNU asm-label extension (encoded as an attribute).
1662 if (Expr *E = (Expr*) D.getAsmLabel()) {
1663 // The parser guarantees this is a string.
1664 StringLiteral *SE = cast<StringLiteral>(E);
1665 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1666 SE->getByteLength())));
1667 }
1668
Nate Begemanc8e89a82008-03-14 18:07:10 +00001669 // Emit an error if an address space was applied to decl with local storage.
1670 // This includes arrays of objects with address space qualifiers, but not
1671 // automatic variables that point to other address spaces.
1672 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001673 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1674 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1675 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001676 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001677 // Merge the decl with the existing one if appropriate. If the decl is
1678 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001679 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001680 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1681 // The user tried to define a non-static data member
1682 // out-of-line (C++ [dcl.meaning]p1).
1683 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1684 << D.getCXXScopeSpec().getRange();
1685 NewVD->Destroy(Context);
1686 return 0;
1687 }
1688
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 NewVD = MergeVarDecl(NewVD, PrevDecl);
1690 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001691
1692 if (D.getCXXScopeSpec().isSet()) {
1693 // No previous declaration in the qualifying scope.
1694 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1695 << Name << D.getCXXScopeSpec().getRange();
1696 InvalidDecl = true;
1697 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001698 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001699 New = NewVD;
1700 }
1701
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001702 // Set the lexical context. If the declarator has a C++ scope specifier, the
1703 // lexical context will be different from the semantic context.
1704 New->setLexicalDeclContext(CurContext);
1705
Reid Spencer5f016e22007-07-11 17:01:13 +00001706 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001707 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001708 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001709 // If any semantic error occurred, mark the decl as invalid.
1710 if (D.getInvalidType() || InvalidDecl)
1711 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001712
1713 return New;
1714}
1715
Steve Naroff6594a702008-10-27 11:34:16 +00001716void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001717 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1718 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001719}
1720
Eli Friedmanc594b322008-05-20 13:48:25 +00001721bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1722 switch (Init->getStmtClass()) {
1723 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001724 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001725 return true;
1726 case Expr::ParenExprClass: {
1727 const ParenExpr* PE = cast<ParenExpr>(Init);
1728 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1729 }
1730 case Expr::CompoundLiteralExprClass:
1731 return cast<CompoundLiteralExpr>(Init)->isFileScope();
Douglas Gregor1a49af92009-01-06 05:10:23 +00001732 case Expr::DeclRefExprClass:
1733 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001734 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001735 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1736 if (VD->hasGlobalStorage())
1737 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001738 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001739 return true;
1740 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001741 if (isa<FunctionDecl>(D))
1742 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001743 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001744 return true;
1745 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001746 case Expr::MemberExprClass: {
1747 const MemberExpr *M = cast<MemberExpr>(Init);
1748 if (M->isArrow())
1749 return CheckAddressConstantExpression(M->getBase());
1750 return CheckAddressConstantExpressionLValue(M->getBase());
1751 }
1752 case Expr::ArraySubscriptExprClass: {
1753 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1754 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1755 return CheckAddressConstantExpression(ASE->getBase()) ||
1756 CheckArithmeticConstantExpression(ASE->getIdx());
1757 }
1758 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001759 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001760 return false;
1761 case Expr::UnaryOperatorClass: {
1762 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1763
1764 // C99 6.6p9
1765 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001766 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001767
Steve Naroff6594a702008-10-27 11:34:16 +00001768 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001769 return true;
1770 }
1771 }
1772}
1773
1774bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1775 switch (Init->getStmtClass()) {
1776 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001777 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001778 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001779 case Expr::ParenExprClass:
1780 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001781 case Expr::StringLiteralClass:
1782 case Expr::ObjCStringLiteralClass:
1783 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001784 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001785 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001786 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1787 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1788 Builtin::BI__builtin___CFStringMakeConstantString)
1789 return false;
1790
Steve Naroff6594a702008-10-27 11:34:16 +00001791 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001792 return true;
1793
Eli Friedmanc594b322008-05-20 13:48:25 +00001794 case Expr::UnaryOperatorClass: {
1795 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1796
1797 // C99 6.6p9
1798 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1799 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1800
1801 if (Exp->getOpcode() == UnaryOperator::Extension)
1802 return CheckAddressConstantExpression(Exp->getSubExpr());
1803
Steve Naroff6594a702008-10-27 11:34:16 +00001804 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001805 return true;
1806 }
1807 case Expr::BinaryOperatorClass: {
1808 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1809 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1810
1811 Expr *PExp = Exp->getLHS();
1812 Expr *IExp = Exp->getRHS();
1813 if (IExp->getType()->isPointerType())
1814 std::swap(PExp, IExp);
1815
1816 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1817 return CheckAddressConstantExpression(PExp) ||
1818 CheckArithmeticConstantExpression(IExp);
1819 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001820 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001821 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001822 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001823 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1824 // Check for implicit promotion
1825 if (SubExpr->getType()->isFunctionType() ||
1826 SubExpr->getType()->isArrayType())
1827 return CheckAddressConstantExpressionLValue(SubExpr);
1828 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001829
1830 // Check for pointer->pointer cast
1831 if (SubExpr->getType()->isPointerType())
1832 return CheckAddressConstantExpression(SubExpr);
1833
Eli Friedmanc3f07642008-08-25 20:46:57 +00001834 if (SubExpr->getType()->isIntegralType()) {
1835 // Check for the special-case of a pointer->int->pointer cast;
1836 // this isn't standard, but some code requires it. See
1837 // PR2720 for an example.
1838 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1839 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1840 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1841 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1842 if (IntWidth >= PointerWidth) {
1843 return CheckAddressConstantExpression(SubCast->getSubExpr());
1844 }
1845 }
1846 }
1847 }
1848 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001849 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001850 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001851
Steve Naroff6594a702008-10-27 11:34:16 +00001852 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001853 return true;
1854 }
1855 case Expr::ConditionalOperatorClass: {
1856 // FIXME: Should we pedwarn here?
1857 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1858 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001859 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001860 return true;
1861 }
1862 if (CheckArithmeticConstantExpression(Exp->getCond()))
1863 return true;
1864 if (Exp->getLHS() &&
1865 CheckAddressConstantExpression(Exp->getLHS()))
1866 return true;
1867 return CheckAddressConstantExpression(Exp->getRHS());
1868 }
1869 case Expr::AddrLabelExprClass:
1870 return false;
1871 }
1872}
1873
Eli Friedman4caf0552008-06-09 05:05:07 +00001874static const Expr* FindExpressionBaseAddress(const Expr* E);
1875
1876static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1877 switch (E->getStmtClass()) {
1878 default:
1879 return E;
1880 case Expr::ParenExprClass: {
1881 const ParenExpr* PE = cast<ParenExpr>(E);
1882 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1883 }
1884 case Expr::MemberExprClass: {
1885 const MemberExpr *M = cast<MemberExpr>(E);
1886 if (M->isArrow())
1887 return FindExpressionBaseAddress(M->getBase());
1888 return FindExpressionBaseAddressLValue(M->getBase());
1889 }
1890 case Expr::ArraySubscriptExprClass: {
1891 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1892 return FindExpressionBaseAddress(ASE->getBase());
1893 }
1894 case Expr::UnaryOperatorClass: {
1895 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1896
1897 if (Exp->getOpcode() == UnaryOperator::Deref)
1898 return FindExpressionBaseAddress(Exp->getSubExpr());
1899
1900 return E;
1901 }
1902 }
1903}
1904
1905static const Expr* FindExpressionBaseAddress(const Expr* E) {
1906 switch (E->getStmtClass()) {
1907 default:
1908 return E;
1909 case Expr::ParenExprClass: {
1910 const ParenExpr* PE = cast<ParenExpr>(E);
1911 return FindExpressionBaseAddress(PE->getSubExpr());
1912 }
1913 case Expr::UnaryOperatorClass: {
1914 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1915
1916 // C99 6.6p9
1917 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1918 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1919
1920 if (Exp->getOpcode() == UnaryOperator::Extension)
1921 return FindExpressionBaseAddress(Exp->getSubExpr());
1922
1923 return E;
1924 }
1925 case Expr::BinaryOperatorClass: {
1926 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1927
1928 Expr *PExp = Exp->getLHS();
1929 Expr *IExp = Exp->getRHS();
1930 if (IExp->getType()->isPointerType())
1931 std::swap(PExp, IExp);
1932
1933 return FindExpressionBaseAddress(PExp);
1934 }
1935 case Expr::ImplicitCastExprClass: {
1936 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1937
1938 // Check for implicit promotion
1939 if (SubExpr->getType()->isFunctionType() ||
1940 SubExpr->getType()->isArrayType())
1941 return FindExpressionBaseAddressLValue(SubExpr);
1942
1943 // Check for pointer->pointer cast
1944 if (SubExpr->getType()->isPointerType())
1945 return FindExpressionBaseAddress(SubExpr);
1946
1947 // We assume that we have an arithmetic expression here;
1948 // if we don't, we'll figure it out later
1949 return 0;
1950 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001951 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001952 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1953
1954 // Check for pointer->pointer cast
1955 if (SubExpr->getType()->isPointerType())
1956 return FindExpressionBaseAddress(SubExpr);
1957
1958 // We assume that we have an arithmetic expression here;
1959 // if we don't, we'll figure it out later
1960 return 0;
1961 }
1962 }
1963}
1964
Anders Carlsson51fe9962008-11-22 21:04:56 +00001965bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001966 switch (Init->getStmtClass()) {
1967 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001968 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001969 return true;
1970 case Expr::ParenExprClass: {
1971 const ParenExpr* PE = cast<ParenExpr>(Init);
1972 return CheckArithmeticConstantExpression(PE->getSubExpr());
1973 }
1974 case Expr::FloatingLiteralClass:
1975 case Expr::IntegerLiteralClass:
1976 case Expr::CharacterLiteralClass:
1977 case Expr::ImaginaryLiteralClass:
1978 case Expr::TypesCompatibleExprClass:
1979 case Expr::CXXBoolLiteralExprClass:
1980 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001981 case Expr::CallExprClass:
1982 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001983 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001984
1985 // Allow any constant foldable calls to builtins.
1986 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001987 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001988
Steve Naroff6594a702008-10-27 11:34:16 +00001989 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001990 return true;
1991 }
Douglas Gregor1a49af92009-01-06 05:10:23 +00001992 case Expr::DeclRefExprClass:
1993 case Expr::QualifiedDeclRefExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001994 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1995 if (isa<EnumConstantDecl>(D))
1996 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001997 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001998 return true;
1999 }
2000 case Expr::CompoundLiteralExprClass:
2001 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
2002 // but vectors are allowed to be magic.
2003 if (Init->getType()->isVectorType())
2004 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002005 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002006 return true;
2007 case Expr::UnaryOperatorClass: {
2008 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
2009
2010 switch (Exp->getOpcode()) {
2011 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
2012 // See C99 6.6p3.
2013 default:
Steve Naroff6594a702008-10-27 11:34:16 +00002014 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002015 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002016 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00002017 if (Exp->getSubExpr()->getType()->isConstantSizeType())
2018 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00002019 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002020 return true;
2021 case UnaryOperator::Extension:
2022 case UnaryOperator::LNot:
2023 case UnaryOperator::Plus:
2024 case UnaryOperator::Minus:
2025 case UnaryOperator::Not:
2026 return CheckArithmeticConstantExpression(Exp->getSubExpr());
2027 }
2028 }
Sebastian Redl05189992008-11-11 17:56:53 +00002029 case Expr::SizeOfAlignOfExprClass: {
2030 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002031 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00002032 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00002033 return false;
2034 // alignof always evaluates to a constant.
2035 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00002036 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00002037 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002038 return true;
2039 }
2040 return false;
2041 }
2042 case Expr::BinaryOperatorClass: {
2043 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
2044
2045 if (Exp->getLHS()->getType()->isArithmeticType() &&
2046 Exp->getRHS()->getType()->isArithmeticType()) {
2047 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
2048 CheckArithmeticConstantExpression(Exp->getRHS());
2049 }
2050
Eli Friedman4caf0552008-06-09 05:05:07 +00002051 if (Exp->getLHS()->getType()->isPointerType() &&
2052 Exp->getRHS()->getType()->isPointerType()) {
2053 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
2054 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
2055
2056 // Only allow a null (constant integer) base; we could
2057 // allow some additional cases if necessary, but this
2058 // is sufficient to cover offsetof-like constructs.
2059 if (!LHSBase && !RHSBase) {
2060 return CheckAddressConstantExpression(Exp->getLHS()) ||
2061 CheckAddressConstantExpression(Exp->getRHS());
2062 }
2063 }
2064
Steve Naroff6594a702008-10-27 11:34:16 +00002065 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002066 return true;
2067 }
2068 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002069 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002070 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00002071 if (SubExpr->getType()->isArithmeticType())
2072 return CheckArithmeticConstantExpression(SubExpr);
2073
Eli Friedmanb529d832008-09-02 09:37:00 +00002074 if (SubExpr->getType()->isPointerType()) {
2075 const Expr* Base = FindExpressionBaseAddress(SubExpr);
2076 // If the pointer has a null base, this is an offsetof-like construct
2077 if (!Base)
2078 return CheckAddressConstantExpression(SubExpr);
2079 }
2080
Steve Naroff6594a702008-10-27 11:34:16 +00002081 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00002082 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00002083 }
2084 case Expr::ConditionalOperatorClass: {
2085 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00002086
2087 // If GNU extensions are disabled, we require all operands to be arithmetic
2088 // constant expressions.
2089 if (getLangOptions().NoExtensions) {
2090 return CheckArithmeticConstantExpression(Exp->getCond()) ||
2091 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
2092 CheckArithmeticConstantExpression(Exp->getRHS());
2093 }
2094
2095 // Otherwise, we have to emulate some of the behavior of fold here.
2096 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
2097 // because it can constant fold things away. To retain compatibility with
2098 // GCC code, we see if we can fold the condition to a constant (which we
2099 // should always be able to do in theory). If so, we only require the
2100 // specified arm of the conditional to be a constant. This is a horrible
2101 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002102 Expr::EvalResult EvalResult;
2103 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
2104 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002105 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00002106 // won't be able to either. Use it to emit the diagnostic though.
2107 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002108 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00002109 return Res;
2110 }
2111
2112 // Verify that the side following the condition is also a constant.
2113 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002114 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00002115 std::swap(TrueSide, FalseSide);
2116
2117 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00002118 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00002119
2120 // Okay, the evaluated side evaluates to a constant, so we accept this.
2121 // Check to see if the other side is obviously not a constant. If so,
2122 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00002123 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00002124 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002125 diag::ext_typecheck_expression_not_constant_but_accepted)
2126 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00002127 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00002128 }
2129 }
2130}
2131
2132bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002133 Expr::EvalResult Result;
2134
Nuno Lopes9a979c32008-07-07 16:46:50 +00002135 Init = Init->IgnoreParens();
2136
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002137 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
2138 return false;
2139
Eli Friedmanc594b322008-05-20 13:48:25 +00002140 // Look through CXXDefaultArgExprs; they have no meaning in this context.
2141 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
2142 return CheckForConstantInitializer(DAE->getExpr(), DclT);
2143
Nuno Lopes9a979c32008-07-07 16:46:50 +00002144 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
2145 return CheckForConstantInitializer(e->getInitializer(), DclT);
2146
Eli Friedmanc594b322008-05-20 13:48:25 +00002147 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
2148 unsigned numInits = Exp->getNumInits();
2149 for (unsigned i = 0; i < numInits; i++) {
2150 // FIXME: Need to get the type of the declaration for C++,
2151 // because it could be a reference?
2152 if (CheckForConstantInitializer(Exp->getInit(i),
2153 Exp->getInit(i)->getType()))
2154 return true;
2155 }
2156 return false;
2157 }
2158
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00002159 // FIXME: We can probably remove some of this code below, now that
2160 // Expr::Evaluate is doing the heavy lifting for scalars.
2161
Eli Friedmanc594b322008-05-20 13:48:25 +00002162 if (Init->isNullPointerConstant(Context))
2163 return false;
2164 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00002165 QualType InitTy = Context.getCanonicalType(Init->getType())
2166 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002167 if (InitTy == Context.BoolTy) {
2168 // Special handling for pointers implicitly cast to bool;
2169 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
2170 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
2171 Expr* SubE = ICE->getSubExpr();
2172 if (SubE->getType()->isPointerType() ||
2173 SubE->getType()->isArrayType() ||
2174 SubE->getType()->isFunctionType()) {
2175 return CheckAddressConstantExpression(Init);
2176 }
2177 }
2178 } else if (InitTy->isIntegralType()) {
2179 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00002180 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002181 SubE = CE->getSubExpr();
2182 // Special check for pointer cast to int; we allow as an extension
2183 // an address constant cast to an integer if the integer
2184 // is of an appropriate width (this sort of code is apparently used
2185 // in some places).
2186 // FIXME: Add pedwarn?
2187 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
2188 if (SubE && (SubE->getType()->isPointerType() ||
2189 SubE->getType()->isArrayType() ||
2190 SubE->getType()->isFunctionType())) {
2191 unsigned IntWidth = Context.getTypeSize(Init->getType());
2192 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
2193 if (IntWidth >= PointerWidth)
2194 return CheckAddressConstantExpression(Init);
2195 }
Eli Friedmanc594b322008-05-20 13:48:25 +00002196 }
2197
2198 return CheckArithmeticConstantExpression(Init);
2199 }
2200
2201 if (Init->getType()->isPointerType())
2202 return CheckAddressConstantExpression(Init);
2203
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00002204 // An array type at the top level that isn't an init-list must
2205 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00002206 if (Init->getType()->isArrayType())
2207 return false;
2208
Nuno Lopes73419bf2008-09-01 18:42:41 +00002209 if (Init->getType()->isFunctionType())
2210 return false;
2211
Steve Naroff8af6a452008-10-02 17:12:56 +00002212 // Allow block exprs at top level.
2213 if (Init->getType()->isBlockPointerType())
2214 return false;
2215
Steve Naroff6594a702008-10-27 11:34:16 +00002216 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002217 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002218}
2219
Sebastian Redl798d1192008-12-13 16:23:55 +00002220void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002221 AddInitializerToDecl(dcl, move(init), /*DirectInit=*/false);
2222}
2223
2224/// AddInitializerToDecl - Adds the initializer Init to the
2225/// declaration dcl. If DirectInit is true, this is C++ direct
2226/// initialization rather than copy initialization.
2227void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init, bool DirectInit) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002228 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002229 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002230 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002231
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002232 // If there is no declaration, there was an error parsing it. Just ignore
2233 // the initializer.
2234 if (RealDecl == 0) {
2235 delete Init;
2236 return;
2237 }
Steve Naroffbb204692007-09-12 14:07:44 +00002238
Steve Naroff410e3e22007-09-12 20:13:48 +00002239 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2240 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002241 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2242 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002243 RealDecl->setInvalidDecl();
2244 return;
2245 }
Steve Naroffbb204692007-09-12 14:07:44 +00002246 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002247 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002248 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002249 if (VDecl->isBlockVarDecl()) {
2250 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002251 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002252 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002253 VDecl->setInvalidDecl();
2254 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002255 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002256 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002257 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002258
2259 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2260 if (!getLangOptions().CPlusPlus) {
2261 if (SC == VarDecl::Static) // C99 6.7.8p4.
2262 CheckForConstantInitializer(Init, DclT);
2263 }
Steve Naroffbb204692007-09-12 14:07:44 +00002264 }
Steve Naroff248a7532008-04-15 22:42:06 +00002265 } else if (VDecl->isFileVarDecl()) {
2266 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002267 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002268 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002269 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Douglas Gregor09f41cf2009-01-14 15:45:31 +00002270 VDecl->getDeclName(), DirectInit))
Steve Naroff248a7532008-04-15 22:42:06 +00002271 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002272
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002273 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2274 if (!getLangOptions().CPlusPlus) {
2275 // C99 6.7.8p4. All file scoped initializers need to be constant.
2276 CheckForConstantInitializer(Init, DclT);
2277 }
Steve Naroffbb204692007-09-12 14:07:44 +00002278 }
2279 // If the type changed, it means we had an incomplete type that was
2280 // completed by the initializer. For example:
2281 // int ary[] = { 1, 3, 5 };
2282 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002283 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002284 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002285 Init->setType(DclT);
2286 }
Steve Naroffbb204692007-09-12 14:07:44 +00002287
2288 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002289 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002290 return;
2291}
2292
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002293void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2294 Decl *RealDecl = static_cast<Decl *>(dcl);
2295
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002296 // If there is no declaration, there was an error parsing it. Just ignore it.
2297 if (RealDecl == 0)
2298 return;
2299
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002300 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2301 QualType Type = Var->getType();
2302 // C++ [dcl.init.ref]p3:
2303 // The initializer can be omitted for a reference only in a
2304 // parameter declaration (8.3.5), in the declaration of a
2305 // function return type, in the declaration of a class member
2306 // within its class declaration (9.2), and where the extern
2307 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002308 if (Type->isReferenceType() &&
2309 Var->getStorageClass() != VarDecl::Extern &&
2310 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002311 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002312 << Var->getDeclName()
2313 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002314 Var->setInvalidDecl();
2315 return;
2316 }
2317
2318 // C++ [dcl.init]p9:
2319 //
2320 // If no initializer is specified for an object, and the object
2321 // is of (possibly cv-qualified) non-POD class type (or array
2322 // thereof), the object shall be default-initialized; if the
2323 // object is of const-qualified type, the underlying class type
2324 // shall have a user-declared default constructor.
2325 if (getLangOptions().CPlusPlus) {
2326 QualType InitType = Type;
2327 if (const ArrayType *Array = Context.getAsArrayType(Type))
2328 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002329 if (Var->getStorageClass() != VarDecl::Extern &&
2330 Var->getStorageClass() != VarDecl::PrivateExtern &&
2331 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002332 const CXXConstructorDecl *Constructor
2333 = PerformInitializationByConstructor(InitType, 0, 0,
2334 Var->getLocation(),
2335 SourceRange(Var->getLocation(),
2336 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002337 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002338 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002339 if (!Constructor)
2340 Var->setInvalidDecl();
2341 }
2342 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002343
Douglas Gregor818ce482008-10-29 13:50:18 +00002344#if 0
2345 // FIXME: Temporarily disabled because we are not properly parsing
2346 // linkage specifications on declarations, e.g.,
2347 //
2348 // extern "C" const CGPoint CGPointerZero;
2349 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002350 // C++ [dcl.init]p9:
2351 //
2352 // If no initializer is specified for an object, and the
2353 // object is of (possibly cv-qualified) non-POD class type (or
2354 // array thereof), the object shall be default-initialized; if
2355 // the object is of const-qualified type, the underlying class
2356 // type shall have a user-declared default
2357 // constructor. Otherwise, if no initializer is specified for
2358 // an object, the object and its subobjects, if any, have an
2359 // indeterminate initial value; if the object or any of its
2360 // subobjects are of const-qualified type, the program is
2361 // ill-formed.
2362 //
2363 // This isn't technically an error in C, so we don't diagnose it.
2364 //
2365 // FIXME: Actually perform the POD/user-defined default
2366 // constructor check.
2367 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002368 Context.getCanonicalType(Type).isConstQualified() &&
2369 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002370 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2371 << Var->getName()
2372 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002373#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002374 }
2375}
2376
Reid Spencer5f016e22007-07-11 17:01:13 +00002377/// The declarators are chained together backwards, reverse the list.
2378Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2379 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002380 Decl *GroupDecl = static_cast<Decl*>(group);
2381 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002382 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002383
2384 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2385 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002386 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002387 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002388 else { // reverse the list.
2389 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002390 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002391 Group->setNextDeclarator(NewGroup);
2392 NewGroup = Group;
2393 Group = Next;
2394 }
2395 }
2396 // Perform semantic analysis that depends on having fully processed both
2397 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002398 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002399 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2400 if (!IDecl)
2401 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002402 QualType T = IDecl->getType();
2403
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002404 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002405 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002406
2407 // FIXME: This won't give the correct result for
2408 // int a[10][n];
2409 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002410 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002411 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2412 SizeRange;
2413
Eli Friedmanc5773c42008-02-15 18:16:39 +00002414 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002415 } else {
2416 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2417 // static storage duration, it shall not have a variable length array.
2418 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002419 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2420 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002421 IDecl->setInvalidDecl();
2422 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002423 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2424 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002425 IDecl->setInvalidDecl();
2426 }
2427 }
2428 } else if (T->isVariablyModifiedType()) {
2429 if (IDecl->isFileVarDecl()) {
2430 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2431 IDecl->setInvalidDecl();
2432 } else {
2433 if (IDecl->getStorageClass() == VarDecl::Extern) {
2434 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2435 IDecl->setInvalidDecl();
2436 }
Steve Naroffbb204692007-09-12 14:07:44 +00002437 }
2438 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002439
Steve Naroffbb204692007-09-12 14:07:44 +00002440 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2441 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002442 if (IDecl->isBlockVarDecl() &&
2443 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002444 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002445 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002446 IDecl->setInvalidDecl();
2447 }
2448 }
2449 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2450 // object that has file scope without an initializer, and without a
2451 // storage-class specifier or with the storage-class specifier "static",
2452 // constitutes a tentative definition. Note: A tentative definition with
2453 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002454 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002455 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002456 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2457 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002458 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002459 // C99 6.9.2p3: If the declaration of an identifier for an object is
2460 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2461 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002462 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002463 IDecl->setInvalidDecl();
2464 }
2465 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002466 if (IDecl->isFileVarDecl())
2467 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002468 }
2469 return NewGroup;
2470}
Steve Naroffe1223f72007-08-28 03:03:08 +00002471
Chris Lattner04421082008-04-08 04:40:51 +00002472/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2473/// to introduce parameters into function prototype scope.
2474Sema::DeclTy *
2475Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002476 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002477
Chris Lattner04421082008-04-08 04:40:51 +00002478 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002479 VarDecl::StorageClass StorageClass = VarDecl::None;
2480 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2481 StorageClass = VarDecl::Register;
2482 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002483 Diag(DS.getStorageClassSpecLoc(),
2484 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002485 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002486 }
2487 if (DS.isThreadSpecified()) {
2488 Diag(DS.getThreadSpecLoc(),
2489 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002490 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002491 }
2492
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002493 // Check that there are no default arguments inside the type of this
2494 // parameter (C++ only).
2495 if (getLangOptions().CPlusPlus)
2496 CheckExtraCXXDefaultArguments(D);
2497
Chris Lattner04421082008-04-08 04:40:51 +00002498 // In this context, we *do not* check D.getInvalidType(). If the declarator
2499 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2500 // though it will not reflect the user specified type.
2501 QualType parmDeclType = GetTypeForDeclarator(D, S);
2502
2503 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2504
Reid Spencer5f016e22007-07-11 17:01:13 +00002505 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2506 // Can this happen for params? We already checked that they don't conflict
2507 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002508 IdentifierInfo *II = D.getIdentifier();
2509 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002510 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002511 // Maybe we will complain about the shadowed template parameter.
2512 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2513 // Just pretend that we didn't see the previous declaration.
2514 PrevDecl = 0;
2515 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002516 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002517
2518 // Recover by removing the name
2519 II = 0;
2520 D.SetIdentifier(0, D.getIdentifierLoc());
2521 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002522 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002523
2524 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2525 // Doing the promotion here has a win and a loss. The win is the type for
2526 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2527 // code generator). The loss is the orginal type isn't preserved. For example:
2528 //
2529 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2530 // int blockvardecl[5];
2531 // sizeof(parmvardecl); // size == 4
2532 // sizeof(blockvardecl); // size == 20
2533 // }
2534 //
2535 // For expressions, all implicit conversions are captured using the
2536 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2537 //
2538 // FIXME: If a source translation tool needs to see the original type, then
2539 // we need to consider storing both types (in ParmVarDecl)...
2540 //
Chris Lattnere6327742008-04-02 05:18:44 +00002541 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002542 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002543 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002544 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002545 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002546
Chris Lattner04421082008-04-08 04:40:51 +00002547 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2548 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002549 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002550 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002551
Chris Lattner04421082008-04-08 04:40:51 +00002552 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002553 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002554
Douglas Gregor584049d2008-12-15 23:53:10 +00002555 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2556 if (D.getCXXScopeSpec().isSet()) {
2557 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2558 << D.getCXXScopeSpec().getRange();
2559 New->setInvalidDecl();
2560 }
2561
Douglas Gregor44b43212008-12-11 16:49:14 +00002562 // Add the parameter declaration into this scope.
2563 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002564 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002565 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002566
Chris Lattner3ff30c82008-06-29 00:02:00 +00002567 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002568 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002569
Reid Spencer5f016e22007-07-11 17:01:13 +00002570}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002571
Chris Lattnerb652cea2007-10-09 17:14:05 +00002572Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002573 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002574 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2575 "Not a function declarator!");
2576 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002577
Reid Spencer5f016e22007-07-11 17:01:13 +00002578 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2579 // for a K&R function.
2580 if (!FTI.hasPrototype) {
2581 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002582 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002583 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2584 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002585 // Implicitly declare the argument as type 'int' for lack of a better
2586 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002587 DeclSpec DS;
2588 const char* PrevSpec; // unused
2589 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2590 PrevSpec);
2591 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2592 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2593 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002594 }
2595 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002596 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002597 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002598 }
2599
Douglas Gregor584049d2008-12-15 23:53:10 +00002600 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002601
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002602 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002603 ActOnDeclarator(ParentScope, D, 0,
2604 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002605}
2606
2607Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2608 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002609 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002610
2611 // See if this is a redefinition.
2612 const FunctionDecl *Definition;
2613 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002614 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002615 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002616 }
2617
Douglas Gregor44b43212008-12-11 16:49:14 +00002618 PushDeclContext(FnBodyScope, FD);
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002619
Chris Lattner04421082008-04-08 04:40:51 +00002620 // Check the validity of our function parameters
2621 CheckParmsForFunctionDef(FD);
2622
2623 // Introduce our parameters into the function scope
2624 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2625 ParmVarDecl *Param = FD->getParamDecl(p);
Douglas Gregora8cc8ce2009-01-09 18:51:29 +00002626 Param->setOwningFunction(FD);
2627
Chris Lattner04421082008-04-08 04:40:51 +00002628 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002629 if (Param->getIdentifier())
2630 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 }
Chris Lattner04421082008-04-08 04:40:51 +00002632
Anton Korobeynikov2f402702008-12-26 00:52:02 +00002633 // Checking attributes of current function definition
2634 // dllimport attribute.
2635 if (FD->getAttr<DLLImportAttr>() && (!FD->getAttr<DLLExportAttr>())) {
2636 // dllimport attribute cannot be applied to definition.
2637 if (!(FD->getAttr<DLLImportAttr>())->isInherited()) {
2638 Diag(FD->getLocation(),
2639 diag::err_attribute_can_be_applied_only_to_symbol_declaration)
2640 << "dllimport";
2641 FD->setInvalidDecl();
2642 return FD;
2643 } else {
2644 // If a symbol previously declared dllimport is later defined, the
2645 // attribute is ignored in subsequent references, and a warning is
2646 // emitted.
2647 Diag(FD->getLocation(),
2648 diag::warn_redeclaration_without_attribute_prev_attribute_ignored)
2649 << FD->getNameAsCString() << "dllimport";
2650 }
2651 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002652 return FD;
2653}
2654
Sebastian Redl798d1192008-12-13 16:23:55 +00002655Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002656 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002657 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002658 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002659 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002660 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002661 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002662 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002663 } else
2664 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002665 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002666 // Verify and clean out per-function state.
2667
2668 // Check goto/label use.
2669 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2670 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2671 // Verify that we have no forward references left. If so, there was a goto
2672 // or address of a label taken, but no definition of it. Label fwd
2673 // definitions are indicated with a null substmt.
2674 if (I->second->getSubStmt() == 0) {
2675 LabelStmt *L = I->second;
2676 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002677 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002678
2679 // At this point, we have gotos that use the bogus label. Stitch it into
2680 // the function body so that they aren't leaked and that the AST is well
2681 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002682 if (Body) {
2683 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002684 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002685 } else {
2686 // The whole function wasn't parsed correctly, just delete this.
2687 delete L;
2688 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 }
2690 }
2691 LabelMap.clear();
2692
Steve Naroffd6d054d2007-11-11 23:20:51 +00002693 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002694}
2695
Reid Spencer5f016e22007-07-11 17:01:13 +00002696/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2697/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002698ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2699 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002700 // Extension in C99. Legal in C90, but warn about it.
2701 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002702 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002703 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002704 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002705
2706 // FIXME: handle stuff like:
2707 // void foo() { extern float X(); }
2708 // void bar() { X(); } <-- implicit decl for X in another scope.
2709
2710 // Set a Declarator for the implicit definition: int foo();
2711 const char *Dummy;
2712 DeclSpec DS;
2713 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2714 Error = Error; // Silence warning.
2715 assert(!Error && "Error setting up implicit decl!");
2716 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002717 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002718 D.SetIdentifier(&II, Loc);
2719
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002720 // Insert this function into translation-unit scope.
2721
2722 DeclContext *PrevDC = CurContext;
2723 CurContext = Context.getTranslationUnitDecl();
2724
Steve Naroffe2ef8152008-04-04 14:32:09 +00002725 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002726 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002727 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002728
2729 CurContext = PrevDC;
2730
Steve Naroffe2ef8152008-04-04 14:32:09 +00002731 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002732}
2733
2734
Chris Lattner41af0932007-11-14 06:34:38 +00002735TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002736 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002737 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002738 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002739
2740 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002741 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2742 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002743 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002744 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002745 if (D.getInvalidType())
2746 NewTD->setInvalidDecl();
2747 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002748}
2749
Steve Naroff08d92e42007-09-15 18:49:24 +00002750/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002751/// former case, Name will be non-null. In the later case, Name will be null.
2752/// TagType indicates what kind of tag this is. TK indicates whether this is a
2753/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002754Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002755 SourceLocation KWLoc, const CXXScopeSpec &SS,
2756 IdentifierInfo *Name, SourceLocation NameLoc,
Douglas Gregorc4b4e7b2008-12-24 02:52:09 +00002757 AttributeList *Attr,
2758 MultiTemplateParamsArg TemplateParameterLists) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002759 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 assert((Name != 0 || TK == TK_Definition) &&
2761 "Nameless record must be a definition!");
2762
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002763 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 switch (TagType) {
2765 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002766 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2767 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2768 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2769 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002770 }
2771
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002772 DeclContext *SearchDC = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002773 DeclContext *DC = CurContext;
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002774 DeclContext *LexicalContext = CurContext;
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002775 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002776
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002777 if (Name && SS.isNotEmpty()) {
2778 // We have a nested-name tag ('struct foo::bar').
2779
2780 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002781 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002782 Name = 0;
2783 goto CreateNewDecl;
2784 }
2785
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002786 DC = static_cast<DeclContext*>(SS.getScopeRep());
2787 // Look-up name inside 'foo::'.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002788 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC)
2789 .getAsDecl());
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002790
2791 // A tag 'foo::bar' must already exist.
2792 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002793 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002794 Name = 0;
2795 goto CreateNewDecl;
2796 }
2797 } else {
2798 // If this is a named struct, check to see if there was a previous forward
2799 // declaration or definition.
2800 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Douglas Gregoreb11cd02009-01-14 22:20:51 +00002801 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S)
2802 .getAsDecl());
Douglas Gregor72de6672009-01-08 20:45:30 +00002803
2804 if (!getLangOptions().CPlusPlus && TK != TK_Reference) {
2805 // FIXME: This makes sure that we ignore the contexts associated
2806 // with C structs, unions, and enums when looking for a matching
2807 // tag declaration or definition. See the similar lookup tweak
2808 // in Sema::LookupDecl; is there a better way to deal with this?
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002809 while (isa<RecordDecl>(SearchDC) || isa<EnumDecl>(SearchDC))
2810 SearchDC = SearchDC->getParent();
Douglas Gregor72de6672009-01-08 20:45:30 +00002811 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002812 }
2813
Douglas Gregorf57172b2008-12-08 18:40:42 +00002814 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002815 // Maybe we will complain about the shadowed template parameter.
2816 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2817 // Just pretend that we didn't see the previous declaration.
2818 PrevDecl = 0;
2819 }
2820
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002821 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002822 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2823 "unexpected Decl type");
2824 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002825 // If this is a use of a previous tag, or if the tag is already declared
2826 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002827 // rementions the tag), reuse the decl.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002828 if (TK == TK_Reference || isDeclInScope(PrevDecl, SearchDC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002829 // Make sure that this wasn't declared as an enum and now used as a
2830 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002831 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002832 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002833 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002834 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002835 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002836 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002837 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002838 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002839
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002840 // FIXME: In the future, return a variant or some other clue
2841 // for the consumer of this Decl to know it doesn't own it.
2842 // For our current ASTs this shouldn't be a problem, but will
2843 // need to be changed with DeclGroups.
2844 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002845 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002846
2847 // Diagnose attempts to redefine a tag.
2848 if (TK == TK_Definition) {
2849 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2850 Diag(NameLoc, diag::err_redefinition) << Name;
2851 Diag(Def->getLocation(), diag::note_previous_definition);
2852 // If this is a redefinition, recover by making this struct be
2853 // anonymous, which will make any later references get the previous
2854 // definition.
2855 Name = 0;
2856 PrevDecl = 0;
2857 }
2858 // Okay, this is definition of a previously declared or referenced
2859 // tag PrevDecl. We're going to create a new Decl for it.
2860 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002861 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002862 // If we get here we have (another) forward declaration or we
2863 // have a definition. Just create a new decl.
2864 } else {
2865 // If we get here, this is a definition of a new tag type in a nested
2866 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2867 // new decl/type. We set PrevDecl to NULL so that the entities
2868 // have distinct types.
2869 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002870 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002871 // If we get here, we're going to create a new Decl. If PrevDecl
2872 // is non-NULL, it's a definition of the tag declared by
2873 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002874 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002875 // PrevDecl is a namespace.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002876 if (isDeclInScope(PrevDecl, SearchDC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002877 // The tag name clashes with a namespace name, issue an error and
2878 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002879 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002880 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002881 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002882 PrevDecl = 0;
2883 } else {
2884 // The existing declaration isn't relevant to us; we're in a
2885 // new scope, so clear out the previous declaration.
2886 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002887 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002888 }
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002889 } else if (TK == TK_Reference && SS.isEmpty() && Name &&
2890 (Kind != TagDecl::TK_enum)) {
2891 // C++ [basic.scope.pdecl]p5:
2892 // -- for an elaborated-type-specifier of the form
2893 //
2894 // class-key identifier
2895 //
2896 // if the elaborated-type-specifier is used in the
2897 // decl-specifier-seq or parameter-declaration-clause of a
2898 // function defined in namespace scope, the identifier is
2899 // declared as a class-name in the namespace that contains
2900 // the declaration; otherwise, except as a friend
2901 // declaration, the identifier is declared in the smallest
2902 // non-class, non-function-prototype scope that contains the
2903 // declaration.
2904 //
2905 // C99 6.7.2.3p8 has a similar (but not identical!) provision for
2906 // C structs and unions.
2907
2908 // Find the context where we'll be declaring the tag.
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002909 // FIXME: We would like to maintain the current DeclContext as the
2910 // lexical context,
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002911 while (DC->isRecord())
2912 DC = DC->getParent();
2913 LexicalContext = DC;
2914
2915 // Find the scope where we'll be declaring the tag.
2916 while (S->isClassScope() ||
2917 (getLangOptions().CPlusPlus && S->isFunctionPrototypeScope()) ||
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00002918 ((S->getFlags() & Scope::DeclScope) == 0) ||
2919 (S->getEntity() &&
2920 ((DeclContext *)S->getEntity())->isTransparentContext()))
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002921 S = S->getParent();
Reid Spencer5f016e22007-07-11 17:01:13 +00002922 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002923
Chris Lattnercc98eac2008-12-17 07:13:27 +00002924CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002925
2926 // If there is an identifier, use the location of the identifier as the
2927 // location of the decl, otherwise use the location of the struct/union
2928 // keyword.
2929 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2930
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002931 // Otherwise, create a new declaration. If there is a previous
2932 // declaration of the same entity, the two will be linked via
2933 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 TagDecl *New;
Douglas Gregorbcbffc42009-01-07 00:43:41 +00002935
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002936 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2938 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002939 New = EnumDecl::Create(Context, DC, Loc, Name,
2940 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002941 // If this is an undefined enum, warn.
2942 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002943 } else {
2944 // struct/union/class
2945
Reid Spencer5f016e22007-07-11 17:01:13 +00002946 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2947 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002948 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002949 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002950 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2951 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002952 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002953 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2954 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002955 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002956
2957 if (Kind != TagDecl::TK_enum) {
2958 // Handle #pragma pack: if the #pragma pack stack has non-default
2959 // alignment, make up a packed attribute for this decl. These
2960 // attributes are checked when the ASTContext lays out the
2961 // structure.
2962 //
2963 // It is important for implementing the correct semantics that this
2964 // happen here (in act on tag decl). The #pragma pack stack is
2965 // maintained as a result of parser callbacks which can occur at
2966 // many points during the parsing of a struct declaration (because
2967 // the #pragma tokens are effectively skipped over during the
2968 // parsing of the struct).
2969 if (unsigned Alignment = PackContext.getAlignment())
2970 New->addAttr(new PackedAttr(Alignment * 8));
2971 }
2972
2973 if (Attr)
2974 ProcessDeclAttributeList(New, Attr);
2975
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002976 // If we're declaring or defining
2977 if (Name && S->isFunctionPrototypeScope() && !getLangOptions().CPlusPlus)
2978 Diag(Loc, diag::warn_decl_in_param_list) << Context.getTagDeclType(New);
2979
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002980 // Set the lexical context. If the tag has a C++ scope specifier, the
2981 // lexical context will be different from the semantic context.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002982 New->setLexicalDeclContext(LexicalContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002983
2984 // If this has an identifier, add it to the scope stack.
2985 if (Name) {
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00002986 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00002987
2988 // Add it to the decl chain.
Douglas Gregor3218c4b2009-01-09 22:42:13 +00002989 if (LexicalContext != CurContext) {
2990 // FIXME: PushOnScopeChains should not rely on CurContext!
2991 DeclContext *OldContext = CurContext;
2992 CurContext = LexicalContext;
2993 PushOnScopeChains(New, S);
2994 CurContext = OldContext;
2995 } else
2996 PushOnScopeChains(New, S);
Douglas Gregor4920f1f2009-01-12 22:49:06 +00002997 } else {
Douglas Gregor482b77d2009-01-12 23:27:07 +00002998 LexicalContext->addDecl(New);
Reid Spencer5f016e22007-07-11 17:01:13 +00002999 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00003000
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 return New;
3002}
3003
Douglas Gregor72de6672009-01-08 20:45:30 +00003004void Sema::ActOnTagStartDefinition(Scope *S, DeclTy *TagD) {
3005 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3006
3007 // Enter the tag context.
3008 PushDeclContext(S, Tag);
3009
3010 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Tag)) {
3011 FieldCollector->StartClass();
3012
3013 if (Record->getIdentifier()) {
3014 // C++ [class]p2:
3015 // [...] The class-name is also inserted into the scope of the
3016 // class itself; this is known as the injected-class-name. For
3017 // purposes of access checking, the injected-class-name is treated
3018 // as if it were a public member name.
3019 RecordDecl *InjectedClassName
3020 = CXXRecordDecl::Create(Context, Record->getTagKind(),
3021 CurContext, Record->getLocation(),
3022 Record->getIdentifier(), Record);
3023 InjectedClassName->setImplicit();
3024 PushOnScopeChains(InjectedClassName, S);
3025 }
3026 }
3027}
3028
3029void Sema::ActOnTagFinishDefinition(Scope *S, DeclTy *TagD) {
3030 TagDecl *Tag = cast<TagDecl>((Decl *)TagD);
3031
3032 if (isa<CXXRecordDecl>(Tag))
3033 FieldCollector->FinishClass();
3034
3035 // Exit this scope of this tag's definition.
3036 PopDeclContext();
3037
3038 // Notify the consumer that we've defined a tag.
3039 Consumer.HandleTagDeclDefinition(Tag);
3040}
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00003041
Chris Lattner1d353ba2008-11-12 21:17:48 +00003042/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
3043/// types into constant array types in certain situations which would otherwise
3044/// be errors (for GCC compatibility).
3045static QualType TryToFixInvalidVariablyModifiedType(QualType T,
3046 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00003047 // This method tries to turn a variable array into a constant
3048 // array even when the size isn't an ICE. This is necessary
3049 // for compatibility with code that depends on gcc's buggy
3050 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00003051 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
3052 if (!VLATy) return QualType();
3053
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003054 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00003055 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003056 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00003057 return QualType();
3058
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00003059 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
3060 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00003061 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
3062 return Context.getConstantArrayType(VLATy->getElementType(),
3063 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003064 return QualType();
3065}
3066
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003067bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00003068 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003069 // FIXME: 6.7.2.1p4 - verify the field type.
3070
3071 llvm::APSInt Value;
3072 if (VerifyIntegerConstantExpression(BitWidth, &Value))
3073 return true;
3074
Chris Lattnercd087072008-12-12 04:56:04 +00003075 // Zero-width bitfield is ok for anonymous field.
3076 if (Value == 0 && FieldName)
3077 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
3078
3079 if (Value.isNegative())
3080 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003081
3082 uint64_t TypeSize = Context.getTypeSize(FieldTy);
3083 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00003084 if (TypeSize && Value.getZExtValue() > TypeSize)
3085 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
3086 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003087
3088 return false;
3089}
3090
Steve Naroff08d92e42007-09-15 18:49:24 +00003091/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00003092/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00003093Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00003094 SourceLocation DeclStart,
3095 Declarator &D, ExprTy *BitfieldWidth) {
3096 IdentifierInfo *II = D.getIdentifier();
3097 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00003099 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 if (II) Loc = D.getIdentifierLoc();
3101
3102 // FIXME: Unnamed fields can be handled in various different ways, for
3103 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00003104
Reid Spencer5f016e22007-07-11 17:01:13 +00003105 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00003106 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3107 bool InvalidDecl = false;
Sebastian Redl64b45f72009-01-05 20:52:13 +00003108
Reid Spencer5f016e22007-07-11 17:01:13 +00003109 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3110 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00003111 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00003112 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003113 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003114 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00003115 T = FixedTy;
3116 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00003117 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00003118 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00003119 InvalidDecl = true;
3120 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003121 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003122
3123 if (BitWidth) {
3124 if (VerifyBitField(Loc, II, T, BitWidth))
3125 InvalidDecl = true;
3126 } else {
3127 // Not a bitfield.
3128
3129 // validate II.
3130
3131 }
3132
Reid Spencer5f016e22007-07-11 17:01:13 +00003133 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00003134 FieldDecl *NewFD;
3135
Douglas Gregor44b43212008-12-11 16:49:14 +00003136 NewFD = FieldDecl::Create(Context, Record,
3137 Loc, II, T, BitWidth,
3138 D.getDeclSpec().getStorageClassSpec() ==
3139 DeclSpec::SCS_mutable,
3140 /*PrevDecl=*/0);
3141
Douglas Gregor72de6672009-01-08 20:45:30 +00003142 if (II) {
3143 Decl *PrevDecl
3144 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3145 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3146 && !isa<TagDecl>(PrevDecl)) {
3147 Diag(Loc, diag::err_duplicate_member) << II;
3148 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3149 NewFD->setInvalidDecl();
3150 Record->setInvalidDecl();
3151 }
3152 }
3153
Sebastian Redl64b45f72009-01-05 20:52:13 +00003154 if (getLangOptions().CPlusPlus) {
Douglas Gregor72b505b2008-12-16 21:30:33 +00003155 CheckExtraCXXDefaultArguments(D);
Sebastian Redl64b45f72009-01-05 20:52:13 +00003156 if (!T->isPODType())
3157 cast<CXXRecordDecl>(Record)->setPOD(false);
3158 }
Douglas Gregor72b505b2008-12-16 21:30:33 +00003159
Chris Lattner3ff30c82008-06-29 00:02:00 +00003160 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00003161
Steve Naroff5912a352007-08-28 20:14:24 +00003162 if (D.getInvalidType() || InvalidDecl)
3163 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00003164
Douglas Gregor72de6672009-01-08 20:45:30 +00003165 if (II) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003166 PushOnScopeChains(NewFD, S);
Douglas Gregor72de6672009-01-08 20:45:30 +00003167 } else
Douglas Gregor482b77d2009-01-12 23:27:07 +00003168 Record->addDecl(NewFD);
Douglas Gregor44b43212008-12-11 16:49:14 +00003169
Steve Naroff5912a352007-08-28 20:14:24 +00003170 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00003171}
3172
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003173/// TranslateIvarVisibility - Translate visibility from a token ID to an
3174/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003175static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00003176TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00003177 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00003178 default: assert(0 && "Unknown visitibility kind");
3179 case tok::objc_private: return ObjCIvarDecl::Private;
3180 case tok::objc_public: return ObjCIvarDecl::Public;
3181 case tok::objc_protected: return ObjCIvarDecl::Protected;
3182 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00003183 }
3184}
3185
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003186/// ActOnIvar - Each ivar field of an objective-c class is passed into this
3187/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003188Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00003189 SourceLocation DeclStart,
3190 Declarator &D, ExprTy *BitfieldWidth,
3191 tok::ObjCKeywordKind Visibility) {
Douglas Gregor72de6672009-01-08 20:45:30 +00003192
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003193 IdentifierInfo *II = D.getIdentifier();
3194 Expr *BitWidth = (Expr*)BitfieldWidth;
3195 SourceLocation Loc = DeclStart;
3196 if (II) Loc = D.getIdentifierLoc();
3197
3198 // FIXME: Unnamed fields can be handled in various different ways, for
3199 // example, unnamed unions inject all members into the struct namespace!
3200
Anders Carlsson9f1e5722008-12-06 20:33:04 +00003201 QualType T = GetTypeForDeclarator(D, S);
3202 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
3203 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003204
3205 if (BitWidth) {
3206 // TODO: Validate.
3207 //printf("WARNING: BITFIELDS IGNORED!\n");
3208
3209 // 6.7.2.1p3
3210 // 6.7.2.1p4
3211
3212 } else {
3213 // Not a bitfield.
3214
3215 // validate II.
3216
3217 }
3218
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003219 // C99 6.7.2.1p8: A member of a structure or union may have any type other
3220 // than a variably modified type.
3221 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00003222 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003223 InvalidDecl = true;
3224 }
3225
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003226 // Get the visibility (access control) for this ivar.
3227 ObjCIvarDecl::AccessControl ac =
3228 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
3229 : ObjCIvarDecl::None;
3230
3231 // Construct the decl.
3232 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00003233 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003234
Douglas Gregor72de6672009-01-08 20:45:30 +00003235 if (II) {
3236 Decl *PrevDecl
3237 = LookupDecl(II, Decl::IDNS_Member, S, 0, false, false, false);
3238 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)
3239 && !isa<TagDecl>(PrevDecl)) {
3240 Diag(Loc, diag::err_duplicate_member) << II;
3241 Diag(PrevDecl->getLocation(), diag::note_previous_declaration);
3242 NewID->setInvalidDecl();
3243 }
3244 }
3245
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003246 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00003247 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003248
3249 if (D.getInvalidType() || InvalidDecl)
3250 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00003251
Douglas Gregor72de6672009-01-08 20:45:30 +00003252 if (II) {
3253 // FIXME: When interfaces are DeclContexts, we'll need to add
3254 // these to the interface.
3255 S->AddDecl(NewID);
3256 IdResolver.AddDecl(NewID);
3257 }
3258
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00003259 return NewID;
3260}
3261
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00003262void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003263 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00003264 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00003265 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00003266 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00003267 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
3268 assert(EnclosingDecl && "missing record or interface decl");
3269 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
3270
Douglas Gregor72de6672009-01-08 20:45:30 +00003271 if (Record) {
3272 QualType RecordType = Context.getTypeDeclType(Record);
3273 if (RecordType->getAsRecordType()->getDecl()->isDefinition()) {
3274 RecordDecl *Def = RecordType->getAsRecordType()->getDecl();
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003275 // Diagnose code like:
3276 // struct S { struct S {} X; };
3277 // We discover this when we complete the outer S. Reject and ignore the
3278 // outer S.
Douglas Gregor72de6672009-01-08 20:45:30 +00003279 Diag(Def->getLocation(), diag::err_nested_redefinition)
3280 << Def->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003281 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003282 Record->setInvalidDecl();
3283 return;
3284 }
Douglas Gregor72de6672009-01-08 20:45:30 +00003285 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00003286
Reid Spencer5f016e22007-07-11 17:01:13 +00003287 // Verify that all the fields are okay.
3288 unsigned NumNamedMembers = 0;
3289 llvm::SmallVector<FieldDecl*, 32> RecFields;
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003290
Reid Spencer5f016e22007-07-11 17:01:13 +00003291 for (unsigned i = 0; i != NumFields; ++i) {
Steve Naroff74216642007-09-14 22:20:54 +00003292 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
3293 assert(FD && "missing field decl");
3294
Reid Spencer5f016e22007-07-11 17:01:13 +00003295 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00003296 Type *FDTy = FD->getType().getTypePtr();
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003297
Douglas Gregor72de6672009-01-08 20:45:30 +00003298 if (!FD->isAnonymousStructOrUnion()) {
Douglas Gregor6b3945f2009-01-07 19:46:03 +00003299 // Remember all fields written by the user.
3300 RecFields.push_back(FD);
3301 }
Steve Narofff13271f2007-09-14 23:09:53 +00003302
Reid Spencer5f016e22007-07-11 17:01:13 +00003303 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00003304 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003305 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003306 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003307 FD->setInvalidDecl();
3308 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003309 continue;
3310 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003311 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
3312 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003313 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003314 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003315 FD->setInvalidDecl();
3316 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003317 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003318 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003319 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003320 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00003321 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003322 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003323 FD->setInvalidDecl();
3324 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003325 continue;
3326 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003327 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003328 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003329 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003330 FD->setInvalidDecl();
3331 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003332 continue;
3333 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003334 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003335 if (Record)
3336 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003337 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003338 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
3339 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00003340 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003341 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
3342 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003343 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003344 Record->setHasFlexibleArrayMember(true);
3345 } else {
3346 // If this is a struct/class and this is not the last element, reject
3347 // it. Note that GCC supports variable sized arrays in the middle of
3348 // structures.
3349 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003350 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003351 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00003352 FD->setInvalidDecl();
3353 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003354 continue;
3355 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003356 // We support flexible arrays at the end of structs in other structs
3357 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003358 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003359 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003360 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003361 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003362 }
3363 }
3364 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003365 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003366 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003367 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003368 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003369 FD->setInvalidDecl();
3370 EnclosingDecl->setInvalidDecl();
3371 continue;
3372 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003373 // Keep track of the number of named members.
Douglas Gregor72de6672009-01-08 20:45:30 +00003374 if (FD->getIdentifier())
Reid Spencer5f016e22007-07-11 17:01:13 +00003375 ++NumNamedMembers;
Reid Spencer5f016e22007-07-11 17:01:13 +00003376 }
Sebastian Redl64b45f72009-01-05 20:52:13 +00003377
Reid Spencer5f016e22007-07-11 17:01:13 +00003378 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003379 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003380 Record->completeDefinition(Context);
Chris Lattnere1e79852008-02-06 00:51:33 +00003381 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003382 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003383 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003384 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003385 // Must enforce the rule that ivars in the base classes may not be
3386 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003387 if (ID->getSuperClass()) {
3388 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3389 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3390 ObjCIvarDecl* Ivar = (*IVI);
3391 IdentifierInfo *II = Ivar->getIdentifier();
3392 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3393 if (prevIvar) {
3394 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
Douglas Gregor72de6672009-01-08 20:45:30 +00003395 Diag(prevIvar->getLocation(), diag::note_previous_declaration);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003396 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003397 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003398 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003399 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003400 else if (ObjCImplementationDecl *IMPDecl =
3401 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003402 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3403 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003404 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003405 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003406 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003407
3408 if (Attr)
3409 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003410}
3411
Steve Naroff08d92e42007-09-15 18:49:24 +00003412Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003413 DeclTy *lastEnumConst,
3414 SourceLocation IdLoc, IdentifierInfo *Id,
3415 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003416 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003417 EnumConstantDecl *LastEnumConst =
3418 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3419 Expr *Val = static_cast<Expr*>(val);
3420
Chris Lattner31e05722007-08-26 06:24:45 +00003421 // The scope passed in may not be a decl scope. Zip up the scope tree until
3422 // we find one that is.
Douglas Gregor1a0d31a2009-01-12 18:45:55 +00003423 S = getNonFieldDeclScope(S);
Chris Lattner31e05722007-08-26 06:24:45 +00003424
Reid Spencer5f016e22007-07-11 17:01:13 +00003425 // Verify that there isn't already something declared with this name in this
3426 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003427 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003428 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003429 // Maybe we will complain about the shadowed template parameter.
3430 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3431 // Just pretend that we didn't see the previous declaration.
3432 PrevDecl = 0;
3433 }
3434
3435 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003436 // When in C++, we may get a TagDecl with the same name; in this case the
3437 // enum constant will 'hide' the tag.
3438 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3439 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003440 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003441 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003442 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003443 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003444 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003445 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003446 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003447 return 0;
3448 }
3449 }
3450
3451 llvm::APSInt EnumVal(32);
3452 QualType EltTy;
3453 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003454 // Make sure to promote the operand type to int.
3455 UsualUnaryConversions(Val);
3456
Reid Spencer5f016e22007-07-11 17:01:13 +00003457 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3458 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003459 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003460 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003461 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003462 } else {
3463 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003464 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003465 }
3466
3467 if (!Val) {
3468 if (LastEnumConst) {
3469 // Assign the last value + 1.
3470 EnumVal = LastEnumConst->getInitVal();
3471 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003472
3473 // Check for overflow on increment.
3474 if (EnumVal < LastEnumConst->getInitVal())
3475 Diag(IdLoc, diag::warn_enum_value_overflow);
3476
Chris Lattnerb7416f92007-08-27 17:37:24 +00003477 EltTy = LastEnumConst->getType();
3478 } else {
3479 // First value, set to zero.
3480 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003481 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003482 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003483 }
3484
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003485 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003486 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3487 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003488 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003489
3490 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003491 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003492
Reid Spencer5f016e22007-07-11 17:01:13 +00003493 return New;
3494}
3495
Steve Naroff02408c62008-08-07 14:08:16 +00003496// FIXME: For consistency with ActOnFields(), we should have the parser
3497// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003498void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003499 DeclTy **Elements, unsigned NumElements) {
3500 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Douglas Gregor074149e2009-01-05 19:45:36 +00003501 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003502
Douglas Gregor074149e2009-01-05 19:45:36 +00003503 if (EnumType->getAsEnumType()->getDecl()->isDefinition()) {
3504 EnumDecl *Def = EnumType->getAsEnumType()->getDecl();
3505 // Diagnose code like:
3506 // enum e0 {
3507 // E0 = sizeof(enum e0 { E1 })
3508 // };
3509 Diag(Def->getLocation(), diag::err_nested_redefinition)
3510 << Enum->getDeclName();
3511 Diag(Enum->getLocation(), diag::note_previous_definition);
3512 Enum->setInvalidDecl();
Douglas Gregor074149e2009-01-05 19:45:36 +00003513 return;
Steve Naroff02408c62008-08-07 14:08:16 +00003514 }
Douglas Gregor074149e2009-01-05 19:45:36 +00003515
Chris Lattnere37f0be2007-08-28 05:10:31 +00003516 // TODO: If the result value doesn't fit in an int, it must be a long or long
3517 // long value. ISO C does not support this, but GCC does as an extension,
3518 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003519 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003520
Chris Lattnerac609682007-08-28 06:15:15 +00003521 // Verify that all the values are okay, compute the size of the values, and
3522 // reverse the list.
3523 unsigned NumNegativeBits = 0;
3524 unsigned NumPositiveBits = 0;
3525
3526 // Keep track of whether all elements have type int.
3527 bool AllElementsInt = true;
3528
Reid Spencer5f016e22007-07-11 17:01:13 +00003529 for (unsigned i = 0; i != NumElements; ++i) {
3530 EnumConstantDecl *ECD =
3531 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3532 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003533
3534 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003535 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003536 assert(InitVal.getBitWidth() >= IntWidth &&
3537 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003538 if (InitVal.getBitWidth() > IntWidth) {
3539 llvm::APSInt V(InitVal);
3540 V.trunc(IntWidth);
3541 V.extend(InitVal.getBitWidth());
3542 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003543 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3544 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003545 }
Chris Lattnerac609682007-08-28 06:15:15 +00003546
3547 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003548 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003549 NumPositiveBits = std::max(NumPositiveBits,
3550 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003551 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003552 NumNegativeBits = std::max(NumNegativeBits,
3553 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003554
Chris Lattnerac609682007-08-28 06:15:15 +00003555 // Keep track of whether every enum element has type int (very commmon).
3556 if (AllElementsInt)
3557 AllElementsInt = ECD->getType() == Context.IntTy;
Reid Spencer5f016e22007-07-11 17:01:13 +00003558 }
3559
Chris Lattnerac609682007-08-28 06:15:15 +00003560 // Figure out the type that should be used for this enum.
3561 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3562 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003563 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003564
3565 if (NumNegativeBits) {
3566 // If there is a negative value, figure out the smallest integer type (of
3567 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003568 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003569 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003570 BestWidth = IntWidth;
3571 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003572 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003573
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003574 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003575 BestType = Context.LongTy;
3576 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003577 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003578
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003579 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003580 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3581 BestType = Context.LongLongTy;
3582 }
3583 }
3584 } else {
3585 // If there is no negative value, figure out which of uint, ulong, ulonglong
3586 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003587 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003588 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003589 BestWidth = IntWidth;
3590 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003591 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003592 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003593 } else {
3594 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003595 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003596 "How could an initializer get larger than ULL?");
3597 BestType = Context.UnsignedLongLongTy;
3598 }
3599 }
3600
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003601 // Loop over all of the enumerator constants, changing their types to match
3602 // the type of the enum if needed.
3603 for (unsigned i = 0; i != NumElements; ++i) {
3604 EnumConstantDecl *ECD =
3605 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3606 if (!ECD) continue; // Already issued a diagnostic.
3607
3608 // Standard C says the enumerators have int type, but we allow, as an
3609 // extension, the enumerators to be larger than int size. If each
3610 // enumerator value fits in an int, type it as an int, otherwise type it the
3611 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3612 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003613 if (ECD->getType() == Context.IntTy) {
3614 // Make sure the init value is signed.
3615 llvm::APSInt IV = ECD->getInitVal();
3616 IV.setIsSigned(true);
3617 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003618
3619 if (getLangOptions().CPlusPlus)
3620 // C++ [dcl.enum]p4: Following the closing brace of an
3621 // enum-specifier, each enumerator has the type of its
3622 // enumeration.
3623 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003624 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003625 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003626
3627 // Determine whether the value fits into an int.
3628 llvm::APSInt InitVal = ECD->getInitVal();
3629 bool FitsInInt;
3630 if (InitVal.isUnsigned() || !InitVal.isNegative())
3631 FitsInInt = InitVal.getActiveBits() < IntWidth;
3632 else
3633 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3634
3635 // If it fits into an integer type, force it. Otherwise force it to match
3636 // the enum decl type.
3637 QualType NewTy;
3638 unsigned NewWidth;
3639 bool NewSign;
3640 if (FitsInInt) {
3641 NewTy = Context.IntTy;
3642 NewWidth = IntWidth;
3643 NewSign = true;
3644 } else if (ECD->getType() == BestType) {
3645 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003646 if (getLangOptions().CPlusPlus)
3647 // C++ [dcl.enum]p4: Following the closing brace of an
3648 // enum-specifier, each enumerator has the type of its
3649 // enumeration.
3650 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003651 continue;
3652 } else {
3653 NewTy = BestType;
3654 NewWidth = BestWidth;
3655 NewSign = BestType->isSignedIntegerType();
3656 }
3657
3658 // Adjust the APSInt value.
3659 InitVal.extOrTrunc(NewWidth);
3660 InitVal.setIsSigned(NewSign);
3661 ECD->setInitVal(InitVal);
3662
3663 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003664 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3665 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003666 if (getLangOptions().CPlusPlus)
3667 // C++ [dcl.enum]p4: Following the closing brace of an
3668 // enum-specifier, each enumerator has the type of its
3669 // enumeration.
3670 ECD->setType(EnumType);
3671 else
3672 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003673 }
Chris Lattnerac609682007-08-28 06:15:15 +00003674
Douglas Gregor44b43212008-12-11 16:49:14 +00003675 Enum->completeDefinition(Context, BestType);
Reid Spencer5f016e22007-07-11 17:01:13 +00003676}
3677
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003678Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003679 ExprArg expr) {
3680 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3681
Chris Lattner8e25d862008-03-16 00:16:02 +00003682 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003683}
3684
Douglas Gregorf44515a2008-12-16 22:23:02 +00003685
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003686void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3687 ExprTy *alignment, SourceLocation PragmaLoc,
3688 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3689 Expr *Alignment = static_cast<Expr *>(alignment);
3690
3691 // If specified then alignment must be a "small" power of two.
3692 unsigned AlignmentVal = 0;
3693 if (Alignment) {
3694 llvm::APSInt Val;
3695 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3696 !Val.isPowerOf2() ||
3697 Val.getZExtValue() > 16) {
3698 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3699 delete Alignment;
3700 return; // Ignore
3701 }
3702
3703 AlignmentVal = (unsigned) Val.getZExtValue();
3704 }
3705
3706 switch (Kind) {
3707 case Action::PPK_Default: // pack([n])
3708 PackContext.setAlignment(AlignmentVal);
3709 break;
3710
3711 case Action::PPK_Show: // pack(show)
3712 // Show the current alignment, making sure to show the right value
3713 // for the default.
3714 AlignmentVal = PackContext.getAlignment();
3715 // FIXME: This should come from the target.
3716 if (AlignmentVal == 0)
3717 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003718 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003719 break;
3720
3721 case Action::PPK_Push: // pack(push [, id] [, [n])
3722 PackContext.push(Name);
3723 // Set the new alignment if specified.
3724 if (Alignment)
3725 PackContext.setAlignment(AlignmentVal);
3726 break;
3727
3728 case Action::PPK_Pop: // pack(pop [, id] [, n])
3729 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3730 // "#pragma pack(pop, identifier, n) is undefined"
3731 if (Alignment && Name)
3732 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3733
3734 // Do the pop.
3735 if (!PackContext.pop(Name)) {
3736 // If a name was specified then failure indicates the name
3737 // wasn't found. Otherwise failure indicates the stack was
3738 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003739 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3740 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003741
3742 // FIXME: Warn about popping named records as MSVC does.
3743 } else {
3744 // Pop succeeded, set the new alignment if specified.
3745 if (Alignment)
3746 PackContext.setAlignment(AlignmentVal);
3747 }
3748 break;
3749
3750 default:
3751 assert(0 && "Invalid #pragma pack kind.");
3752 }
3753}
3754
3755bool PragmaPackStack::pop(IdentifierInfo *Name) {
3756 if (Stack.empty())
3757 return false;
3758
3759 // If name is empty just pop top.
3760 if (!Name) {
3761 Alignment = Stack.back().first;
3762 Stack.pop_back();
3763 return true;
3764 }
3765
3766 // Otherwise, find the named record.
3767 for (unsigned i = Stack.size(); i != 0; ) {
3768 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003769 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003770 // Found it, pop up to and including this record.
3771 Alignment = Stack[i].first;
3772 Stack.erase(Stack.begin() + i, Stack.end());
3773 return true;
3774 }
3775 }
3776
3777 return false;
3778}