blob: 76835bc3abcce027428da3aedd7f77688fac72a2 [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"
Daniel Dunbar4cde9272008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000031Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S,
32 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000033 DeclContext *DC = 0;
34 if (SS) {
35 if (SS->isInvalid())
36 return 0;
37 DC = static_cast<DeclContext*>(SS->getScopeRep());
38 }
39 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000040
Douglas Gregor2ce52f32008-04-13 21:07:44 +000041 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
42 isa<ObjCInterfaceDecl>(IIDecl) ||
43 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000045 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000046}
47
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000048DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000049 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000050 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000051 if (MD->isOutOfLineDefinition())
52 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000053
54 // A C++ inline method is parsed *after* the topmost class it was declared in
55 // is fully parsed (it's "complete").
56 // The parsing of a C++ inline method happens at the declaration context of
57 // the topmost (non-nested) class it is declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000058 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
59 DC = MD->getParent();
60 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
61 DC = RD;
62
63 // Return the declaration context of the topmost class the inline method is
64 // declared in.
65 return DC;
66 }
67
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000068 if (isa<ObjCMethodDecl>(DC))
69 return Context.getTranslationUnitDecl();
70
71 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
72 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000073
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000074 return DC->getParent();
75}
76
Chris Lattner9fdf9c62008-04-22 18:39:57 +000077void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000078 assert(getContainingDC(DC) == CurContext &&
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000079 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000080 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000081}
82
Chris Lattnerb048c982008-04-06 04:47:34 +000083void Sema::PopDeclContext() {
84 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000085 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000086}
87
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000088/// Add this decl to the scope shadowed decl chains.
89void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000090 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000091
92 // C++ [basic.scope]p4:
93 // -- exactly one declaration shall declare a class name or
94 // enumeration name that is not a typedef name and the other
95 // declarations shall all refer to the same object or
96 // enumerator, or all refer to functions and function templates;
97 // in this case the class name or enumeration name is hidden.
98 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
99 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000100 IdentifierResolver::iterator
101 I = IdResolver.begin(TD->getIdentifier(),
102 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000103 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000104 // There is already a declaration with the same name in the same
105 // scope. It must be found before we find the new declaration,
106 // so swap the order on the shadowed declaration chain.
107
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000108 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000109 return;
110 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000111 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
112 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000113 // We are pushing the name of a function, which might be an
114 // overloaded name.
115 IdentifierResolver::iterator
116 I = IdResolver.begin(FD->getIdentifier(),
117 FD->getDeclContext(), false/*LookInParentCtx*/);
118 if (I != IdResolver.end() &&
119 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
120 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
121 // There is already a declaration with the same name in the same
122 // scope. It must be a function or an overloaded function.
123 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
124 if (!Ovl) {
125 // We haven't yet overloaded this function. Take the existing
126 // FunctionDecl and put it into an OverloadedFunctionDecl.
127 Ovl = OverloadedFunctionDecl::Create(Context,
128 FD->getDeclContext(),
129 FD->getIdentifier());
130 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
131
132 // Remove the name binding to the existing FunctionDecl...
133 IdResolver.RemoveDecl(*I);
134
135 // ... and put the OverloadedFunctionDecl in its place.
136 IdResolver.AddDecl(Ovl);
137 }
138
139 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
140 // to its list of overloads.
141 Ovl->addOverload(FD);
142
143 return;
144 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000145 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000146
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000147 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000148}
149
Steve Naroffb216c882007-10-09 22:01:59 +0000150void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000151 if (S->decl_empty()) return;
152 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000153
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
155 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000156 Decl *TmpD = static_cast<Decl*>(*I);
157 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000158
159 if (isa<CXXFieldDecl>(TmpD)) continue;
160
161 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
162 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000163
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 IdentifierInfo *II = D->getIdentifier();
165 if (!II) continue;
166
Ted Kremeneka89d1972008-09-03 18:03:35 +0000167 // We only want to remove the decls from the identifier decl chains for
168 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000169 if (S->getFnParent() != 0)
170 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000171
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000172 // Chain this decl to the containing DeclContext.
173 D->setNext(CurContext->getDeclChain());
174 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 }
176}
177
Steve Naroffe8043c32008-04-01 23:04:06 +0000178/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
179/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000180ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000181 // The third "scope" argument is 0 since we aren't enabling lazy built-in
182 // creation from this context.
183 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000184
Steve Naroffb327ce02008-04-02 14:35:35 +0000185 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000186}
187
Steve Naroffe8043c32008-04-01 23:04:06 +0000188/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000189/// namespace.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000190Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000191 const DeclContext *LookupCtx,
192 bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000194 unsigned NS = NSI;
195 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
196 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000197
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000198 IdentifierResolver::iterator
199 I = LookupCtx ? IdResolver.begin(II, LookupCtx, false/*LookInParentCtx*/) :
200 IdResolver.begin(II, CurContext, true/*LookInParentCtx*/);
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 // Scan up the scope chain looking for a decl that matches this identifier
202 // that is in the appropriate namespace. This search should not take long, as
203 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000204 for (; I != IdResolver.end(); ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000205 if ((*I)->getIdentifierNamespace() & NS)
206 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000207
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 // If we didn't find a use of this identifier, and if the identifier
209 // corresponds to a compiler builtin, create the decl object for the builtin
210 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000211 if (NS & Decl::IDNS_Ordinary) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000212 if (enableLazyBuiltinCreation &&
213 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000214 // If this is a builtin on this (or all) targets, create the decl.
215 if (unsigned BuiltinID = II->getBuiltinID())
216 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
217 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000218 if (getLangOptions().ObjC1) {
219 // @interface and @compatibility_alias introduce typedef-like names.
220 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000221 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000222 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000223 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
224 if (IDI != ObjCInterfaceDecls.end())
225 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000226 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
227 if (I != ObjCAliasDecls.end())
228 return I->second->getClassInterface();
229 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 }
231 return 0;
232}
233
Chris Lattner95e2c712008-05-05 22:18:14 +0000234void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000235 if (!Context.getBuiltinVaListType().isNull())
236 return;
237
238 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000239 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000240 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000241 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
242}
243
Reid Spencer5f016e22007-07-11 17:01:13 +0000244/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
245/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000246ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
247 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 Builtin::ID BID = (Builtin::ID)bid;
249
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000250 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000251 InitBuiltinVaListType();
252
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000253 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000254 FunctionDecl *New = FunctionDecl::Create(Context,
255 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000256 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000257 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000258
Chris Lattner95e2c712008-05-05 22:18:14 +0000259 // Create Decl objects for each parameter, adding them to the
260 // FunctionDecl.
261 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
262 llvm::SmallVector<ParmVarDecl*, 16> Params;
263 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
264 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
265 FT->getArgType(i), VarDecl::None, 0,
266 0));
267 New->setParams(&Params[0], Params.size());
268 }
269
270
271
Chris Lattner7f925cc2008-04-11 07:00:53 +0000272 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000273 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 return New;
275}
276
Sebastian Redlc42e1182008-11-11 11:37:55 +0000277/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
278/// everything from the standard library is defined.
279NamespaceDecl *Sema::GetStdNamespace() {
280 if (!StdNamespace) {
281 DeclContext *Global = Context.getTranslationUnitDecl();
282 Decl *Std = LookupDecl(Ident_StdNs, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
283 0, Global, /*enableLazyBuiltinCreation=*/false);
284 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
285 }
286 return StdNamespace;
287}
288
Reid Spencer5f016e22007-07-11 17:01:13 +0000289/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
290/// and scope as a previous declaration 'Old'. Figure out how to resolve this
291/// situation, merging decls or emitting diagnostics as appropriate.
292///
Steve Naroffe8043c32008-04-01 23:04:06 +0000293TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000294 // Allow multiple definitions for ObjC built-in typedefs.
295 // FIXME: Verify the underlying types are equivalent!
296 if (getLangOptions().ObjC1) {
297 const IdentifierInfo *typeIdent = New->getIdentifier();
298 if (typeIdent == Ident_id) {
299 Context.setObjCIdType(New);
300 return New;
301 } else if (typeIdent == Ident_Class) {
302 Context.setObjCClassType(New);
303 return New;
304 } else if (typeIdent == Ident_SEL) {
305 Context.setObjCSelType(New);
306 return New;
307 } else if (typeIdent == Ident_Protocol) {
308 Context.setObjCProtoType(New->getUnderlyingType());
309 return New;
310 }
311 // Fall through - the typedef name was not a builtin type.
312 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000313 // Verify the old decl was also a typedef.
314 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
315 if (!Old) {
316 Diag(New->getLocation(), diag::err_redefinition_different_kind,
317 New->getName());
318 Diag(OldD->getLocation(), diag::err_previous_definition);
319 return New;
320 }
321
Chris Lattner99cb9972008-07-25 18:44:27 +0000322 // If the typedef types are not identical, reject them in all languages and
323 // with any extensions enabled.
324 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
325 Context.getCanonicalType(Old->getUnderlyingType()) !=
326 Context.getCanonicalType(New->getUnderlyingType())) {
327 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
328 New->getUnderlyingType().getAsString(),
329 Old->getUnderlyingType().getAsString());
330 Diag(Old->getLocation(), diag::err_previous_definition);
331 return Old;
332 }
333
Eli Friedman54ecfce2008-06-11 06:20:39 +0000334 if (getLangOptions().Microsoft) return New;
335
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000336 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
337 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
338 // *either* declaration is in a system header. The code below implements
339 // this adhoc compatibility rule. FIXME: The following code will not
340 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000341 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
342 SourceManager &SrcMgr = Context.getSourceManager();
343 if (SrcMgr.isInSystemHeader(Old->getLocation()))
344 return New;
345 if (SrcMgr.isInSystemHeader(New->getLocation()))
346 return New;
347 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000348
Ted Kremenek2d05c082008-05-23 21:28:18 +0000349 Diag(New->getLocation(), diag::err_redefinition, New->getName());
350 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000351 return New;
352}
353
Chris Lattner6b6b5372008-06-26 18:38:35 +0000354/// DeclhasAttr - returns true if decl Declaration already has the target
355/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000356static bool DeclHasAttr(const Decl *decl, const Attr *target) {
357 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
358 if (attr->getKind() == target->getKind())
359 return true;
360
361 return false;
362}
363
364/// MergeAttributes - append attributes from the Old decl to the New one.
365static void MergeAttributes(Decl *New, Decl *Old) {
366 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
367
Chris Lattnerddee4232008-03-03 03:28:21 +0000368 while (attr) {
369 tmp = attr;
370 attr = attr->getNext();
371
372 if (!DeclHasAttr(New, tmp)) {
373 New->addAttr(tmp);
374 } else {
375 tmp->setNext(0);
376 delete(tmp);
377 }
378 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000379
380 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000381}
382
Chris Lattner04421082008-04-08 04:40:51 +0000383/// MergeFunctionDecl - We just parsed a function 'New' from
384/// declarator D which has the same name and scope as a previous
385/// declaration 'Old'. Figure out how to resolve this situation,
386/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000387/// Redeclaration will be set true if this New is a redeclaration OldD.
388///
389/// In C++, New and Old must be declarations that are not
390/// overloaded. Use IsOverload to determine whether New and Old are
391/// overloaded, and to select the Old declaration that New should be
392/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000393FunctionDecl *
394Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000395 assert(!isa<OverloadedFunctionDecl>(OldD) &&
396 "Cannot merge with an overloaded function declaration");
397
Douglas Gregorf0097952008-04-21 02:02:58 +0000398 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000399 // Verify the old decl was also a function.
400 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
401 if (!Old) {
402 Diag(New->getLocation(), diag::err_redefinition_different_kind,
403 New->getName());
404 Diag(OldD->getLocation(), diag::err_previous_definition);
405 return New;
406 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000407
408 // Determine whether the previous declaration was a definition,
409 // implicit declaration, or a declaration.
410 diag::kind PrevDiag;
411 if (Old->isThisDeclarationADefinition())
412 PrevDiag = diag::err_previous_definition;
413 else if (Old->isImplicit())
414 PrevDiag = diag::err_previous_implicit_declaration;
415 else
416 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000417
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000418 QualType OldQType = Context.getCanonicalType(Old->getType());
419 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000420
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000421 if (getLangOptions().CPlusPlus) {
422 // (C++98 13.1p2):
423 // Certain function declarations cannot be overloaded:
424 // -- Function declarations that differ only in the return type
425 // cannot be overloaded.
426 QualType OldReturnType
427 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
428 QualType NewReturnType
429 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
430 if (OldReturnType != NewReturnType) {
431 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
432 Diag(Old->getLocation(), PrevDiag);
433 return New;
434 }
435
436 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
437 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
438 if (OldMethod && NewMethod) {
439 // -- Member function declarations with the same name and the
440 // same parameter types cannot be overloaded if any of them
441 // is a static member function declaration.
442 if (OldMethod->isStatic() || NewMethod->isStatic()) {
443 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
444 Diag(Old->getLocation(), PrevDiag);
445 return New;
446 }
447 }
448
449 // (C++98 8.3.5p3):
450 // All declarations for a function shall agree exactly in both the
451 // return type and the parameter-type-list.
452 if (OldQType == NewQType) {
453 // We have a redeclaration.
454 MergeAttributes(New, Old);
455 Redeclaration = true;
456 return MergeCXXFunctionDecl(New, Old);
457 }
458
459 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000460 }
Chris Lattner04421082008-04-08 04:40:51 +0000461
462 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000463 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000464 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000465 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000466 MergeAttributes(New, Old);
467 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000468 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000469 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000470
Steve Naroff837618c2008-01-16 15:01:34 +0000471 // A function that has already been declared has been redeclared or defined
472 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000473
Reid Spencer5f016e22007-07-11 17:01:13 +0000474 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
475 // TODO: This is totally simplistic. It should handle merging functions
476 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000477 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
478 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000479 return New;
480}
481
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000482/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000483static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000484 if (VD->isFileVarDecl())
485 return (!VD->getInit() &&
486 (VD->getStorageClass() == VarDecl::None ||
487 VD->getStorageClass() == VarDecl::Static));
488 return false;
489}
490
491/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
492/// when dealing with C "tentative" external object definitions (C99 6.9.2).
493void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
494 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000495 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000496
497 for (IdentifierResolver::iterator
498 I = IdResolver.begin(VD->getIdentifier(),
499 VD->getDeclContext(), false/*LookInParentCtx*/),
500 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000501 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000502 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
503
Steve Narofff855e6f2008-08-10 15:20:13 +0000504 // Handle the following case:
505 // int a[10];
506 // int a[]; - the code below makes sure we set the correct type.
507 // int a[11]; - this is an error, size isn't 10.
508 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
509 OldDecl->getType()->isConstantArrayType())
510 VD->setType(OldDecl->getType());
511
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000512 // Check for "tentative" definitions. We can't accomplish this in
513 // MergeVarDecl since the initializer hasn't been attached.
514 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
515 continue;
516
517 // Handle __private_extern__ just like extern.
518 if (OldDecl->getStorageClass() != VarDecl::Extern &&
519 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
520 VD->getStorageClass() != VarDecl::Extern &&
521 VD->getStorageClass() != VarDecl::PrivateExtern) {
522 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
523 Diag(OldDecl->getLocation(), diag::err_previous_definition);
524 }
525 }
526 }
527}
528
Reid Spencer5f016e22007-07-11 17:01:13 +0000529/// MergeVarDecl - We just parsed a variable 'New' which has the same name
530/// and scope as a previous declaration 'Old'. Figure out how to resolve this
531/// situation, merging decls or emitting diagnostics as appropriate.
532///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000533/// Tentative definition rules (C99 6.9.2p2) are checked by
534/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
535/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000536///
Steve Naroffe8043c32008-04-01 23:04:06 +0000537VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000538 // Verify the old decl was also a variable.
539 VarDecl *Old = dyn_cast<VarDecl>(OldD);
540 if (!Old) {
541 Diag(New->getLocation(), diag::err_redefinition_different_kind,
542 New->getName());
543 Diag(OldD->getLocation(), diag::err_previous_definition);
544 return New;
545 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000546
547 MergeAttributes(New, Old);
548
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000550 QualType OldCType = Context.getCanonicalType(Old->getType());
551 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000552 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000553 Diag(New->getLocation(), diag::err_redefinition, New->getName());
554 Diag(Old->getLocation(), diag::err_previous_definition);
555 return New;
556 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000557 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
558 if (New->getStorageClass() == VarDecl::Static &&
559 (Old->getStorageClass() == VarDecl::None ||
560 Old->getStorageClass() == VarDecl::Extern)) {
561 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
562 Diag(Old->getLocation(), diag::err_previous_definition);
563 return New;
564 }
565 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
566 if (New->getStorageClass() != VarDecl::Static &&
567 Old->getStorageClass() == VarDecl::Static) {
568 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
569 Diag(Old->getLocation(), diag::err_previous_definition);
570 return New;
571 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000572 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
573 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000574 Diag(New->getLocation(), diag::err_redefinition, New->getName());
575 Diag(Old->getLocation(), diag::err_previous_definition);
576 }
577 return New;
578}
579
Chris Lattner04421082008-04-08 04:40:51 +0000580/// CheckParmsForFunctionDef - Check that the parameters of the given
581/// function are appropriate for the definition of a function. This
582/// takes care of any checks that cannot be performed on the
583/// declaration itself, e.g., that the types of each of the function
584/// parameters are complete.
585bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
586 bool HasInvalidParm = false;
587 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
588 ParmVarDecl *Param = FD->getParamDecl(p);
589
590 // C99 6.7.5.3p4: the parameters in a parameter type list in a
591 // function declarator that is part of a function definition of
592 // that function shall not have incomplete type.
593 if (Param->getType()->isIncompleteType() &&
594 !Param->isInvalidDecl()) {
595 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
596 Param->getType().getAsString());
597 Param->setInvalidDecl();
598 HasInvalidParm = true;
599 }
600 }
601
602 return HasInvalidParm;
603}
604
Reid Spencer5f016e22007-07-11 17:01:13 +0000605/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
606/// no declarator (e.g. "struct foo;") is parsed.
607Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
608 // TODO: emit error on 'int;' or 'const enum foo;'.
609 // TODO: emit error on 'typedef int;'
610 // if (!DS.isMissingDeclaratorOk()) Diag(...);
611
Steve Naroff92199282007-11-17 21:37:36 +0000612 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000613}
614
Steve Naroffd0091aa2008-01-10 22:15:12 +0000615bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000616 // Get the type before calling CheckSingleAssignmentConstraints(), since
617 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000618 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000619
Chris Lattner5cf216b2008-01-04 18:04:52 +0000620 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
621 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
622 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000623}
624
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000625bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000626 const ArrayType *AT = Context.getAsArrayType(DeclT);
627
628 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000629 // C99 6.7.8p14. We have an array of character type with unknown size
630 // being initialized to a string literal.
631 llvm::APSInt ConstVal(32);
632 ConstVal = strLiteral->getByteLength() + 1;
633 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000634 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000635 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000636 } else {
637 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000638 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000639 // FIXME: Avoid truncation for 64-bit length strings.
640 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000641 Diag(strLiteral->getSourceRange().getBegin(),
642 diag::warn_initializer_string_for_char_array_too_long,
643 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000644 }
645 // Set type from "char *" to "constant array of char".
646 strLiteral->setType(DeclT);
647 // For now, we always return false (meaning success).
648 return false;
649}
650
651StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000652 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000653 if (AT && AT->getElementType()->isCharType()) {
654 return dyn_cast<StringLiteral>(Init);
655 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000656 return 0;
657}
658
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000659bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
660 SourceLocation InitLoc,
661 std::string InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000662 // C++ [dcl.init.ref]p1:
663 // A variable declared to be a T&, that is “reference to type T”
664 // (8.3.2), shall be initialized by an object, or function, of
665 // type T or by an object that can be converted into a T.
666 if (DeclType->isReferenceType())
667 return CheckReferenceInit(Init, DeclType);
668
Steve Naroffca107302008-01-21 23:53:58 +0000669 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
670 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000671 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000672 return Diag(InitLoc,
Steve Naroffca107302008-01-21 23:53:58 +0000673 diag::err_variable_object_no_init,
674 VAT->getSizeExpr()->getSourceRange());
675
Steve Naroff2fdc3742007-12-10 22:44:33 +0000676 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
677 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000678 // FIXME: Handle wide strings
679 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
680 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000681
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000682 // C++ [dcl.init]p14:
683 // -- If the destination type is a (possibly cv-qualified) class
684 // type:
685 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
686 QualType DeclTypeC = Context.getCanonicalType(DeclType);
687 QualType InitTypeC = Context.getCanonicalType(Init->getType());
688
689 // -- If the initialization is direct-initialization, or if it is
690 // copy-initialization where the cv-unqualified version of the
691 // source type is the same class as, or a derived class of, the
692 // class of the destination, constructors are considered.
693 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
694 IsDerivedFrom(InitTypeC, DeclTypeC)) {
695 CXXConstructorDecl *Constructor
696 = PerformInitializationByConstructor(DeclType, &Init, 1,
697 InitLoc, Init->getSourceRange(),
698 InitEntity, IK_Copy);
699 return Constructor == 0;
700 }
701
702 // -- Otherwise (i.e., for the remaining copy-initialization
703 // cases), user-defined conversion sequences that can
704 // convert from the source type to the destination type or
705 // (when a conversion function is used) to a derived class
706 // thereof are enumerated as described in 13.3.1.4, and the
707 // best one is chosen through overload resolution
708 // (13.3). If the conversion cannot be done or is
709 // ambiguous, the initialization is ill-formed. The
710 // function selected is called with the initializer
711 // expression as its argument; if the function is a
712 // constructor, the call initializes a temporary of the
713 // destination type.
714 // FIXME: We're pretending to do copy elision here; return to
715 // this when we have ASTs for such things.
716 if (PerformImplicitConversion(Init, DeclType))
717 return Diag(InitLoc,
718 diag::err_typecheck_convert_incompatible,
719 DeclType.getAsString(), InitEntity,
720 "initializing",
721 Init->getSourceRange());
722 else
723 return false;
724 }
725
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000726 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000727 if (DeclType->isArrayType())
728 return Diag(Init->getLocStart(),
729 diag::err_array_init_list_required,
730 Init->getSourceRange());
731
Steve Naroffd0091aa2008-01-10 22:15:12 +0000732 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000733 } else if (getLangOptions().CPlusPlus) {
734 // C++ [dcl.init]p14:
735 // [...] If the class is an aggregate (8.5.1), and the initializer
736 // is a brace-enclosed list, see 8.5.1.
737 //
738 // Note: 8.5.1 is handled below; here, we diagnose the case where
739 // we have an initializer list and a destination type that is not
740 // an aggregate.
741 // FIXME: In C++0x, this is yet another form of initialization.
742 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
743 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
744 if (!ClassDecl->isAggregate())
745 return Diag(InitLoc,
746 diag::err_init_non_aggr_init_list,
747 DeclType.getAsString(),
748 Init->getSourceRange());
749 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000750 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000751
Steve Naroff0cca7492008-05-01 22:18:59 +0000752 InitListChecker CheckInitList(this, InitList, DeclType);
753 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000754}
755
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000756Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000757Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000758 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000759 IdentifierInfo *II = D.getIdentifier();
760
Chris Lattnere80a59c2007-07-25 00:24:17 +0000761 // All of these full declarators require an identifier. If it doesn't have
762 // one, the ParsedFreeStandingDeclSpec action should be used.
763 if (II == 0) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000764 if (!D.getInvalidType()) // Reject this if we think it is valid.
765 Diag(D.getDeclSpec().getSourceRange().getBegin(),
766 diag::err_declarator_need_ident,
767 D.getDeclSpec().getSourceRange(), D.getSourceRange());
Chris Lattnere80a59c2007-07-25 00:24:17 +0000768 return 0;
769 }
770
Chris Lattner31e05722007-08-26 06:24:45 +0000771 // The scope passed in may not be a decl scope. Zip up the scope tree until
772 // we find one that is.
773 while ((S->getFlags() & Scope::DeclScope) == 0)
774 S = S->getParent();
775
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000776 DeclContext *DC;
777 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000778 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000779 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000780
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000781 // See if this is a redefinition of a variable in the same scope.
782 if (!D.getCXXScopeSpec().isSet()) {
783 DC = CurContext;
784 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
785 } else { // Something like "int foo::x;"
786 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
787 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S, DC);
788
789 // C++ 7.3.1.2p2:
790 // Members (including explicit specializations of templates) of a named
791 // namespace can also be defined outside that namespace by explicit
792 // qualification of the name being defined, provided that the entity being
793 // defined was already declared in the namespace and the definition appears
794 // after the point of declaration in a namespace that encloses the
795 // declarations namespace.
796 //
797 if (PrevDecl == 0) {
798 // No previous declaration in the qualifying scope.
799 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
800 II->getName(), D.getCXXScopeSpec().getRange());
801 } else if (!CurContext->Encloses(DC)) {
802 // The qualifying scope doesn't enclose the original declaration.
803 // Emit diagnostic based on current scope.
804 SourceLocation L = D.getIdentifierLoc();
805 SourceRange R = D.getCXXScopeSpec().getRange();
806 if (isa<FunctionDecl>(CurContext)) {
807 Diag(L, diag::err_invalid_declarator_in_function, II->getName(), R);
808 } else {
809 Diag(L, diag::err_invalid_declarator_scope, II->getName(),
810 cast<NamedDecl>(DC)->getName(), R);
811 }
812 }
813 }
814
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000815 // In C++, the previous declaration we find might be a tag type
816 // (class or enum). In this case, the new declaration will hide the
817 // tag type.
818 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
819 PrevDecl = 0;
820
Chris Lattner41af0932007-11-14 06:34:38 +0000821 QualType R = GetTypeForDeclarator(D, S);
822 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
823
Reid Spencer5f016e22007-07-11 17:01:13 +0000824 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000825 // Check that there are no default arguments (C++ only).
826 if (getLangOptions().CPlusPlus)
827 CheckExtraCXXDefaultArguments(D);
828
Chris Lattner41af0932007-11-14 06:34:38 +0000829 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000830 if (!NewTD) return 0;
831
832 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000833 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000834 // Merge the decl with the existing one if appropriate. If the decl is
835 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000836 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000837 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
838 if (NewTD == 0) return 0;
839 }
840 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000841 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000842 // C99 6.7.7p2: If a typedef name specifies a variably modified type
843 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000844 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
845 // FIXME: Diagnostic needs to be fixed.
846 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000847 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000848 }
849 }
Chris Lattner41af0932007-11-14 06:34:38 +0000850 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000851 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000852 switch (D.getDeclSpec().getStorageClassSpec()) {
853 default: assert(0 && "Unknown storage class!");
854 case DeclSpec::SCS_auto:
855 case DeclSpec::SCS_register:
856 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
857 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000858 InvalidDecl = true;
859 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000860 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
861 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
862 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000863 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000864 }
865
Chris Lattnera98e58d2008-03-15 21:24:04 +0000866 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000867 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000868 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
869
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000870 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000871 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000872 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000873 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +0000874 "Constructors can only be declared in a member context");
875
Douglas Gregor42a552f2008-11-05 20:51:48 +0000876 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000877
878 // Create the new declaration
879 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000880 cast<CXXRecordDecl>(DC),
Douglas Gregorb48fe382008-10-31 09:07:45 +0000881 D.getIdentifierLoc(), II, R,
882 isExplicit, isInline,
883 /*isImplicitlyDeclared=*/false);
884
Douglas Gregor42a552f2008-11-05 20:51:48 +0000885 if (isInvalidDecl)
886 NewFD->setInvalidDecl();
887 } else if (D.getKind() == Declarator::DK_Destructor) {
888 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000889 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000890 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000891
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000892 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000893 cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000894 D.getIdentifierLoc(), II, R,
895 isInline,
896 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000897
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000898 if (isInvalidDecl)
899 NewFD->setInvalidDecl();
900 } else {
901 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
902 // Create a FunctionDecl to satisfy the function definition parsing
903 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000904 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000905 II, R, SC, isInline, LastDeclarator,
906 // FIXME: Move to DeclGroup...
907 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000908 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000909 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000910 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000911 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000912 Diag(D.getIdentifierLoc(),
913 diag::err_conv_function_not_member);
914 return 0;
915 } else {
916 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
917
918 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000919 cast<CXXRecordDecl>(DC),
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000920 D.getIdentifierLoc(), II, R,
921 isInline, isExplicit);
922
923 if (isInvalidDecl)
924 NewFD->setInvalidDecl();
925 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000926 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000927 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000928 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000929 D.getIdentifierLoc(), II, R,
930 (SC == FunctionDecl::Static), isInline,
931 LastDeclarator);
932 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000933 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000934 D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000935 II, R, SC, isInline, LastDeclarator,
936 // FIXME: Move to DeclGroup...
937 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000938 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000939 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000940 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000941
Daniel Dunbara80f8742008-08-05 01:35:17 +0000942 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000943 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000944 // The parser guarantees this is a string.
945 StringLiteral *SE = cast<StringLiteral>(E);
946 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
947 SE->getByteLength())));
948 }
949
Chris Lattner04421082008-04-08 04:40:51 +0000950 // Copy the parameter declarations from the declarator D to
951 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000952 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000953 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
954
955 // Create Decl objects for each parameter, adding them to the
956 // FunctionDecl.
957 llvm::SmallVector<ParmVarDecl*, 16> Params;
958
959 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
960 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000961 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000962 // We let through "const void" here because Sema::GetTypeForDeclarator
963 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000964 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
965 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000966 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
967 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000968 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
969
Chris Lattnerdef026a2008-04-10 02:26:16 +0000970 // In C++, the empty parameter-type-list must be spelled "void"; a
971 // typedef of void is not permitted.
972 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000973 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000974 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
975 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000976 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000977 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
978 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
979 }
980
981 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +0000982 } else if (R->getAsTypedefType()) {
983 // When we're declaring a function with a typedef, as in the
984 // following example, we'll need to synthesize (unnamed)
985 // parameters for use in the declaration.
986 //
987 // @code
988 // typedef void fn(int);
989 // fn f;
990 // @endcode
991 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
992 if (!FT) {
993 // This is a typedef of a function with no prototype, so we
994 // don't need to do anything.
995 } else if ((FT->getNumArgs() == 0) ||
996 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
997 FT->getArgType(0)->isVoidType())) {
998 // This is a zero-argument function. We don't need to do anything.
999 } else {
1000 // Synthesize a parameter for each argument type.
1001 llvm::SmallVector<ParmVarDecl*, 16> Params;
1002 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1003 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001004 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001005 SourceLocation(), 0,
1006 *ArgType, VarDecl::None,
1007 0, 0));
1008 }
1009
1010 NewFD->setParams(&Params[0], Params.size());
1011 }
Chris Lattner04421082008-04-08 04:40:51 +00001012 }
1013
Douglas Gregor42a552f2008-11-05 20:51:48 +00001014 // C++ constructors and destructors are handled by separate
1015 // routines, since they don't require any declaration merging (C++
1016 // [class.mfct]p2) and they aren't ever pushed into scope, because
1017 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1018 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1019 return ActOnConstructorDeclarator(Constructor);
1020 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1021 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001022 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1023 return ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001024
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001025 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1026 if (NewFD->isOverloadedOperator() &&
1027 CheckOverloadedOperatorDeclaration(NewFD))
1028 NewFD->setInvalidDecl();
1029
Steve Naroffffce4d52008-01-09 23:34:55 +00001030 // Merge the decl with the existing one if appropriate. Since C functions
1031 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001032 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001033 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001034 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001035
1036 // If C++, determine whether NewFD is an overload of PrevDecl or
1037 // a declaration that requires merging. If it's an overload,
1038 // there's no more work to do here; we'll just add the new
1039 // function to the scope.
1040 OverloadedFunctionDecl::function_iterator MatchedDecl;
1041 if (!getLangOptions().CPlusPlus ||
1042 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1043 Decl *OldDecl = PrevDecl;
1044
1045 // If PrevDecl was an overloaded function, extract the
1046 // FunctionDecl that matched.
1047 if (isa<OverloadedFunctionDecl>(PrevDecl))
1048 OldDecl = *MatchedDecl;
1049
1050 // NewFD and PrevDecl represent declarations that need to be
1051 // merged.
1052 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1053
1054 if (NewFD == 0) return 0;
1055 if (Redeclaration) {
1056 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1057
1058 if (OldDecl == PrevDecl) {
1059 // Remove the name binding for the previous
1060 // declaration. We'll add the binding back later, but then
1061 // it will refer to the new declaration (which will
1062 // contain more information).
1063 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1064 } else {
1065 // We need to update the OverloadedFunctionDecl with the
1066 // latest declaration of this function, so that name
1067 // lookup will always refer to the latest declaration of
1068 // this function.
1069 *MatchedDecl = NewFD;
1070
1071 // Add the redeclaration to the current scope, since we'll
1072 // be skipping PushOnScopeChains.
1073 S->AddDecl(NewFD);
1074
1075 return NewFD;
1076 }
1077 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001078 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001079 }
1080 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001081
1082 // In C++, check default arguments now that we have merged decls.
1083 if (getLangOptions().CPlusPlus)
1084 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001086 // Check that there are no default arguments (C++ only).
1087 if (getLangOptions().CPlusPlus)
1088 CheckExtraCXXDefaultArguments(D);
1089
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001090 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001091 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1092 D.getIdentifier()->getName());
1093 InvalidDecl = true;
1094 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001095
1096 VarDecl *NewVD;
1097 VarDecl::StorageClass SC;
1098 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001099 default: assert(0 && "Unknown storage class!");
1100 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1101 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1102 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1103 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1104 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1105 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001106 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001107 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001108 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1109 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001110 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001111 D.getIdentifierLoc(), II,
1112 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001113 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001114 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001115 if (S->getFnParent() == 0) {
1116 // C99 6.9p2: The storage-class specifiers auto and register shall not
1117 // appear in the declaration specifiers in an external declaration.
1118 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1119 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1120 R.getAsString());
1121 InvalidDecl = true;
1122 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001123 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001124 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001125 II, R, SC, LastDeclarator,
1126 // FIXME: Move to DeclGroup...
1127 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001128 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001129 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001130 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001131 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001132
Daniel Dunbara735ad82008-08-06 00:03:29 +00001133 // Handle GNU asm-label extension (encoded as an attribute).
1134 if (Expr *E = (Expr*) D.getAsmLabel()) {
1135 // The parser guarantees this is a string.
1136 StringLiteral *SE = cast<StringLiteral>(E);
1137 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1138 SE->getByteLength())));
1139 }
1140
Nate Begemanc8e89a82008-03-14 18:07:10 +00001141 // Emit an error if an address space was applied to decl with local storage.
1142 // This includes arrays of objects with address space qualifiers, but not
1143 // automatic variables that point to other address spaces.
1144 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001145 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1146 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1147 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001148 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001149 // Merge the decl with the existing one if appropriate. If the decl is
1150 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001151 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001152 NewVD = MergeVarDecl(NewVD, PrevDecl);
1153 if (NewVD == 0) return 0;
1154 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001155 New = NewVD;
1156 }
1157
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001158 // Set the lexical context. If the declarator has a C++ scope specifier, the
1159 // lexical context will be different from the semantic context.
1160 New->setLexicalDeclContext(CurContext);
1161
Reid Spencer5f016e22007-07-11 17:01:13 +00001162 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001163 if (II)
1164 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001165 // If any semantic error occurred, mark the decl as invalid.
1166 if (D.getInvalidType() || InvalidDecl)
1167 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001168
1169 return New;
1170}
1171
Steve Naroff6594a702008-10-27 11:34:16 +00001172void Sema::InitializerElementNotConstant(const Expr *Init) {
1173 Diag(Init->getExprLoc(),
1174 diag::err_init_element_not_constant, Init->getSourceRange());
1175}
1176
Eli Friedmanc594b322008-05-20 13:48:25 +00001177bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1178 switch (Init->getStmtClass()) {
1179 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001180 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001181 return true;
1182 case Expr::ParenExprClass: {
1183 const ParenExpr* PE = cast<ParenExpr>(Init);
1184 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1185 }
1186 case Expr::CompoundLiteralExprClass:
1187 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1188 case Expr::DeclRefExprClass: {
1189 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001190 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1191 if (VD->hasGlobalStorage())
1192 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001193 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001194 return true;
1195 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001196 if (isa<FunctionDecl>(D))
1197 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001198 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001199 return true;
1200 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001201 case Expr::MemberExprClass: {
1202 const MemberExpr *M = cast<MemberExpr>(Init);
1203 if (M->isArrow())
1204 return CheckAddressConstantExpression(M->getBase());
1205 return CheckAddressConstantExpressionLValue(M->getBase());
1206 }
1207 case Expr::ArraySubscriptExprClass: {
1208 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1209 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1210 return CheckAddressConstantExpression(ASE->getBase()) ||
1211 CheckArithmeticConstantExpression(ASE->getIdx());
1212 }
1213 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001214 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001215 return false;
1216 case Expr::UnaryOperatorClass: {
1217 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1218
1219 // C99 6.6p9
1220 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001221 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001222
Steve Naroff6594a702008-10-27 11:34:16 +00001223 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001224 return true;
1225 }
1226 }
1227}
1228
1229bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1230 switch (Init->getStmtClass()) {
1231 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001232 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001233 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001234 case Expr::ParenExprClass:
1235 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001236 case Expr::StringLiteralClass:
1237 case Expr::ObjCStringLiteralClass:
1238 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001239 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001240 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001241 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1242 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1243 Builtin::BI__builtin___CFStringMakeConstantString)
1244 return false;
1245
Steve Naroff6594a702008-10-27 11:34:16 +00001246 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001247 return true;
1248
Eli Friedmanc594b322008-05-20 13:48:25 +00001249 case Expr::UnaryOperatorClass: {
1250 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1251
1252 // C99 6.6p9
1253 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1254 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1255
1256 if (Exp->getOpcode() == UnaryOperator::Extension)
1257 return CheckAddressConstantExpression(Exp->getSubExpr());
1258
Steve Naroff6594a702008-10-27 11:34:16 +00001259 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001260 return true;
1261 }
1262 case Expr::BinaryOperatorClass: {
1263 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1264 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1265
1266 Expr *PExp = Exp->getLHS();
1267 Expr *IExp = Exp->getRHS();
1268 if (IExp->getType()->isPointerType())
1269 std::swap(PExp, IExp);
1270
1271 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1272 return CheckAddressConstantExpression(PExp) ||
1273 CheckArithmeticConstantExpression(IExp);
1274 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001275 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001276 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001277 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001278 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1279 // Check for implicit promotion
1280 if (SubExpr->getType()->isFunctionType() ||
1281 SubExpr->getType()->isArrayType())
1282 return CheckAddressConstantExpressionLValue(SubExpr);
1283 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001284
1285 // Check for pointer->pointer cast
1286 if (SubExpr->getType()->isPointerType())
1287 return CheckAddressConstantExpression(SubExpr);
1288
Eli Friedmanc3f07642008-08-25 20:46:57 +00001289 if (SubExpr->getType()->isIntegralType()) {
1290 // Check for the special-case of a pointer->int->pointer cast;
1291 // this isn't standard, but some code requires it. See
1292 // PR2720 for an example.
1293 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1294 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1295 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1296 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1297 if (IntWidth >= PointerWidth) {
1298 return CheckAddressConstantExpression(SubCast->getSubExpr());
1299 }
1300 }
1301 }
1302 }
1303 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001304 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001305 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001306
Steve Naroff6594a702008-10-27 11:34:16 +00001307 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001308 return true;
1309 }
1310 case Expr::ConditionalOperatorClass: {
1311 // FIXME: Should we pedwarn here?
1312 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1313 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001314 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001315 return true;
1316 }
1317 if (CheckArithmeticConstantExpression(Exp->getCond()))
1318 return true;
1319 if (Exp->getLHS() &&
1320 CheckAddressConstantExpression(Exp->getLHS()))
1321 return true;
1322 return CheckAddressConstantExpression(Exp->getRHS());
1323 }
1324 case Expr::AddrLabelExprClass:
1325 return false;
1326 }
1327}
1328
Eli Friedman4caf0552008-06-09 05:05:07 +00001329static const Expr* FindExpressionBaseAddress(const Expr* E);
1330
1331static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1332 switch (E->getStmtClass()) {
1333 default:
1334 return E;
1335 case Expr::ParenExprClass: {
1336 const ParenExpr* PE = cast<ParenExpr>(E);
1337 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1338 }
1339 case Expr::MemberExprClass: {
1340 const MemberExpr *M = cast<MemberExpr>(E);
1341 if (M->isArrow())
1342 return FindExpressionBaseAddress(M->getBase());
1343 return FindExpressionBaseAddressLValue(M->getBase());
1344 }
1345 case Expr::ArraySubscriptExprClass: {
1346 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1347 return FindExpressionBaseAddress(ASE->getBase());
1348 }
1349 case Expr::UnaryOperatorClass: {
1350 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1351
1352 if (Exp->getOpcode() == UnaryOperator::Deref)
1353 return FindExpressionBaseAddress(Exp->getSubExpr());
1354
1355 return E;
1356 }
1357 }
1358}
1359
1360static const Expr* FindExpressionBaseAddress(const Expr* E) {
1361 switch (E->getStmtClass()) {
1362 default:
1363 return E;
1364 case Expr::ParenExprClass: {
1365 const ParenExpr* PE = cast<ParenExpr>(E);
1366 return FindExpressionBaseAddress(PE->getSubExpr());
1367 }
1368 case Expr::UnaryOperatorClass: {
1369 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1370
1371 // C99 6.6p9
1372 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1373 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1374
1375 if (Exp->getOpcode() == UnaryOperator::Extension)
1376 return FindExpressionBaseAddress(Exp->getSubExpr());
1377
1378 return E;
1379 }
1380 case Expr::BinaryOperatorClass: {
1381 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1382
1383 Expr *PExp = Exp->getLHS();
1384 Expr *IExp = Exp->getRHS();
1385 if (IExp->getType()->isPointerType())
1386 std::swap(PExp, IExp);
1387
1388 return FindExpressionBaseAddress(PExp);
1389 }
1390 case Expr::ImplicitCastExprClass: {
1391 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1392
1393 // Check for implicit promotion
1394 if (SubExpr->getType()->isFunctionType() ||
1395 SubExpr->getType()->isArrayType())
1396 return FindExpressionBaseAddressLValue(SubExpr);
1397
1398 // Check for pointer->pointer cast
1399 if (SubExpr->getType()->isPointerType())
1400 return FindExpressionBaseAddress(SubExpr);
1401
1402 // We assume that we have an arithmetic expression here;
1403 // if we don't, we'll figure it out later
1404 return 0;
1405 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001406 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001407 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1408
1409 // Check for pointer->pointer cast
1410 if (SubExpr->getType()->isPointerType())
1411 return FindExpressionBaseAddress(SubExpr);
1412
1413 // We assume that we have an arithmetic expression here;
1414 // if we don't, we'll figure it out later
1415 return 0;
1416 }
1417 }
1418}
1419
Eli Friedmanc594b322008-05-20 13:48:25 +00001420bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1421 switch (Init->getStmtClass()) {
1422 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001423 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001424 return true;
1425 case Expr::ParenExprClass: {
1426 const ParenExpr* PE = cast<ParenExpr>(Init);
1427 return CheckArithmeticConstantExpression(PE->getSubExpr());
1428 }
1429 case Expr::FloatingLiteralClass:
1430 case Expr::IntegerLiteralClass:
1431 case Expr::CharacterLiteralClass:
1432 case Expr::ImaginaryLiteralClass:
1433 case Expr::TypesCompatibleExprClass:
1434 case Expr::CXXBoolLiteralExprClass:
1435 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001436 case Expr::CallExprClass:
1437 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001438 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001439
1440 // Allow any constant foldable calls to builtins.
1441 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001442 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001443
Steve Naroff6594a702008-10-27 11:34:16 +00001444 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001445 return true;
1446 }
1447 case Expr::DeclRefExprClass: {
1448 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1449 if (isa<EnumConstantDecl>(D))
1450 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001451 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001452 return true;
1453 }
1454 case Expr::CompoundLiteralExprClass:
1455 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1456 // but vectors are allowed to be magic.
1457 if (Init->getType()->isVectorType())
1458 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001459 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001460 return true;
1461 case Expr::UnaryOperatorClass: {
1462 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1463
1464 switch (Exp->getOpcode()) {
1465 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1466 // See C99 6.6p3.
1467 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001468 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001469 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001470 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001471 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1472 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001473 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001474 return true;
1475 case UnaryOperator::Extension:
1476 case UnaryOperator::LNot:
1477 case UnaryOperator::Plus:
1478 case UnaryOperator::Minus:
1479 case UnaryOperator::Not:
1480 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1481 }
1482 }
Sebastian Redl05189992008-11-11 17:56:53 +00001483 case Expr::SizeOfAlignOfExprClass: {
1484 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001485 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001486 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001487 return false;
1488 // alignof always evaluates to a constant.
1489 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001490 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001491 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001492 return true;
1493 }
1494 return false;
1495 }
1496 case Expr::BinaryOperatorClass: {
1497 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1498
1499 if (Exp->getLHS()->getType()->isArithmeticType() &&
1500 Exp->getRHS()->getType()->isArithmeticType()) {
1501 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1502 CheckArithmeticConstantExpression(Exp->getRHS());
1503 }
1504
Eli Friedman4caf0552008-06-09 05:05:07 +00001505 if (Exp->getLHS()->getType()->isPointerType() &&
1506 Exp->getRHS()->getType()->isPointerType()) {
1507 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1508 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1509
1510 // Only allow a null (constant integer) base; we could
1511 // allow some additional cases if necessary, but this
1512 // is sufficient to cover offsetof-like constructs.
1513 if (!LHSBase && !RHSBase) {
1514 return CheckAddressConstantExpression(Exp->getLHS()) ||
1515 CheckAddressConstantExpression(Exp->getRHS());
1516 }
1517 }
1518
Steve Naroff6594a702008-10-27 11:34:16 +00001519 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001520 return true;
1521 }
1522 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001523 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001524 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001525 if (SubExpr->getType()->isArithmeticType())
1526 return CheckArithmeticConstantExpression(SubExpr);
1527
Eli Friedmanb529d832008-09-02 09:37:00 +00001528 if (SubExpr->getType()->isPointerType()) {
1529 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1530 // If the pointer has a null base, this is an offsetof-like construct
1531 if (!Base)
1532 return CheckAddressConstantExpression(SubExpr);
1533 }
1534
Steve Naroff6594a702008-10-27 11:34:16 +00001535 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001536 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001537 }
1538 case Expr::ConditionalOperatorClass: {
1539 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001540
1541 // If GNU extensions are disabled, we require all operands to be arithmetic
1542 // constant expressions.
1543 if (getLangOptions().NoExtensions) {
1544 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1545 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1546 CheckArithmeticConstantExpression(Exp->getRHS());
1547 }
1548
1549 // Otherwise, we have to emulate some of the behavior of fold here.
1550 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1551 // because it can constant fold things away. To retain compatibility with
1552 // GCC code, we see if we can fold the condition to a constant (which we
1553 // should always be able to do in theory). If so, we only require the
1554 // specified arm of the conditional to be a constant. This is a horrible
1555 // hack, but is require by real world code that uses __builtin_constant_p.
1556 APValue Val;
1557 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1558 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1559 // won't be able to either. Use it to emit the diagnostic though.
1560 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1561 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1562 return Res;
1563 }
1564
1565 // Verify that the side following the condition is also a constant.
1566 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1567 if (Val.getInt() == 0)
1568 std::swap(TrueSide, FalseSide);
1569
1570 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001571 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001572
1573 // Okay, the evaluated side evaluates to a constant, so we accept this.
1574 // Check to see if the other side is obviously not a constant. If so,
1575 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001576 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001577 Diag(Init->getExprLoc(),
1578 diag::ext_typecheck_expression_not_constant_but_accepted,
1579 FalseSide->getSourceRange());
1580 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001581 }
1582 }
1583}
1584
1585bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001586 Init = Init->IgnoreParens();
1587
Eli Friedmanc594b322008-05-20 13:48:25 +00001588 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1589 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1590 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1591
Nuno Lopes9a979c32008-07-07 16:46:50 +00001592 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1593 return CheckForConstantInitializer(e->getInitializer(), DclT);
1594
Eli Friedmanc594b322008-05-20 13:48:25 +00001595 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1596 unsigned numInits = Exp->getNumInits();
1597 for (unsigned i = 0; i < numInits; i++) {
1598 // FIXME: Need to get the type of the declaration for C++,
1599 // because it could be a reference?
1600 if (CheckForConstantInitializer(Exp->getInit(i),
1601 Exp->getInit(i)->getType()))
1602 return true;
1603 }
1604 return false;
1605 }
1606
1607 if (Init->isNullPointerConstant(Context))
1608 return false;
1609 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001610 QualType InitTy = Context.getCanonicalType(Init->getType())
1611 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001612 if (InitTy == Context.BoolTy) {
1613 // Special handling for pointers implicitly cast to bool;
1614 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1615 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1616 Expr* SubE = ICE->getSubExpr();
1617 if (SubE->getType()->isPointerType() ||
1618 SubE->getType()->isArrayType() ||
1619 SubE->getType()->isFunctionType()) {
1620 return CheckAddressConstantExpression(Init);
1621 }
1622 }
1623 } else if (InitTy->isIntegralType()) {
1624 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001625 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001626 SubE = CE->getSubExpr();
1627 // Special check for pointer cast to int; we allow as an extension
1628 // an address constant cast to an integer if the integer
1629 // is of an appropriate width (this sort of code is apparently used
1630 // in some places).
1631 // FIXME: Add pedwarn?
1632 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1633 if (SubE && (SubE->getType()->isPointerType() ||
1634 SubE->getType()->isArrayType() ||
1635 SubE->getType()->isFunctionType())) {
1636 unsigned IntWidth = Context.getTypeSize(Init->getType());
1637 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1638 if (IntWidth >= PointerWidth)
1639 return CheckAddressConstantExpression(Init);
1640 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001641 }
1642
1643 return CheckArithmeticConstantExpression(Init);
1644 }
1645
1646 if (Init->getType()->isPointerType())
1647 return CheckAddressConstantExpression(Init);
1648
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001649 // An array type at the top level that isn't an init-list must
1650 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001651 if (Init->getType()->isArrayType())
1652 return false;
1653
Nuno Lopes73419bf2008-09-01 18:42:41 +00001654 if (Init->getType()->isFunctionType())
1655 return false;
1656
Steve Naroff8af6a452008-10-02 17:12:56 +00001657 // Allow block exprs at top level.
1658 if (Init->getType()->isBlockPointerType())
1659 return false;
1660
Steve Naroff6594a702008-10-27 11:34:16 +00001661 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001662 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001663}
1664
Steve Naroffbb204692007-09-12 14:07:44 +00001665void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001666 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001667 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001668 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001669
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001670 // If there is no declaration, there was an error parsing it. Just ignore
1671 // the initializer.
1672 if (RealDecl == 0) {
1673 delete Init;
1674 return;
1675 }
Steve Naroffbb204692007-09-12 14:07:44 +00001676
Steve Naroff410e3e22007-09-12 20:13:48 +00001677 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1678 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001679 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1680 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001681 RealDecl->setInvalidDecl();
1682 return;
1683 }
Steve Naroffbb204692007-09-12 14:07:44 +00001684 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001685 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001686 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001687 if (VDecl->isBlockVarDecl()) {
1688 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001689 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001690 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001691 VDecl->setInvalidDecl();
1692 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001693 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1694 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001695 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001696
1697 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1698 if (!getLangOptions().CPlusPlus) {
1699 if (SC == VarDecl::Static) // C99 6.7.8p4.
1700 CheckForConstantInitializer(Init, DclT);
1701 }
Steve Naroffbb204692007-09-12 14:07:44 +00001702 }
Steve Naroff248a7532008-04-15 22:42:06 +00001703 } else if (VDecl->isFileVarDecl()) {
1704 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001705 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001706 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001707 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1708 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001709 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001710
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001711 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1712 if (!getLangOptions().CPlusPlus) {
1713 // C99 6.7.8p4. All file scoped initializers need to be constant.
1714 CheckForConstantInitializer(Init, DclT);
1715 }
Steve Naroffbb204692007-09-12 14:07:44 +00001716 }
1717 // If the type changed, it means we had an incomplete type that was
1718 // completed by the initializer. For example:
1719 // int ary[] = { 1, 3, 5 };
1720 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001721 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001722 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001723 Init->setType(DclT);
1724 }
Steve Naroffbb204692007-09-12 14:07:44 +00001725
1726 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001727 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001728 return;
1729}
1730
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001731void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1732 Decl *RealDecl = static_cast<Decl *>(dcl);
1733
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001734 // If there is no declaration, there was an error parsing it. Just ignore it.
1735 if (RealDecl == 0)
1736 return;
1737
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001738 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1739 QualType Type = Var->getType();
1740 // C++ [dcl.init.ref]p3:
1741 // The initializer can be omitted for a reference only in a
1742 // parameter declaration (8.3.5), in the declaration of a
1743 // function return type, in the declaration of a class member
1744 // within its class declaration (9.2), and where the extern
1745 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001746 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001747 Diag(Var->getLocation(),
1748 diag::err_reference_var_requires_init,
1749 Var->getName(),
1750 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor18fe5682008-11-03 20:45:27 +00001751 Var->setInvalidDecl();
1752 return;
1753 }
1754
1755 // C++ [dcl.init]p9:
1756 //
1757 // If no initializer is specified for an object, and the object
1758 // is of (possibly cv-qualified) non-POD class type (or array
1759 // thereof), the object shall be default-initialized; if the
1760 // object is of const-qualified type, the underlying class type
1761 // shall have a user-declared default constructor.
1762 if (getLangOptions().CPlusPlus) {
1763 QualType InitType = Type;
1764 if (const ArrayType *Array = Context.getAsArrayType(Type))
1765 InitType = Array->getElementType();
1766 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001767 const CXXConstructorDecl *Constructor
1768 = PerformInitializationByConstructor(InitType, 0, 0,
1769 Var->getLocation(),
1770 SourceRange(Var->getLocation(),
1771 Var->getLocation()),
1772 Var->getName(),
1773 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001774 if (!Constructor)
1775 Var->setInvalidDecl();
1776 }
1777 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001778
Douglas Gregor818ce482008-10-29 13:50:18 +00001779#if 0
1780 // FIXME: Temporarily disabled because we are not properly parsing
1781 // linkage specifications on declarations, e.g.,
1782 //
1783 // extern "C" const CGPoint CGPointerZero;
1784 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001785 // C++ [dcl.init]p9:
1786 //
1787 // If no initializer is specified for an object, and the
1788 // object is of (possibly cv-qualified) non-POD class type (or
1789 // array thereof), the object shall be default-initialized; if
1790 // the object is of const-qualified type, the underlying class
1791 // type shall have a user-declared default
1792 // constructor. Otherwise, if no initializer is specified for
1793 // an object, the object and its subobjects, if any, have an
1794 // indeterminate initial value; if the object or any of its
1795 // subobjects are of const-qualified type, the program is
1796 // ill-formed.
1797 //
1798 // This isn't technically an error in C, so we don't diagnose it.
1799 //
1800 // FIXME: Actually perform the POD/user-defined default
1801 // constructor check.
1802 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001803 Context.getCanonicalType(Type).isConstQualified() &&
1804 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001805 Diag(Var->getLocation(),
1806 diag::err_const_var_requires_init,
1807 Var->getName(),
1808 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor818ce482008-10-29 13:50:18 +00001809#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001810 }
1811}
1812
Reid Spencer5f016e22007-07-11 17:01:13 +00001813/// The declarators are chained together backwards, reverse the list.
1814Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1815 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001816 Decl *GroupDecl = static_cast<Decl*>(group);
1817 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001818 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001819
1820 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1821 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001822 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001823 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001824 else { // reverse the list.
1825 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001826 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001827 Group->setNextDeclarator(NewGroup);
1828 NewGroup = Group;
1829 Group = Next;
1830 }
1831 }
1832 // Perform semantic analysis that depends on having fully processed both
1833 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001834 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001835 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1836 if (!IDecl)
1837 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001838 QualType T = IDecl->getType();
1839
1840 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1841 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001842 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1843 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001844 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001845 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1846 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001847 }
1848 }
1849 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1850 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001851 if (IDecl->isBlockVarDecl() &&
1852 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001853 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001854 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1855 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001856 IDecl->setInvalidDecl();
1857 }
1858 }
1859 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1860 // object that has file scope without an initializer, and without a
1861 // storage-class specifier or with the storage-class specifier "static",
1862 // constitutes a tentative definition. Note: A tentative definition with
1863 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001864 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001865 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001866 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1867 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001868 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001869 // C99 6.9.2p3: If the declaration of an identifier for an object is
1870 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1871 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001872 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1873 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001874 IDecl->setInvalidDecl();
1875 }
1876 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001877 if (IDecl->isFileVarDecl())
1878 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001879 }
1880 return NewGroup;
1881}
Steve Naroffe1223f72007-08-28 03:03:08 +00001882
Chris Lattner04421082008-04-08 04:40:51 +00001883/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1884/// to introduce parameters into function prototype scope.
1885Sema::DeclTy *
1886Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001887 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00001888 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001889
1890 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001891 VarDecl::StorageClass StorageClass = VarDecl::None;
1892 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1893 StorageClass = VarDecl::Register;
1894 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001895 Diag(DS.getStorageClassSpecLoc(),
1896 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001897 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001898 }
1899 if (DS.isThreadSpecified()) {
1900 Diag(DS.getThreadSpecLoc(),
1901 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001902 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001903 }
1904
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001905 // Check that there are no default arguments inside the type of this
1906 // parameter (C++ only).
1907 if (getLangOptions().CPlusPlus)
1908 CheckExtraCXXDefaultArguments(D);
1909
Chris Lattner04421082008-04-08 04:40:51 +00001910 // In this context, we *do not* check D.getInvalidType(). If the declarator
1911 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1912 // though it will not reflect the user specified type.
1913 QualType parmDeclType = GetTypeForDeclarator(D, S);
1914
1915 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1916
Reid Spencer5f016e22007-07-11 17:01:13 +00001917 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1918 // Can this happen for params? We already checked that they don't conflict
1919 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001920 IdentifierInfo *II = D.getIdentifier();
1921 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1922 if (S->isDeclScope(PrevDecl)) {
1923 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1924 dyn_cast<NamedDecl>(PrevDecl)->getName());
1925
1926 // Recover by removing the name
1927 II = 0;
1928 D.SetIdentifier(0, D.getIdentifierLoc());
1929 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001930 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001931
1932 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1933 // Doing the promotion here has a win and a loss. The win is the type for
1934 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1935 // code generator). The loss is the orginal type isn't preserved. For example:
1936 //
1937 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1938 // int blockvardecl[5];
1939 // sizeof(parmvardecl); // size == 4
1940 // sizeof(blockvardecl); // size == 20
1941 // }
1942 //
1943 // For expressions, all implicit conversions are captured using the
1944 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1945 //
1946 // FIXME: If a source translation tool needs to see the original type, then
1947 // we need to consider storing both types (in ParmVarDecl)...
1948 //
Chris Lattnere6327742008-04-02 05:18:44 +00001949 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001950 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001951 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001952 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001953 parmDeclType = Context.getPointerType(parmDeclType);
1954
Chris Lattner04421082008-04-08 04:40:51 +00001955 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1956 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001957 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001958 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001959
Chris Lattner04421082008-04-08 04:40:51 +00001960 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001961 New->setInvalidDecl();
1962
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001963 if (II)
1964 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001965
Chris Lattner3ff30c82008-06-29 00:02:00 +00001966 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001968
Reid Spencer5f016e22007-07-11 17:01:13 +00001969}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001970
Chris Lattnerb652cea2007-10-09 17:14:05 +00001971Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001972 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001973 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1974 "Not a function declarator!");
1975 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001976
Reid Spencer5f016e22007-07-11 17:01:13 +00001977 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1978 // for a K&R function.
1979 if (!FTI.hasPrototype) {
1980 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001981 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1983 FTI.ArgInfo[i].Ident->getName());
1984 // Implicitly declare the argument as type 'int' for lack of a better
1985 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001986 DeclSpec DS;
1987 const char* PrevSpec; // unused
1988 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1989 PrevSpec);
1990 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1991 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1992 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001993 }
1994 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001995 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001996 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001997 }
1998
1999 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002000
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002001 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00002002 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002003}
2004
2005Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2006 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002007 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002008
2009 // See if this is a redefinition.
2010 const FunctionDecl *Definition;
2011 if (FD->getBody(Definition)) {
2012 Diag(FD->getLocation(), diag::err_redefinition,
2013 FD->getName());
2014 Diag(Definition->getLocation(), diag::err_previous_definition);
2015 }
2016
Chris Lattnerb048c982008-04-06 04:47:34 +00002017 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00002018
2019 // Check the validity of our function parameters
2020 CheckParmsForFunctionDef(FD);
2021
2022 // Introduce our parameters into the function scope
2023 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2024 ParmVarDecl *Param = FD->getParamDecl(p);
2025 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002026 if (Param->getIdentifier())
2027 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002028 }
Chris Lattner04421082008-04-08 04:40:51 +00002029
Reid Spencer5f016e22007-07-11 17:01:13 +00002030 return FD;
2031}
2032
Steve Naroffd6d054d2007-11-11 23:20:51 +00002033Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2034 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002035 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002036 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002037 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002038 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002039 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002040 } else
2041 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002042 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002043 // Verify and clean out per-function state.
2044
2045 // Check goto/label use.
2046 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2047 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2048 // Verify that we have no forward references left. If so, there was a goto
2049 // or address of a label taken, but no definition of it. Label fwd
2050 // definitions are indicated with a null substmt.
2051 if (I->second->getSubStmt() == 0) {
2052 LabelStmt *L = I->second;
2053 // Emit error.
2054 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2055
2056 // At this point, we have gotos that use the bogus label. Stitch it into
2057 // the function body so that they aren't leaked and that the AST is well
2058 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002059 if (Body) {
2060 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2061 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2062 } else {
2063 // The whole function wasn't parsed correctly, just delete this.
2064 delete L;
2065 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002066 }
2067 }
2068 LabelMap.clear();
2069
Steve Naroffd6d054d2007-11-11 23:20:51 +00002070 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002071}
2072
Reid Spencer5f016e22007-07-11 17:01:13 +00002073/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2074/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002075ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2076 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002077 // Extension in C99. Legal in C90, but warn about it.
2078 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00002079 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00002080 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002081 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2082
2083 // FIXME: handle stuff like:
2084 // void foo() { extern float X(); }
2085 // void bar() { X(); } <-- implicit decl for X in another scope.
2086
2087 // Set a Declarator for the implicit definition: int foo();
2088 const char *Dummy;
2089 DeclSpec DS;
2090 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2091 Error = Error; // Silence warning.
2092 assert(!Error && "Error setting up implicit decl!");
2093 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002094 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002095 D.SetIdentifier(&II, Loc);
2096
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002097 // Insert this function into translation-unit scope.
2098
2099 DeclContext *PrevDC = CurContext;
2100 CurContext = Context.getTranslationUnitDecl();
2101
Steve Naroffe2ef8152008-04-04 14:32:09 +00002102 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002103 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002104 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002105
2106 CurContext = PrevDC;
2107
Steve Naroffe2ef8152008-04-04 14:32:09 +00002108 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002109}
2110
2111
Chris Lattner41af0932007-11-14 06:34:38 +00002112TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002113 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002114 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002115 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002116
2117 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002118 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2119 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002120 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002121 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002122 if (D.getInvalidType())
2123 NewTD->setInvalidDecl();
2124 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002125}
2126
Steve Naroff08d92e42007-09-15 18:49:24 +00002127/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002128/// former case, Name will be non-null. In the later case, Name will be null.
2129/// TagType indicates what kind of tag this is. TK indicates whether this is a
2130/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002131Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002132 SourceLocation KWLoc, const CXXScopeSpec &SS,
2133 IdentifierInfo *Name, SourceLocation NameLoc,
2134 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 // If this is a use of an existing tag, it must have a name.
2136 assert((Name != 0 || TK == TK_Definition) &&
2137 "Nameless record must be a definition!");
2138
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002139 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 switch (TagType) {
2141 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002142 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2143 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2144 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2145 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002146 }
2147
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002148 // Two code paths: a new one for structs/unions/classes where we create
2149 // separate decls for forward declarations, and an old (eventually to
2150 // be removed) code path for enums.
2151 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002152 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002153
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002154 DeclContext *DC = CurContext;
2155 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002156
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002157 if (Name && SS.isNotEmpty()) {
2158 // We have a nested-name tag ('struct foo::bar').
2159
2160 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002161 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002162 Name = 0;
2163 goto CreateNewDecl;
2164 }
2165
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002166 DC = static_cast<DeclContext*>(SS.getScopeRep());
2167 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002168 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2169
2170 // A tag 'foo::bar' must already exist.
2171 if (PrevDecl == 0) {
2172 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2173 SS.getRange());
2174 Name = 0;
2175 goto CreateNewDecl;
2176 }
2177 } else {
2178 // If this is a named struct, check to see if there was a previous forward
2179 // declaration or definition.
2180 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2181 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2182 }
2183
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002184 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002185 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2186 "unexpected Decl type");
2187 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002188 // If this is a use of a previous tag, or if the tag is already declared
2189 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002190 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002191 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002192 // Make sure that this wasn't declared as an enum and now used as a
2193 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002194 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002195 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2196 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002197 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002198 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002199 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002200 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002201 // If this is a use or a forward declaration, we're good.
2202 if (TK != TK_Definition)
2203 return PrevDecl;
2204
2205 // Diagnose attempts to redefine a tag.
2206 if (PrevTagDecl->isDefinition()) {
2207 Diag(NameLoc, diag::err_redefinition, Name->getName());
2208 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2209 // If this is a redefinition, recover by making this struct be
2210 // anonymous, which will make any later references get the previous
2211 // definition.
2212 Name = 0;
2213 } else {
2214 // Okay, this is definition of a previously declared or referenced
2215 // tag. Move the location of the decl to be the definition site.
2216 PrevDecl->setLocation(NameLoc);
2217 return PrevDecl;
2218 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002219 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002220 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002221 // If we get here, this is a definition of a new struct type in a nested
2222 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2223 // type.
2224 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002225 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002226 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002227 // The tag name clashes with a namespace name, issue an error and
2228 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002229 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2230 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2231 Name = 0;
2232 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002233 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002234 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002235
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002236 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002237
2238 // If there is an identifier, use the location of the identifier as the
2239 // location of the decl, otherwise use the location of the struct/union
2240 // keyword.
2241 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2242
2243 // Otherwise, if this is the first time we've seen this tag, create the decl.
2244 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002245 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002246 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2247 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002248 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002249 // If this is an undefined enum, warn.
2250 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002251 } else {
2252 // struct/union/class
2253
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2255 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002256 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002257 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002258 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002259 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002260 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002261 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002262
2263 // If this has an identifier, add it to the scope stack.
2264 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002265 // The scope passed in may not be a decl scope. Zip up the scope tree until
2266 // we find one that is.
2267 while ((S->getFlags() & Scope::DeclScope) == 0)
2268 S = S->getParent();
2269
2270 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002271 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002273
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002274 if (Attr)
2275 ProcessDeclAttributeList(New, Attr);
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002276
2277 // Set the lexical context. If the tag has a C++ scope specifier, the
2278 // lexical context will be different from the semantic context.
2279 New->setLexicalDeclContext(CurContext);
2280
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 return New;
2282}
2283
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002284/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2285/// the logic for enums, we create separate decls for forward declarations.
2286/// This is called by ActOnTag, but eventually will replace its logic.
2287Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002288 SourceLocation KWLoc, const CXXScopeSpec &SS,
2289 IdentifierInfo *Name, SourceLocation NameLoc,
2290 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002291 DeclContext *DC = CurContext;
2292 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002293
2294 if (Name && SS.isNotEmpty()) {
2295 // We have a nested-name tag ('struct foo::bar').
2296
2297 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002298 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002299 Name = 0;
2300 goto CreateNewDecl;
2301 }
2302
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002303 DC = static_cast<DeclContext*>(SS.getScopeRep());
2304 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002305 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2306
2307 // A tag 'foo::bar' must already exist.
2308 if (PrevDecl == 0) {
2309 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2310 SS.getRange());
2311 Name = 0;
2312 goto CreateNewDecl;
2313 }
2314 } else {
2315 // If this is a named struct, check to see if there was a previous forward
2316 // declaration or definition.
2317 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2318 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2319 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002320
2321 if (PrevDecl) {
2322 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2323 "unexpected Decl type");
2324
2325 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2326 // If this is a use of a previous tag, or if the tag is already declared
2327 // in the same scope (so that the definition/declaration completes or
2328 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002329 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002330 // Make sure that this wasn't declared as an enum and now used as a
2331 // struct or something similar.
2332 if (PrevTagDecl->getTagKind() != Kind) {
2333 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2334 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2335 // Recover by making this an anonymous redefinition.
2336 Name = 0;
2337 PrevDecl = 0;
2338 } else {
2339 // If this is a use, return the original decl.
2340
2341 // FIXME: In the future, return a variant or some other clue
2342 // for the consumer of this Decl to know it doesn't own it.
2343 // For our current ASTs this shouldn't be a problem, but will
2344 // need to be changed with DeclGroups.
2345 if (TK == TK_Reference)
2346 return PrevDecl;
2347
2348 // The new decl is a definition?
2349 if (TK == TK_Definition) {
2350 // Diagnose attempts to redefine a tag.
2351 if (RecordDecl* DefRecord =
2352 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2353 Diag(NameLoc, diag::err_redefinition, Name->getName());
2354 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2355 // If this is a redefinition, recover by making this struct be
2356 // anonymous, which will make any later references get the previous
2357 // definition.
2358 Name = 0;
2359 PrevDecl = 0;
2360 }
2361 // Okay, this is definition of a previously declared or referenced
2362 // tag. We're going to create a new Decl.
2363 }
2364 }
2365 // If we get here we have (another) forward declaration. Just create
2366 // a new decl.
2367 }
2368 else {
2369 // If we get here, this is a definition of a new struct type in a nested
2370 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2371 // new decl/type. We set PrevDecl to NULL so that the Records
2372 // have distinct types.
2373 PrevDecl = 0;
2374 }
2375 } else {
2376 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002377 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002378 // The tag name clashes with a namespace name, issue an error and
2379 // recover by making this tag be anonymous.
2380 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2381 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2382 Name = 0;
2383 }
2384 }
2385 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002386
2387 CreateNewDecl:
2388
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002389 // If there is an identifier, use the location of the identifier as the
2390 // location of the decl, otherwise use the location of the struct/union
2391 // keyword.
2392 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2393
2394 // Otherwise, if this is the first time we've seen this tag, create the decl.
2395 TagDecl *New;
2396
2397 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2398 // struct X { int A; } D; D should chain to X.
2399 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002400 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002401 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002402 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2403 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002404 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002405 dyn_cast_or_null<RecordDecl>(PrevDecl));
2406
2407 // If this has an identifier, add it to the scope stack.
2408 if ((TK == TK_Definition || !PrevDecl) && Name) {
2409 // The scope passed in may not be a decl scope. Zip up the scope tree until
2410 // we find one that is.
2411 while ((S->getFlags() & Scope::DeclScope) == 0)
2412 S = S->getParent();
2413
2414 // Add it to the decl chain.
2415 PushOnScopeChains(New, S);
2416 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002417
2418 // Handle #pragma pack: if the #pragma pack stack has non-default
2419 // alignment, make up a packed attribute for this decl. These
2420 // attributes are checked when the ASTContext lays out the
2421 // structure.
2422 //
2423 // It is important for implementing the correct semantics that this
2424 // happen here (in act on tag decl). The #pragma pack stack is
2425 // maintained as a result of parser callbacks which can occur at
2426 // many points during the parsing of a struct declaration (because
2427 // the #pragma tokens are effectively skipped over during the
2428 // parsing of the struct).
2429 if (unsigned Alignment = PackContext.getAlignment())
2430 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002431
2432 if (Attr)
2433 ProcessDeclAttributeList(New, Attr);
2434
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002435 // Set the lexical context. If the tag has a C++ scope specifier, the
2436 // lexical context will be different from the semantic context.
2437 New->setLexicalDeclContext(CurContext);
2438
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002439 return New;
2440}
2441
2442
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002443/// Collect the instance variables declared in an Objective-C object. Used in
2444/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002445static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002446 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002447 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002448 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2449
2450 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002451 for (ObjCInterfaceDecl::ivar_iterator
2452 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2453
Ted Kremenek01e67792008-08-20 03:26:33 +00002454 ObjCIvarDecl* ID = *I;
2455 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2456 ID->getIdentifier(),
2457 ID->getType(),
2458 ID->getBitWidth()));
2459 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002460}
2461
2462/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2463/// instance variables of ClassName into Decls.
2464void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2465 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002466 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002467 // Check that ClassName is a valid class
2468 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2469 if (!Class) {
2470 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2471 return;
2472 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002473 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002474 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002475}
2476
Chris Lattner1d353ba2008-11-12 21:17:48 +00002477/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2478/// types into constant array types in certain situations which would otherwise
2479/// be errors (for GCC compatibility).
2480static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2481 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002482 // This method tries to turn a variable array into a constant
2483 // array even when the size isn't an ICE. This is necessary
2484 // for compatibility with code that depends on gcc's buggy
2485 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002486 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2487 if (!VLATy) return QualType();
2488
2489 APValue Result;
2490 if (!VLATy->getSizeExpr() ||
2491 !VLATy->getSizeExpr()->tryEvaluate(Result, Context))
2492 return QualType();
2493
2494 assert(Result.isInt() && "Size expressions must be integers!");
2495 llvm::APSInt &Res = Result.getInt();
2496 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2497 return Context.getConstantArrayType(VLATy->getElementType(),
2498 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002499 return QualType();
2500}
2501
Steve Naroff08d92e42007-09-15 18:49:24 +00002502/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002503/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002504Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002505 SourceLocation DeclStart,
2506 Declarator &D, ExprTy *BitfieldWidth) {
2507 IdentifierInfo *II = D.getIdentifier();
2508 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002509 SourceLocation Loc = DeclStart;
2510 if (II) Loc = D.getIdentifierLoc();
2511
2512 // FIXME: Unnamed fields can be handled in various different ways, for
2513 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002514
Reid Spencer5f016e22007-07-11 17:01:13 +00002515 if (BitWidth) {
2516 // TODO: Validate.
2517 //printf("WARNING: BITFIELDS IGNORED!\n");
2518
2519 // 6.7.2.1p3
2520 // 6.7.2.1p4
2521
2522 } else {
2523 // Not a bitfield.
2524
2525 // validate II.
2526
2527 }
2528
2529 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002530 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2531 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002532
Reid Spencer5f016e22007-07-11 17:01:13 +00002533 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2534 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002535 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002536 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002537 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002538 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002539 T = FixedTy;
2540 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002541 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002542 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002543 InvalidDecl = true;
2544 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002545 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002546 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002547 FieldDecl *NewFD;
2548
2549 if (getLangOptions().CPlusPlus) {
2550 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2551 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2552 Loc, II, T, BitWidth);
2553 if (II)
2554 PushOnScopeChains(NewFD, S);
2555 }
2556 else
2557 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002558
Chris Lattner3ff30c82008-06-29 00:02:00 +00002559 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002560
Steve Naroff5912a352007-08-28 20:14:24 +00002561 if (D.getInvalidType() || InvalidDecl)
2562 NewFD->setInvalidDecl();
2563 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002564}
2565
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002566/// TranslateIvarVisibility - Translate visibility from a token ID to an
2567/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002568static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002569TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002570 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002571 default: assert(0 && "Unknown visitibility kind");
2572 case tok::objc_private: return ObjCIvarDecl::Private;
2573 case tok::objc_public: return ObjCIvarDecl::Public;
2574 case tok::objc_protected: return ObjCIvarDecl::Protected;
2575 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002576 }
2577}
2578
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002579/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2580/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002581Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002582 SourceLocation DeclStart,
2583 Declarator &D, ExprTy *BitfieldWidth,
2584 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002585 IdentifierInfo *II = D.getIdentifier();
2586 Expr *BitWidth = (Expr*)BitfieldWidth;
2587 SourceLocation Loc = DeclStart;
2588 if (II) Loc = D.getIdentifierLoc();
2589
2590 // FIXME: Unnamed fields can be handled in various different ways, for
2591 // example, unnamed unions inject all members into the struct namespace!
2592
2593
2594 if (BitWidth) {
2595 // TODO: Validate.
2596 //printf("WARNING: BITFIELDS IGNORED!\n");
2597
2598 // 6.7.2.1p3
2599 // 6.7.2.1p4
2600
2601 } else {
2602 // Not a bitfield.
2603
2604 // validate II.
2605
2606 }
2607
2608 QualType T = GetTypeForDeclarator(D, S);
2609 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2610 bool InvalidDecl = false;
2611
2612 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2613 // than a variably modified type.
2614 if (T->isVariablyModifiedType()) {
2615 // FIXME: This diagnostic needs work
2616 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2617 InvalidDecl = true;
2618 }
2619
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002620 // Get the visibility (access control) for this ivar.
2621 ObjCIvarDecl::AccessControl ac =
2622 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2623 : ObjCIvarDecl::None;
2624
2625 // Construct the decl.
2626 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002627 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002628
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002629 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002630 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002631
2632 if (D.getInvalidType() || InvalidDecl)
2633 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002634
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002635 return NewID;
2636}
2637
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002638void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002639 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002640 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002641 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002642 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002643 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2644 assert(EnclosingDecl && "missing record or interface decl");
2645 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2646
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002647 if (Record)
2648 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2649 // Diagnose code like:
2650 // struct S { struct S {} X; };
2651 // We discover this when we complete the outer S. Reject and ignore the
2652 // outer S.
2653 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2654 DefRecord->getKindName());
2655 Diag(RecLoc, diag::err_previous_definition);
2656 Record->setInvalidDecl();
2657 return;
2658 }
2659
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 // Verify that all the fields are okay.
2661 unsigned NumNamedMembers = 0;
2662 llvm::SmallVector<FieldDecl*, 32> RecFields;
2663 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002664
Reid Spencer5f016e22007-07-11 17:01:13 +00002665 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002666
Steve Naroff74216642007-09-14 22:20:54 +00002667 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2668 assert(FD && "missing field decl");
2669
2670 // Remember all fields.
2671 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002672
2673 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002674 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002675
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002677 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002678 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002679 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002680 FD->setInvalidDecl();
2681 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002682 continue;
2683 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002684 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2685 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002686 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002687 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002688 FD->setInvalidDecl();
2689 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002690 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002691 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002693 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002694 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002696 FD->setInvalidDecl();
2697 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002698 continue;
2699 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002700 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2702 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002703 FD->setInvalidDecl();
2704 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002705 continue;
2706 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002708 if (Record)
2709 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002710 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002711 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2712 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002713 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002714 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2715 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002716 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002717 Record->setHasFlexibleArrayMember(true);
2718 } else {
2719 // If this is a struct/class and this is not the last element, reject
2720 // it. Note that GCC supports variable sized arrays in the middle of
2721 // structures.
2722 if (i != NumFields-1) {
2723 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2724 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002725 FD->setInvalidDecl();
2726 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 continue;
2728 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002729 // We support flexible arrays at the end of structs in other structs
2730 // as an extension.
2731 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2732 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002733 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002734 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002735 }
2736 }
2737 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002738 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002739 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002740 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2741 FD->getName());
2742 FD->setInvalidDecl();
2743 EnclosingDecl->setInvalidDecl();
2744 continue;
2745 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 // Keep track of the number of named members.
2747 if (IdentifierInfo *II = FD->getIdentifier()) {
2748 // Detect duplicate member names.
2749 if (!FieldIDs.insert(II)) {
2750 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2751 // Find the previous decl.
2752 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002753 for (unsigned i = 0; ; ++i) {
2754 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002755 if (RecFields[i]->getIdentifier() == II) {
2756 PrevLoc = RecFields[i]->getLocation();
2757 break;
2758 }
2759 }
2760 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002761 FD->setInvalidDecl();
2762 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 continue;
2764 }
2765 ++NumNamedMembers;
2766 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 }
2768
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002770 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002771 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002772 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2773 // Sema::ActOnFinishCXXClassDef.
2774 if (!isa<CXXRecordDecl>(Record))
2775 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002776 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002777 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2778 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2779 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2780 else if (ObjCImplementationDecl *IMPDecl =
2781 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002782 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2783 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002784 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002785 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002786 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002787
2788 if (Attr)
2789 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002790}
2791
Steve Naroff08d92e42007-09-15 18:49:24 +00002792Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002793 DeclTy *lastEnumConst,
2794 SourceLocation IdLoc, IdentifierInfo *Id,
2795 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002796 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 EnumConstantDecl *LastEnumConst =
2798 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2799 Expr *Val = static_cast<Expr*>(val);
2800
Chris Lattner31e05722007-08-26 06:24:45 +00002801 // The scope passed in may not be a decl scope. Zip up the scope tree until
2802 // we find one that is.
2803 while ((S->getFlags() & Scope::DeclScope) == 0)
2804 S = S->getParent();
2805
Reid Spencer5f016e22007-07-11 17:01:13 +00002806 // Verify that there isn't already something declared with this name in this
2807 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002808 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002809 // When in C++, we may get a TagDecl with the same name; in this case the
2810 // enum constant will 'hide' the tag.
2811 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2812 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002813 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002814 if (isa<EnumConstantDecl>(PrevDecl))
2815 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2816 else
2817 Diag(IdLoc, diag::err_redefinition, Id->getName());
2818 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002819 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002820 return 0;
2821 }
2822 }
2823
2824 llvm::APSInt EnumVal(32);
2825 QualType EltTy;
2826 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002827 // Make sure to promote the operand type to int.
2828 UsualUnaryConversions(Val);
2829
Reid Spencer5f016e22007-07-11 17:01:13 +00002830 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2831 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002832 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002833 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2834 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002835 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002836 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002837 } else {
2838 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002839 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002840 }
2841
2842 if (!Val) {
2843 if (LastEnumConst) {
2844 // Assign the last value + 1.
2845 EnumVal = LastEnumConst->getInitVal();
2846 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002847
2848 // Check for overflow on increment.
2849 if (EnumVal < LastEnumConst->getInitVal())
2850 Diag(IdLoc, diag::warn_enum_value_overflow);
2851
Chris Lattnerb7416f92007-08-27 17:37:24 +00002852 EltTy = LastEnumConst->getType();
2853 } else {
2854 // First value, set to zero.
2855 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002856 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002857 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002858 }
2859
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002860 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002861 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2862 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002863 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002864
2865 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002866 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002867 return New;
2868}
2869
Steve Naroff02408c62008-08-07 14:08:16 +00002870// FIXME: For consistency with ActOnFields(), we should have the parser
2871// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002872void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002873 DeclTy **Elements, unsigned NumElements) {
2874 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002875
Steve Naroff02408c62008-08-07 14:08:16 +00002876 if (Enum && Enum->isDefinition()) {
2877 // Diagnose code like:
2878 // enum e0 {
2879 // E0 = sizeof(enum e0 { E1 })
2880 // };
2881 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2882 Enum->getName());
2883 Diag(EnumLoc, diag::err_previous_definition);
2884 Enum->setInvalidDecl();
2885 return;
2886 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002887 // TODO: If the result value doesn't fit in an int, it must be a long or long
2888 // long value. ISO C does not support this, but GCC does as an extension,
2889 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002890 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002891
Chris Lattnerac609682007-08-28 06:15:15 +00002892 // Verify that all the values are okay, compute the size of the values, and
2893 // reverse the list.
2894 unsigned NumNegativeBits = 0;
2895 unsigned NumPositiveBits = 0;
2896
2897 // Keep track of whether all elements have type int.
2898 bool AllElementsInt = true;
2899
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 EnumConstantDecl *EltList = 0;
2901 for (unsigned i = 0; i != NumElements; ++i) {
2902 EnumConstantDecl *ECD =
2903 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2904 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002905
2906 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002907 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002908 assert(InitVal.getBitWidth() >= IntWidth &&
2909 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002910 if (InitVal.getBitWidth() > IntWidth) {
2911 llvm::APSInt V(InitVal);
2912 V.trunc(IntWidth);
2913 V.extend(InitVal.getBitWidth());
2914 if (V != InitVal)
2915 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002916 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002917 }
Chris Lattnerac609682007-08-28 06:15:15 +00002918
2919 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002920 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002921 NumPositiveBits = std::max(NumPositiveBits,
2922 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002923 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002924 NumNegativeBits = std::max(NumNegativeBits,
2925 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002926
Chris Lattnerac609682007-08-28 06:15:15 +00002927 // Keep track of whether every enum element has type int (very commmon).
2928 if (AllElementsInt)
2929 AllElementsInt = ECD->getType() == Context.IntTy;
2930
Reid Spencer5f016e22007-07-11 17:01:13 +00002931 ECD->setNextDeclarator(EltList);
2932 EltList = ECD;
2933 }
2934
Chris Lattnerac609682007-08-28 06:15:15 +00002935 // Figure out the type that should be used for this enum.
2936 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2937 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002938 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002939
2940 if (NumNegativeBits) {
2941 // If there is a negative value, figure out the smallest integer type (of
2942 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002943 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002944 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002945 BestWidth = IntWidth;
2946 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002947 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002948
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002949 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002950 BestType = Context.LongTy;
2951 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002952 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002953
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002954 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002955 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2956 BestType = Context.LongLongTy;
2957 }
2958 }
2959 } else {
2960 // If there is no negative value, figure out which of uint, ulong, ulonglong
2961 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002962 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002963 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002964 BestWidth = IntWidth;
2965 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002966 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002967 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002968 } else {
2969 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002970 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002971 "How could an initializer get larger than ULL?");
2972 BestType = Context.UnsignedLongLongTy;
2973 }
2974 }
2975
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002976 // Loop over all of the enumerator constants, changing their types to match
2977 // the type of the enum if needed.
2978 for (unsigned i = 0; i != NumElements; ++i) {
2979 EnumConstantDecl *ECD =
2980 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2981 if (!ECD) continue; // Already issued a diagnostic.
2982
2983 // Standard C says the enumerators have int type, but we allow, as an
2984 // extension, the enumerators to be larger than int size. If each
2985 // enumerator value fits in an int, type it as an int, otherwise type it the
2986 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2987 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002988 if (ECD->getType() == Context.IntTy) {
2989 // Make sure the init value is signed.
2990 llvm::APSInt IV = ECD->getInitVal();
2991 IV.setIsSigned(true);
2992 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002993 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002994 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002995
2996 // Determine whether the value fits into an int.
2997 llvm::APSInt InitVal = ECD->getInitVal();
2998 bool FitsInInt;
2999 if (InitVal.isUnsigned() || !InitVal.isNegative())
3000 FitsInInt = InitVal.getActiveBits() < IntWidth;
3001 else
3002 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3003
3004 // If it fits into an integer type, force it. Otherwise force it to match
3005 // the enum decl type.
3006 QualType NewTy;
3007 unsigned NewWidth;
3008 bool NewSign;
3009 if (FitsInInt) {
3010 NewTy = Context.IntTy;
3011 NewWidth = IntWidth;
3012 NewSign = true;
3013 } else if (ECD->getType() == BestType) {
3014 // Already the right type!
3015 continue;
3016 } else {
3017 NewTy = BestType;
3018 NewWidth = BestWidth;
3019 NewSign = BestType->isSignedIntegerType();
3020 }
3021
3022 // Adjust the APSInt value.
3023 InitVal.extOrTrunc(NewWidth);
3024 InitVal.setIsSigned(NewSign);
3025 ECD->setInitVal(InitVal);
3026
3027 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003028 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3029 /*isLvalue=*/false));
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003030 ECD->setType(NewTy);
3031 }
Chris Lattnerac609682007-08-28 06:15:15 +00003032
Chris Lattnere00b18c2007-08-28 18:24:31 +00003033 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003034 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003035}
3036
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003037Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3038 ExprTy *expr) {
3039 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3040
Chris Lattner8e25d862008-03-16 00:16:02 +00003041 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003042}
3043
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003044Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003045 SourceLocation LBrace,
3046 SourceLocation RBrace,
3047 const char *Lang,
3048 unsigned StrSize,
3049 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003050 LinkageSpecDecl::LanguageIDs Language;
3051 Decl *dcl = static_cast<Decl *>(D);
3052 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3053 Language = LinkageSpecDecl::lang_c;
3054 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3055 Language = LinkageSpecDecl::lang_cxx;
3056 else {
3057 Diag(Loc, diag::err_bad_language);
3058 return 0;
3059 }
3060
3061 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003062 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003063}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003064
3065void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3066 ExprTy *alignment, SourceLocation PragmaLoc,
3067 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3068 Expr *Alignment = static_cast<Expr *>(alignment);
3069
3070 // If specified then alignment must be a "small" power of two.
3071 unsigned AlignmentVal = 0;
3072 if (Alignment) {
3073 llvm::APSInt Val;
3074 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3075 !Val.isPowerOf2() ||
3076 Val.getZExtValue() > 16) {
3077 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3078 delete Alignment;
3079 return; // Ignore
3080 }
3081
3082 AlignmentVal = (unsigned) Val.getZExtValue();
3083 }
3084
3085 switch (Kind) {
3086 case Action::PPK_Default: // pack([n])
3087 PackContext.setAlignment(AlignmentVal);
3088 break;
3089
3090 case Action::PPK_Show: // pack(show)
3091 // Show the current alignment, making sure to show the right value
3092 // for the default.
3093 AlignmentVal = PackContext.getAlignment();
3094 // FIXME: This should come from the target.
3095 if (AlignmentVal == 0)
3096 AlignmentVal = 8;
3097 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
3098 break;
3099
3100 case Action::PPK_Push: // pack(push [, id] [, [n])
3101 PackContext.push(Name);
3102 // Set the new alignment if specified.
3103 if (Alignment)
3104 PackContext.setAlignment(AlignmentVal);
3105 break;
3106
3107 case Action::PPK_Pop: // pack(pop [, id] [, n])
3108 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3109 // "#pragma pack(pop, identifier, n) is undefined"
3110 if (Alignment && Name)
3111 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3112
3113 // Do the pop.
3114 if (!PackContext.pop(Name)) {
3115 // If a name was specified then failure indicates the name
3116 // wasn't found. Otherwise failure indicates the stack was
3117 // empty.
3118 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3119 Name ? "no record matching name" : "stack empty");
3120
3121 // FIXME: Warn about popping named records as MSVC does.
3122 } else {
3123 // Pop succeeded, set the new alignment if specified.
3124 if (Alignment)
3125 PackContext.setAlignment(AlignmentVal);
3126 }
3127 break;
3128
3129 default:
3130 assert(0 && "Invalid #pragma pack kind.");
3131 }
3132}
3133
3134bool PragmaPackStack::pop(IdentifierInfo *Name) {
3135 if (Stack.empty())
3136 return false;
3137
3138 // If name is empty just pop top.
3139 if (!Name) {
3140 Alignment = Stack.back().first;
3141 Stack.pop_back();
3142 return true;
3143 }
3144
3145 // Otherwise, find the named record.
3146 for (unsigned i = Stack.size(); i != 0; ) {
3147 --i;
3148 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3149 // Found it, pop up to and including this record.
3150 Alignment = Stack[i].first;
3151 Stack.erase(Stack.begin() + i, Stack.end());
3152 return true;
3153 }
3154 }
3155
3156 return false;
3157}