blob: cae05a365c089d1a2abcac9722e076da542c8741 [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
Douglas Gregor2f1bc522008-11-07 20:08:42 +000048std::string Sema::getTypeAsString(TypeTy *Type) {
49 QualType Ty = QualType::getFromOpaquePtr(Type);
50 return Ty.getAsString();
51}
52
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000053DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000054 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000055 // A C++ out-of-line method will return to the file declaration context.
56 if (!MD->isInlineDefinition())
57 return LexicalFileContext;
58
59 // A C++ inline method is parsed *after* the topmost class it was declared in
60 // is fully parsed (it's "complete").
61 // The parsing of a C++ inline method happens at the declaration context of
62 // the topmost (non-nested) class it is declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000063 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
64 DC = MD->getParent();
65 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
66 DC = RD;
67
68 // Return the declaration context of the topmost class the inline method is
69 // declared in.
70 return DC;
71 }
72
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000073 if (isa<FunctionDecl>(DC) || isa<ObjCMethodDecl>(DC))
74 return LexicalFileContext;
75
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000076 return DC->getParent();
77}
78
Chris Lattner9fdf9c62008-04-22 18:39:57 +000079void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000080 assert(getContainingDC(DC) == CurContext &&
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000081 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000082 CurContext = DC;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000083 if (CurContext->isFileContext())
84 LexicalFileContext = CurContext;
Chris Lattner0ed844b2008-04-04 06:12:32 +000085}
86
Chris Lattnerb048c982008-04-06 04:47:34 +000087void Sema::PopDeclContext() {
88 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000089 CurContext = getContainingDC(CurContext);
90 if (CurContext->isFileContext())
91 LexicalFileContext = CurContext;
Chris Lattner0ed844b2008-04-04 06:12:32 +000092}
93
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094/// Add this decl to the scope shadowed decl chains.
95void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000096 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000097
98 // C++ [basic.scope]p4:
99 // -- exactly one declaration shall declare a class name or
100 // enumeration name that is not a typedef name and the other
101 // declarations shall all refer to the same object or
102 // enumerator, or all refer to functions and function templates;
103 // in this case the class name or enumeration name is hidden.
104 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
105 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000106 IdentifierResolver::iterator
107 I = IdResolver.begin(TD->getIdentifier(),
108 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000109 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000110 // There is already a declaration with the same name in the same
111 // scope. It must be found before we find the new declaration,
112 // so swap the order on the shadowed declaration chain.
113
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000114 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000115 return;
116 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000117 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
118 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000119 // We are pushing the name of a function, which might be an
120 // overloaded name.
121 IdentifierResolver::iterator
122 I = IdResolver.begin(FD->getIdentifier(),
123 FD->getDeclContext(), false/*LookInParentCtx*/);
124 if (I != IdResolver.end() &&
125 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
126 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
127 // There is already a declaration with the same name in the same
128 // scope. It must be a function or an overloaded function.
129 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
130 if (!Ovl) {
131 // We haven't yet overloaded this function. Take the existing
132 // FunctionDecl and put it into an OverloadedFunctionDecl.
133 Ovl = OverloadedFunctionDecl::Create(Context,
134 FD->getDeclContext(),
135 FD->getIdentifier());
136 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
137
138 // Remove the name binding to the existing FunctionDecl...
139 IdResolver.RemoveDecl(*I);
140
141 // ... and put the OverloadedFunctionDecl in its place.
142 IdResolver.AddDecl(Ovl);
143 }
144
145 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
146 // to its list of overloads.
147 Ovl->addOverload(FD);
148
149 return;
150 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000151 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000152
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000153 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000154}
155
Steve Naroffb216c882007-10-09 22:01:59 +0000156void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000157 if (S->decl_empty()) return;
158 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000159
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
161 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000162 Decl *TmpD = static_cast<Decl*>(*I);
163 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000164
165 if (isa<CXXFieldDecl>(TmpD)) continue;
166
167 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
168 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000169
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 IdentifierInfo *II = D->getIdentifier();
171 if (!II) continue;
172
Ted Kremeneka89d1972008-09-03 18:03:35 +0000173 // We only want to remove the decls from the identifier decl chains for
174 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000175 if (S->getFnParent() != 0)
176 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000177
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000178 // Chain this decl to the containing DeclContext.
179 D->setNext(CurContext->getDeclChain());
180 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000181 }
182}
183
Steve Naroffe8043c32008-04-01 23:04:06 +0000184/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
185/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000186ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000187 // The third "scope" argument is 0 since we aren't enabling lazy built-in
188 // creation from this context.
189 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000190
Steve Naroffb327ce02008-04-02 14:35:35 +0000191 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000192}
193
Steve Naroffe8043c32008-04-01 23:04:06 +0000194/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000195/// namespace.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000196Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI, Scope *S,
197 DeclContext *LookupCtx, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000199 unsigned NS = NSI;
200 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
201 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000202
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000203 IdentifierResolver::iterator
204 I = LookupCtx ? IdResolver.begin(II, LookupCtx, false/*LookInParentCtx*/) :
205 IdResolver.begin(II, CurContext, true/*LookInParentCtx*/);
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 // Scan up the scope chain looking for a decl that matches this identifier
207 // that is in the appropriate namespace. This search should not take long, as
208 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000209 for (; I != IdResolver.end(); ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000210 if ((*I)->getIdentifierNamespace() & NS)
211 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000212
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 // If we didn't find a use of this identifier, and if the identifier
214 // corresponds to a compiler builtin, create the decl object for the builtin
215 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000216 if (NS & Decl::IDNS_Ordinary) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000217 if (enableLazyBuiltinCreation &&
218 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000219 // If this is a builtin on this (or all) targets, create the decl.
220 if (unsigned BuiltinID = II->getBuiltinID())
221 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
222 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000223 if (getLangOptions().ObjC1) {
224 // @interface and @compatibility_alias introduce typedef-like names.
225 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000226 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000227 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000228 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
229 if (IDI != ObjCInterfaceDecls.end())
230 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000231 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
232 if (I != ObjCAliasDecls.end())
233 return I->second->getClassInterface();
234 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000235 }
236 return 0;
237}
238
Chris Lattner95e2c712008-05-05 22:18:14 +0000239void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000240 if (!Context.getBuiltinVaListType().isNull())
241 return;
242
243 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000244 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000245 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000246 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
247}
248
Reid Spencer5f016e22007-07-11 17:01:13 +0000249/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
250/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000251ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
252 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000253 Builtin::ID BID = (Builtin::ID)bid;
254
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000255 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000256 InitBuiltinVaListType();
257
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000258 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000259 FunctionDecl *New = FunctionDecl::Create(Context,
260 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000261 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000262 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000263
Chris Lattner95e2c712008-05-05 22:18:14 +0000264 // Create Decl objects for each parameter, adding them to the
265 // FunctionDecl.
266 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
267 llvm::SmallVector<ParmVarDecl*, 16> Params;
268 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
269 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
270 FT->getArgType(i), VarDecl::None, 0,
271 0));
272 New->setParams(&Params[0], Params.size());
273 }
274
275
276
Chris Lattner7f925cc2008-04-11 07:00:53 +0000277 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000278 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000279 return New;
280}
281
282/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
283/// and scope as a previous declaration 'Old'. Figure out how to resolve this
284/// situation, merging decls or emitting diagnostics as appropriate.
285///
Steve Naroffe8043c32008-04-01 23:04:06 +0000286TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000287 // Allow multiple definitions for ObjC built-in typedefs.
288 // FIXME: Verify the underlying types are equivalent!
289 if (getLangOptions().ObjC1) {
290 const IdentifierInfo *typeIdent = New->getIdentifier();
291 if (typeIdent == Ident_id) {
292 Context.setObjCIdType(New);
293 return New;
294 } else if (typeIdent == Ident_Class) {
295 Context.setObjCClassType(New);
296 return New;
297 } else if (typeIdent == Ident_SEL) {
298 Context.setObjCSelType(New);
299 return New;
300 } else if (typeIdent == Ident_Protocol) {
301 Context.setObjCProtoType(New->getUnderlyingType());
302 return New;
303 }
304 // Fall through - the typedef name was not a builtin type.
305 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 // Verify the old decl was also a typedef.
307 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
308 if (!Old) {
309 Diag(New->getLocation(), diag::err_redefinition_different_kind,
310 New->getName());
311 Diag(OldD->getLocation(), diag::err_previous_definition);
312 return New;
313 }
314
Chris Lattner99cb9972008-07-25 18:44:27 +0000315 // If the typedef types are not identical, reject them in all languages and
316 // with any extensions enabled.
317 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
318 Context.getCanonicalType(Old->getUnderlyingType()) !=
319 Context.getCanonicalType(New->getUnderlyingType())) {
320 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
321 New->getUnderlyingType().getAsString(),
322 Old->getUnderlyingType().getAsString());
323 Diag(Old->getLocation(), diag::err_previous_definition);
324 return Old;
325 }
326
Eli Friedman54ecfce2008-06-11 06:20:39 +0000327 if (getLangOptions().Microsoft) return New;
328
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000329 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
330 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
331 // *either* declaration is in a system header. The code below implements
332 // this adhoc compatibility rule. FIXME: The following code will not
333 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000334 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
335 SourceManager &SrcMgr = Context.getSourceManager();
336 if (SrcMgr.isInSystemHeader(Old->getLocation()))
337 return New;
338 if (SrcMgr.isInSystemHeader(New->getLocation()))
339 return New;
340 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000341
Ted Kremenek2d05c082008-05-23 21:28:18 +0000342 Diag(New->getLocation(), diag::err_redefinition, New->getName());
343 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000344 return New;
345}
346
Chris Lattner6b6b5372008-06-26 18:38:35 +0000347/// DeclhasAttr - returns true if decl Declaration already has the target
348/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000349static bool DeclHasAttr(const Decl *decl, const Attr *target) {
350 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
351 if (attr->getKind() == target->getKind())
352 return true;
353
354 return false;
355}
356
357/// MergeAttributes - append attributes from the Old decl to the New one.
358static void MergeAttributes(Decl *New, Decl *Old) {
359 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
360
Chris Lattnerddee4232008-03-03 03:28:21 +0000361 while (attr) {
362 tmp = attr;
363 attr = attr->getNext();
364
365 if (!DeclHasAttr(New, tmp)) {
366 New->addAttr(tmp);
367 } else {
368 tmp->setNext(0);
369 delete(tmp);
370 }
371 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000372
373 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000374}
375
Chris Lattner04421082008-04-08 04:40:51 +0000376/// MergeFunctionDecl - We just parsed a function 'New' from
377/// declarator D which has the same name and scope as a previous
378/// declaration 'Old'. Figure out how to resolve this situation,
379/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000380/// Redeclaration will be set true if this New is a redeclaration OldD.
381///
382/// In C++, New and Old must be declarations that are not
383/// overloaded. Use IsOverload to determine whether New and Old are
384/// overloaded, and to select the Old declaration that New should be
385/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000386FunctionDecl *
387Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000388 assert(!isa<OverloadedFunctionDecl>(OldD) &&
389 "Cannot merge with an overloaded function declaration");
390
Douglas Gregorf0097952008-04-21 02:02:58 +0000391 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000392 // Verify the old decl was also a function.
393 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
394 if (!Old) {
395 Diag(New->getLocation(), diag::err_redefinition_different_kind,
396 New->getName());
397 Diag(OldD->getLocation(), diag::err_previous_definition);
398 return New;
399 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000400
401 // Determine whether the previous declaration was a definition,
402 // implicit declaration, or a declaration.
403 diag::kind PrevDiag;
404 if (Old->isThisDeclarationADefinition())
405 PrevDiag = diag::err_previous_definition;
406 else if (Old->isImplicit())
407 PrevDiag = diag::err_previous_implicit_declaration;
408 else
409 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000410
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000411 QualType OldQType = Context.getCanonicalType(Old->getType());
412 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000413
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000414 if (getLangOptions().CPlusPlus) {
415 // (C++98 13.1p2):
416 // Certain function declarations cannot be overloaded:
417 // -- Function declarations that differ only in the return type
418 // cannot be overloaded.
419 QualType OldReturnType
420 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
421 QualType NewReturnType
422 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
423 if (OldReturnType != NewReturnType) {
424 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
425 Diag(Old->getLocation(), PrevDiag);
426 return New;
427 }
428
429 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
430 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
431 if (OldMethod && NewMethod) {
432 // -- Member function declarations with the same name and the
433 // same parameter types cannot be overloaded if any of them
434 // is a static member function declaration.
435 if (OldMethod->isStatic() || NewMethod->isStatic()) {
436 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
437 Diag(Old->getLocation(), PrevDiag);
438 return New;
439 }
440 }
441
442 // (C++98 8.3.5p3):
443 // All declarations for a function shall agree exactly in both the
444 // return type and the parameter-type-list.
445 if (OldQType == NewQType) {
446 // We have a redeclaration.
447 MergeAttributes(New, Old);
448 Redeclaration = true;
449 return MergeCXXFunctionDecl(New, Old);
450 }
451
452 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000453 }
Chris Lattner04421082008-04-08 04:40:51 +0000454
455 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000456 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000457 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000458 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000459 MergeAttributes(New, Old);
460 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000461 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000462 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000463
Steve Naroff837618c2008-01-16 15:01:34 +0000464 // A function that has already been declared has been redeclared or defined
465 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000466
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
468 // TODO: This is totally simplistic. It should handle merging functions
469 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000470 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
471 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000472 return New;
473}
474
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000475/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000476static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000477 if (VD->isFileVarDecl())
478 return (!VD->getInit() &&
479 (VD->getStorageClass() == VarDecl::None ||
480 VD->getStorageClass() == VarDecl::Static));
481 return false;
482}
483
484/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
485/// when dealing with C "tentative" external object definitions (C99 6.9.2).
486void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
487 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000488 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000489
490 for (IdentifierResolver::iterator
491 I = IdResolver.begin(VD->getIdentifier(),
492 VD->getDeclContext(), false/*LookInParentCtx*/),
493 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000494 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000495 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
496
Steve Narofff855e6f2008-08-10 15:20:13 +0000497 // Handle the following case:
498 // int a[10];
499 // int a[]; - the code below makes sure we set the correct type.
500 // int a[11]; - this is an error, size isn't 10.
501 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
502 OldDecl->getType()->isConstantArrayType())
503 VD->setType(OldDecl->getType());
504
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000505 // Check for "tentative" definitions. We can't accomplish this in
506 // MergeVarDecl since the initializer hasn't been attached.
507 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
508 continue;
509
510 // Handle __private_extern__ just like extern.
511 if (OldDecl->getStorageClass() != VarDecl::Extern &&
512 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
513 VD->getStorageClass() != VarDecl::Extern &&
514 VD->getStorageClass() != VarDecl::PrivateExtern) {
515 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
516 Diag(OldDecl->getLocation(), diag::err_previous_definition);
517 }
518 }
519 }
520}
521
Reid Spencer5f016e22007-07-11 17:01:13 +0000522/// MergeVarDecl - We just parsed a variable 'New' which has the same name
523/// and scope as a previous declaration 'Old'. Figure out how to resolve this
524/// situation, merging decls or emitting diagnostics as appropriate.
525///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000526/// Tentative definition rules (C99 6.9.2p2) are checked by
527/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
528/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000529///
Steve Naroffe8043c32008-04-01 23:04:06 +0000530VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 // Verify the old decl was also a variable.
532 VarDecl *Old = dyn_cast<VarDecl>(OldD);
533 if (!Old) {
534 Diag(New->getLocation(), diag::err_redefinition_different_kind,
535 New->getName());
536 Diag(OldD->getLocation(), diag::err_previous_definition);
537 return New;
538 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000539
540 MergeAttributes(New, Old);
541
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000543 QualType OldCType = Context.getCanonicalType(Old->getType());
544 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000545 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000546 Diag(New->getLocation(), diag::err_redefinition, New->getName());
547 Diag(Old->getLocation(), diag::err_previous_definition);
548 return New;
549 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000550 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
551 if (New->getStorageClass() == VarDecl::Static &&
552 (Old->getStorageClass() == VarDecl::None ||
553 Old->getStorageClass() == VarDecl::Extern)) {
554 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
555 Diag(Old->getLocation(), diag::err_previous_definition);
556 return New;
557 }
558 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
559 if (New->getStorageClass() != VarDecl::Static &&
560 Old->getStorageClass() == VarDecl::Static) {
561 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
562 Diag(Old->getLocation(), diag::err_previous_definition);
563 return New;
564 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000565 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
566 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 Diag(New->getLocation(), diag::err_redefinition, New->getName());
568 Diag(Old->getLocation(), diag::err_previous_definition);
569 }
570 return New;
571}
572
Chris Lattner04421082008-04-08 04:40:51 +0000573/// CheckParmsForFunctionDef - Check that the parameters of the given
574/// function are appropriate for the definition of a function. This
575/// takes care of any checks that cannot be performed on the
576/// declaration itself, e.g., that the types of each of the function
577/// parameters are complete.
578bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
579 bool HasInvalidParm = false;
580 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
581 ParmVarDecl *Param = FD->getParamDecl(p);
582
583 // C99 6.7.5.3p4: the parameters in a parameter type list in a
584 // function declarator that is part of a function definition of
585 // that function shall not have incomplete type.
586 if (Param->getType()->isIncompleteType() &&
587 !Param->isInvalidDecl()) {
588 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
589 Param->getType().getAsString());
590 Param->setInvalidDecl();
591 HasInvalidParm = true;
592 }
593 }
594
595 return HasInvalidParm;
596}
597
Reid Spencer5f016e22007-07-11 17:01:13 +0000598/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
599/// no declarator (e.g. "struct foo;") is parsed.
600Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
601 // TODO: emit error on 'int;' or 'const enum foo;'.
602 // TODO: emit error on 'typedef int;'
603 // if (!DS.isMissingDeclaratorOk()) Diag(...);
604
Steve Naroff92199282007-11-17 21:37:36 +0000605 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000606}
607
Steve Naroffd0091aa2008-01-10 22:15:12 +0000608bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000609 // Get the type before calling CheckSingleAssignmentConstraints(), since
610 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000611 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000612
Chris Lattner5cf216b2008-01-04 18:04:52 +0000613 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
614 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
615 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000616}
617
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000618bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000619 const ArrayType *AT = Context.getAsArrayType(DeclT);
620
621 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000622 // C99 6.7.8p14. We have an array of character type with unknown size
623 // being initialized to a string literal.
624 llvm::APSInt ConstVal(32);
625 ConstVal = strLiteral->getByteLength() + 1;
626 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000627 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000628 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000629 } else {
630 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000631 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000632 // FIXME: Avoid truncation for 64-bit length strings.
633 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000634 Diag(strLiteral->getSourceRange().getBegin(),
635 diag::warn_initializer_string_for_char_array_too_long,
636 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000637 }
638 // Set type from "char *" to "constant array of char".
639 strLiteral->setType(DeclT);
640 // For now, we always return false (meaning success).
641 return false;
642}
643
644StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000645 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000646 if (AT && AT->getElementType()->isCharType()) {
647 return dyn_cast<StringLiteral>(Init);
648 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000649 return 0;
650}
651
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000652bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
653 SourceLocation InitLoc,
654 std::string InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000655 // C++ [dcl.init.ref]p1:
656 // A variable declared to be a T&, that is “reference to type T”
657 // (8.3.2), shall be initialized by an object, or function, of
658 // type T or by an object that can be converted into a T.
659 if (DeclType->isReferenceType())
660 return CheckReferenceInit(Init, DeclType);
661
Steve Naroffca107302008-01-21 23:53:58 +0000662 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
663 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000664 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000665 return Diag(InitLoc,
Steve Naroffca107302008-01-21 23:53:58 +0000666 diag::err_variable_object_no_init,
667 VAT->getSizeExpr()->getSourceRange());
668
Steve Naroff2fdc3742007-12-10 22:44:33 +0000669 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
670 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000671 // FIXME: Handle wide strings
672 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
673 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000674
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000675 // C++ [dcl.init]p14:
676 // -- If the destination type is a (possibly cv-qualified) class
677 // type:
678 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
679 QualType DeclTypeC = Context.getCanonicalType(DeclType);
680 QualType InitTypeC = Context.getCanonicalType(Init->getType());
681
682 // -- If the initialization is direct-initialization, or if it is
683 // copy-initialization where the cv-unqualified version of the
684 // source type is the same class as, or a derived class of, the
685 // class of the destination, constructors are considered.
686 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
687 IsDerivedFrom(InitTypeC, DeclTypeC)) {
688 CXXConstructorDecl *Constructor
689 = PerformInitializationByConstructor(DeclType, &Init, 1,
690 InitLoc, Init->getSourceRange(),
691 InitEntity, IK_Copy);
692 return Constructor == 0;
693 }
694
695 // -- Otherwise (i.e., for the remaining copy-initialization
696 // cases), user-defined conversion sequences that can
697 // convert from the source type to the destination type or
698 // (when a conversion function is used) to a derived class
699 // thereof are enumerated as described in 13.3.1.4, and the
700 // best one is chosen through overload resolution
701 // (13.3). If the conversion cannot be done or is
702 // ambiguous, the initialization is ill-formed. The
703 // function selected is called with the initializer
704 // expression as its argument; if the function is a
705 // constructor, the call initializes a temporary of the
706 // destination type.
707 // FIXME: We're pretending to do copy elision here; return to
708 // this when we have ASTs for such things.
709 if (PerformImplicitConversion(Init, DeclType))
710 return Diag(InitLoc,
711 diag::err_typecheck_convert_incompatible,
712 DeclType.getAsString(), InitEntity,
713 "initializing",
714 Init->getSourceRange());
715 else
716 return false;
717 }
718
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000719 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000720 if (DeclType->isArrayType())
721 return Diag(Init->getLocStart(),
722 diag::err_array_init_list_required,
723 Init->getSourceRange());
724
Steve Naroffd0091aa2008-01-10 22:15:12 +0000725 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000726 } else if (getLangOptions().CPlusPlus) {
727 // C++ [dcl.init]p14:
728 // [...] If the class is an aggregate (8.5.1), and the initializer
729 // is a brace-enclosed list, see 8.5.1.
730 //
731 // Note: 8.5.1 is handled below; here, we diagnose the case where
732 // we have an initializer list and a destination type that is not
733 // an aggregate.
734 // FIXME: In C++0x, this is yet another form of initialization.
735 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
736 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
737 if (!ClassDecl->isAggregate())
738 return Diag(InitLoc,
739 diag::err_init_non_aggr_init_list,
740 DeclType.getAsString(),
741 Init->getSourceRange());
742 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000743 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000744
Steve Naroff0cca7492008-05-01 22:18:59 +0000745 InitListChecker CheckInitList(this, InitList, DeclType);
746 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000747}
748
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000749Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000750Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000751 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 IdentifierInfo *II = D.getIdentifier();
753
Chris Lattnere80a59c2007-07-25 00:24:17 +0000754 // All of these full declarators require an identifier. If it doesn't have
755 // one, the ParsedFreeStandingDeclSpec action should be used.
756 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000757 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000758 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000759 D.getDeclSpec().getSourceRange(), D.getSourceRange());
760 return 0;
761 }
762
Chris Lattner31e05722007-08-26 06:24:45 +0000763 // The scope passed in may not be a decl scope. Zip up the scope tree until
764 // we find one that is.
765 while ((S->getFlags() & Scope::DeclScope) == 0)
766 S = S->getParent();
767
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000768 DeclContext *DC;
769 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000770 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000771 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000772
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000773 // See if this is a redefinition of a variable in the same scope.
774 if (!D.getCXXScopeSpec().isSet()) {
775 DC = CurContext;
776 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
777 } else { // Something like "int foo::x;"
778 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
779 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S, DC);
780
781 // C++ 7.3.1.2p2:
782 // Members (including explicit specializations of templates) of a named
783 // namespace can also be defined outside that namespace by explicit
784 // qualification of the name being defined, provided that the entity being
785 // defined was already declared in the namespace and the definition appears
786 // after the point of declaration in a namespace that encloses the
787 // declarations namespace.
788 //
789 if (PrevDecl == 0) {
790 // No previous declaration in the qualifying scope.
791 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
792 II->getName(), D.getCXXScopeSpec().getRange());
793 } else if (!CurContext->Encloses(DC)) {
794 // The qualifying scope doesn't enclose the original declaration.
795 // Emit diagnostic based on current scope.
796 SourceLocation L = D.getIdentifierLoc();
797 SourceRange R = D.getCXXScopeSpec().getRange();
798 if (isa<FunctionDecl>(CurContext)) {
799 Diag(L, diag::err_invalid_declarator_in_function, II->getName(), R);
800 } else {
801 Diag(L, diag::err_invalid_declarator_scope, II->getName(),
802 cast<NamedDecl>(DC)->getName(), R);
803 }
804 }
805 }
806
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000807 // In C++, the previous declaration we find might be a tag type
808 // (class or enum). In this case, the new declaration will hide the
809 // tag type.
810 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
811 PrevDecl = 0;
812
Chris Lattner41af0932007-11-14 06:34:38 +0000813 QualType R = GetTypeForDeclarator(D, S);
814 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
815
Reid Spencer5f016e22007-07-11 17:01:13 +0000816 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000817 // Check that there are no default arguments (C++ only).
818 if (getLangOptions().CPlusPlus)
819 CheckExtraCXXDefaultArguments(D);
820
Chris Lattner41af0932007-11-14 06:34:38 +0000821 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000822 if (!NewTD) return 0;
823
824 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000825 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000826 // Merge the decl with the existing one if appropriate. If the decl is
827 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000828 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000829 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
830 if (NewTD == 0) return 0;
831 }
832 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000833 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000834 // C99 6.7.7p2: If a typedef name specifies a variably modified type
835 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000836 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
837 // FIXME: Diagnostic needs to be fixed.
838 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000839 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000840 }
841 }
Chris Lattner41af0932007-11-14 06:34:38 +0000842 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000843 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000844 switch (D.getDeclSpec().getStorageClassSpec()) {
845 default: assert(0 && "Unknown storage class!");
846 case DeclSpec::SCS_auto:
847 case DeclSpec::SCS_register:
848 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
849 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000850 InvalidDecl = true;
851 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000852 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
853 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
854 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000855 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000856 }
857
Chris Lattnera98e58d2008-03-15 21:24:04 +0000858 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000859 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000860 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
861
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000862 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000863 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000864 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000865 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +0000866 "Constructors can only be declared in a member context");
867
Douglas Gregor42a552f2008-11-05 20:51:48 +0000868 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000869
870 // Create the new declaration
871 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000872 cast<CXXRecordDecl>(DC),
Douglas Gregorb48fe382008-10-31 09:07:45 +0000873 D.getIdentifierLoc(), II, R,
874 isExplicit, isInline,
875 /*isImplicitlyDeclared=*/false);
876
Douglas Gregor42a552f2008-11-05 20:51:48 +0000877 if (isInvalidDecl)
878 NewFD->setInvalidDecl();
879 } else if (D.getKind() == Declarator::DK_Destructor) {
880 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000881 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000882 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000883
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000884 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000885 cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000886 D.getIdentifierLoc(), II, R,
887 isInline,
888 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000889
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000890 if (isInvalidDecl)
891 NewFD->setInvalidDecl();
892 } else {
893 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
894 // Create a FunctionDecl to satisfy the function definition parsing
895 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000896 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000897 II, R, SC, isInline, LastDeclarator,
898 // FIXME: Move to DeclGroup...
899 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000900 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000901 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000902 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000903 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000904 Diag(D.getIdentifierLoc(),
905 diag::err_conv_function_not_member);
906 return 0;
907 } else {
908 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
909
910 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000911 cast<CXXRecordDecl>(DC),
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000912 D.getIdentifierLoc(), II, R,
913 isInline, isExplicit);
914
915 if (isInvalidDecl)
916 NewFD->setInvalidDecl();
917 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000918 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000919 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000920 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000921 D.getIdentifierLoc(), II, R,
922 (SC == FunctionDecl::Static), isInline,
923 LastDeclarator);
924 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000925 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000926 D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000927 II, R, SC, isInline, LastDeclarator,
928 // FIXME: Move to DeclGroup...
929 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000930 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000931 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000932 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000933
Daniel Dunbara80f8742008-08-05 01:35:17 +0000934 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000935 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000936 // The parser guarantees this is a string.
937 StringLiteral *SE = cast<StringLiteral>(E);
938 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
939 SE->getByteLength())));
940 }
941
Chris Lattner04421082008-04-08 04:40:51 +0000942 // Copy the parameter declarations from the declarator D to
943 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000944 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000945 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
946
947 // Create Decl objects for each parameter, adding them to the
948 // FunctionDecl.
949 llvm::SmallVector<ParmVarDecl*, 16> Params;
950
951 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
952 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000953 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000954 // We let through "const void" here because Sema::GetTypeForDeclarator
955 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000956 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
957 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000958 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
959 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000960 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
961
Chris Lattnerdef026a2008-04-10 02:26:16 +0000962 // In C++, the empty parameter-type-list must be spelled "void"; a
963 // typedef of void is not permitted.
964 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000965 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000966 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
967 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000968 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000969 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
970 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
971 }
972
973 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +0000974 } else if (R->getAsTypedefType()) {
975 // When we're declaring a function with a typedef, as in the
976 // following example, we'll need to synthesize (unnamed)
977 // parameters for use in the declaration.
978 //
979 // @code
980 // typedef void fn(int);
981 // fn f;
982 // @endcode
983 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
984 if (!FT) {
985 // This is a typedef of a function with no prototype, so we
986 // don't need to do anything.
987 } else if ((FT->getNumArgs() == 0) ||
988 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
989 FT->getArgType(0)->isVoidType())) {
990 // This is a zero-argument function. We don't need to do anything.
991 } else {
992 // Synthesize a parameter for each argument type.
993 llvm::SmallVector<ParmVarDecl*, 16> Params;
994 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
995 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000996 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +0000997 SourceLocation(), 0,
998 *ArgType, VarDecl::None,
999 0, 0));
1000 }
1001
1002 NewFD->setParams(&Params[0], Params.size());
1003 }
Chris Lattner04421082008-04-08 04:40:51 +00001004 }
1005
Douglas Gregor42a552f2008-11-05 20:51:48 +00001006 // C++ constructors and destructors are handled by separate
1007 // routines, since they don't require any declaration merging (C++
1008 // [class.mfct]p2) and they aren't ever pushed into scope, because
1009 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1010 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1011 return ActOnConstructorDeclarator(Constructor);
1012 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1013 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001014 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1015 return ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001016
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001017 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1018 if (NewFD->isOverloadedOperator() &&
1019 CheckOverloadedOperatorDeclaration(NewFD))
1020 NewFD->setInvalidDecl();
1021
Steve Naroffffce4d52008-01-09 23:34:55 +00001022 // Merge the decl with the existing one if appropriate. Since C functions
1023 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001024 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001025 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001026 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001027
1028 // If C++, determine whether NewFD is an overload of PrevDecl or
1029 // a declaration that requires merging. If it's an overload,
1030 // there's no more work to do here; we'll just add the new
1031 // function to the scope.
1032 OverloadedFunctionDecl::function_iterator MatchedDecl;
1033 if (!getLangOptions().CPlusPlus ||
1034 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1035 Decl *OldDecl = PrevDecl;
1036
1037 // If PrevDecl was an overloaded function, extract the
1038 // FunctionDecl that matched.
1039 if (isa<OverloadedFunctionDecl>(PrevDecl))
1040 OldDecl = *MatchedDecl;
1041
1042 // NewFD and PrevDecl represent declarations that need to be
1043 // merged.
1044 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1045
1046 if (NewFD == 0) return 0;
1047 if (Redeclaration) {
1048 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1049
1050 if (OldDecl == PrevDecl) {
1051 // Remove the name binding for the previous
1052 // declaration. We'll add the binding back later, but then
1053 // it will refer to the new declaration (which will
1054 // contain more information).
1055 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1056 } else {
1057 // We need to update the OverloadedFunctionDecl with the
1058 // latest declaration of this function, so that name
1059 // lookup will always refer to the latest declaration of
1060 // this function.
1061 *MatchedDecl = NewFD;
1062
1063 // Add the redeclaration to the current scope, since we'll
1064 // be skipping PushOnScopeChains.
1065 S->AddDecl(NewFD);
1066
1067 return NewFD;
1068 }
1069 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001070 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001071 }
1072 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001073
1074 // In C++, check default arguments now that we have merged decls.
1075 if (getLangOptions().CPlusPlus)
1076 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001077 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001078 // Check that there are no default arguments (C++ only).
1079 if (getLangOptions().CPlusPlus)
1080 CheckExtraCXXDefaultArguments(D);
1081
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001082 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001083 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1084 D.getIdentifier()->getName());
1085 InvalidDecl = true;
1086 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001087
1088 VarDecl *NewVD;
1089 VarDecl::StorageClass SC;
1090 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001091 default: assert(0 && "Unknown storage class!");
1092 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1093 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1094 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1095 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1096 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1097 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001098 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001099 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001100 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1101 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001102 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001103 D.getIdentifierLoc(), II,
1104 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001105 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001106 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001107 if (S->getFnParent() == 0) {
1108 // C99 6.9p2: The storage-class specifiers auto and register shall not
1109 // appear in the declaration specifiers in an external declaration.
1110 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1111 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1112 R.getAsString());
1113 InvalidDecl = true;
1114 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001115 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001116 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001117 II, R, SC, LastDeclarator,
1118 // FIXME: Move to DeclGroup...
1119 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001120 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001121 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001122 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001123 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001124
Daniel Dunbara735ad82008-08-06 00:03:29 +00001125 // Handle GNU asm-label extension (encoded as an attribute).
1126 if (Expr *E = (Expr*) D.getAsmLabel()) {
1127 // The parser guarantees this is a string.
1128 StringLiteral *SE = cast<StringLiteral>(E);
1129 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1130 SE->getByteLength())));
1131 }
1132
Nate Begemanc8e89a82008-03-14 18:07:10 +00001133 // Emit an error if an address space was applied to decl with local storage.
1134 // This includes arrays of objects with address space qualifiers, but not
1135 // automatic variables that point to other address spaces.
1136 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001137 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1138 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1139 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001140 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001141 // Merge the decl with the existing one if appropriate. If the decl is
1142 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001143 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001144 NewVD = MergeVarDecl(NewVD, PrevDecl);
1145 if (NewVD == 0) return 0;
1146 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001147 New = NewVD;
1148 }
1149
1150 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001151 if (II)
1152 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001153 // If any semantic error occurred, mark the decl as invalid.
1154 if (D.getInvalidType() || InvalidDecl)
1155 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001156
1157 return New;
1158}
1159
Steve Naroff6594a702008-10-27 11:34:16 +00001160void Sema::InitializerElementNotConstant(const Expr *Init) {
1161 Diag(Init->getExprLoc(),
1162 diag::err_init_element_not_constant, Init->getSourceRange());
1163}
1164
Eli Friedmanc594b322008-05-20 13:48:25 +00001165bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1166 switch (Init->getStmtClass()) {
1167 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001168 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001169 return true;
1170 case Expr::ParenExprClass: {
1171 const ParenExpr* PE = cast<ParenExpr>(Init);
1172 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1173 }
1174 case Expr::CompoundLiteralExprClass:
1175 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1176 case Expr::DeclRefExprClass: {
1177 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001178 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1179 if (VD->hasGlobalStorage())
1180 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001181 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001182 return true;
1183 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001184 if (isa<FunctionDecl>(D))
1185 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001186 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001187 return true;
1188 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001189 case Expr::MemberExprClass: {
1190 const MemberExpr *M = cast<MemberExpr>(Init);
1191 if (M->isArrow())
1192 return CheckAddressConstantExpression(M->getBase());
1193 return CheckAddressConstantExpressionLValue(M->getBase());
1194 }
1195 case Expr::ArraySubscriptExprClass: {
1196 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1197 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1198 return CheckAddressConstantExpression(ASE->getBase()) ||
1199 CheckArithmeticConstantExpression(ASE->getIdx());
1200 }
1201 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001202 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001203 return false;
1204 case Expr::UnaryOperatorClass: {
1205 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1206
1207 // C99 6.6p9
1208 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001209 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001210
Steve Naroff6594a702008-10-27 11:34:16 +00001211 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001212 return true;
1213 }
1214 }
1215}
1216
1217bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1218 switch (Init->getStmtClass()) {
1219 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001220 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001221 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001222 case Expr::ParenExprClass:
1223 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001224 case Expr::StringLiteralClass:
1225 case Expr::ObjCStringLiteralClass:
1226 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001227 case Expr::CallExprClass:
1228 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1229 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1230 Builtin::BI__builtin___CFStringMakeConstantString)
1231 return false;
1232
Steve Naroff6594a702008-10-27 11:34:16 +00001233 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001234 return true;
1235
Eli Friedmanc594b322008-05-20 13:48:25 +00001236 case Expr::UnaryOperatorClass: {
1237 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1238
1239 // C99 6.6p9
1240 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1241 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1242
1243 if (Exp->getOpcode() == UnaryOperator::Extension)
1244 return CheckAddressConstantExpression(Exp->getSubExpr());
1245
Steve Naroff6594a702008-10-27 11:34:16 +00001246 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001247 return true;
1248 }
1249 case Expr::BinaryOperatorClass: {
1250 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1251 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1252
1253 Expr *PExp = Exp->getLHS();
1254 Expr *IExp = Exp->getRHS();
1255 if (IExp->getType()->isPointerType())
1256 std::swap(PExp, IExp);
1257
1258 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1259 return CheckAddressConstantExpression(PExp) ||
1260 CheckArithmeticConstantExpression(IExp);
1261 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001262 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001263 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001264 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001265 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1266 // Check for implicit promotion
1267 if (SubExpr->getType()->isFunctionType() ||
1268 SubExpr->getType()->isArrayType())
1269 return CheckAddressConstantExpressionLValue(SubExpr);
1270 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001271
1272 // Check for pointer->pointer cast
1273 if (SubExpr->getType()->isPointerType())
1274 return CheckAddressConstantExpression(SubExpr);
1275
Eli Friedmanc3f07642008-08-25 20:46:57 +00001276 if (SubExpr->getType()->isIntegralType()) {
1277 // Check for the special-case of a pointer->int->pointer cast;
1278 // this isn't standard, but some code requires it. See
1279 // PR2720 for an example.
1280 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1281 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1282 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1283 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1284 if (IntWidth >= PointerWidth) {
1285 return CheckAddressConstantExpression(SubCast->getSubExpr());
1286 }
1287 }
1288 }
1289 }
1290 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001291 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001292 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001293
Steve Naroff6594a702008-10-27 11:34:16 +00001294 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001295 return true;
1296 }
1297 case Expr::ConditionalOperatorClass: {
1298 // FIXME: Should we pedwarn here?
1299 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1300 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001301 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001302 return true;
1303 }
1304 if (CheckArithmeticConstantExpression(Exp->getCond()))
1305 return true;
1306 if (Exp->getLHS() &&
1307 CheckAddressConstantExpression(Exp->getLHS()))
1308 return true;
1309 return CheckAddressConstantExpression(Exp->getRHS());
1310 }
1311 case Expr::AddrLabelExprClass:
1312 return false;
1313 }
1314}
1315
Eli Friedman4caf0552008-06-09 05:05:07 +00001316static const Expr* FindExpressionBaseAddress(const Expr* E);
1317
1318static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1319 switch (E->getStmtClass()) {
1320 default:
1321 return E;
1322 case Expr::ParenExprClass: {
1323 const ParenExpr* PE = cast<ParenExpr>(E);
1324 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1325 }
1326 case Expr::MemberExprClass: {
1327 const MemberExpr *M = cast<MemberExpr>(E);
1328 if (M->isArrow())
1329 return FindExpressionBaseAddress(M->getBase());
1330 return FindExpressionBaseAddressLValue(M->getBase());
1331 }
1332 case Expr::ArraySubscriptExprClass: {
1333 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1334 return FindExpressionBaseAddress(ASE->getBase());
1335 }
1336 case Expr::UnaryOperatorClass: {
1337 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1338
1339 if (Exp->getOpcode() == UnaryOperator::Deref)
1340 return FindExpressionBaseAddress(Exp->getSubExpr());
1341
1342 return E;
1343 }
1344 }
1345}
1346
1347static const Expr* FindExpressionBaseAddress(const Expr* E) {
1348 switch (E->getStmtClass()) {
1349 default:
1350 return E;
1351 case Expr::ParenExprClass: {
1352 const ParenExpr* PE = cast<ParenExpr>(E);
1353 return FindExpressionBaseAddress(PE->getSubExpr());
1354 }
1355 case Expr::UnaryOperatorClass: {
1356 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1357
1358 // C99 6.6p9
1359 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1360 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1361
1362 if (Exp->getOpcode() == UnaryOperator::Extension)
1363 return FindExpressionBaseAddress(Exp->getSubExpr());
1364
1365 return E;
1366 }
1367 case Expr::BinaryOperatorClass: {
1368 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1369
1370 Expr *PExp = Exp->getLHS();
1371 Expr *IExp = Exp->getRHS();
1372 if (IExp->getType()->isPointerType())
1373 std::swap(PExp, IExp);
1374
1375 return FindExpressionBaseAddress(PExp);
1376 }
1377 case Expr::ImplicitCastExprClass: {
1378 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1379
1380 // Check for implicit promotion
1381 if (SubExpr->getType()->isFunctionType() ||
1382 SubExpr->getType()->isArrayType())
1383 return FindExpressionBaseAddressLValue(SubExpr);
1384
1385 // Check for pointer->pointer cast
1386 if (SubExpr->getType()->isPointerType())
1387 return FindExpressionBaseAddress(SubExpr);
1388
1389 // We assume that we have an arithmetic expression here;
1390 // if we don't, we'll figure it out later
1391 return 0;
1392 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001393 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001394 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1395
1396 // Check for pointer->pointer cast
1397 if (SubExpr->getType()->isPointerType())
1398 return FindExpressionBaseAddress(SubExpr);
1399
1400 // We assume that we have an arithmetic expression here;
1401 // if we don't, we'll figure it out later
1402 return 0;
1403 }
1404 }
1405}
1406
Eli Friedmanc594b322008-05-20 13:48:25 +00001407bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1408 switch (Init->getStmtClass()) {
1409 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001410 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001411 return true;
1412 case Expr::ParenExprClass: {
1413 const ParenExpr* PE = cast<ParenExpr>(Init);
1414 return CheckArithmeticConstantExpression(PE->getSubExpr());
1415 }
1416 case Expr::FloatingLiteralClass:
1417 case Expr::IntegerLiteralClass:
1418 case Expr::CharacterLiteralClass:
1419 case Expr::ImaginaryLiteralClass:
1420 case Expr::TypesCompatibleExprClass:
1421 case Expr::CXXBoolLiteralExprClass:
1422 return false;
1423 case Expr::CallExprClass: {
1424 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001425
1426 // Allow any constant foldable calls to builtins.
1427 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001428 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001429
Steve Naroff6594a702008-10-27 11:34:16 +00001430 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001431 return true;
1432 }
1433 case Expr::DeclRefExprClass: {
1434 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1435 if (isa<EnumConstantDecl>(D))
1436 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001437 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001438 return true;
1439 }
1440 case Expr::CompoundLiteralExprClass:
1441 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1442 // but vectors are allowed to be magic.
1443 if (Init->getType()->isVectorType())
1444 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001445 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001446 return true;
1447 case Expr::UnaryOperatorClass: {
1448 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1449
1450 switch (Exp->getOpcode()) {
1451 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1452 // See C99 6.6p3.
1453 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001454 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001455 return true;
1456 case UnaryOperator::SizeOf:
1457 case UnaryOperator::AlignOf:
1458 case UnaryOperator::OffsetOf:
1459 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1460 // See C99 6.5.3.4p2 and 6.6p3.
1461 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1462 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001463 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001464 return true;
1465 case UnaryOperator::Extension:
1466 case UnaryOperator::LNot:
1467 case UnaryOperator::Plus:
1468 case UnaryOperator::Minus:
1469 case UnaryOperator::Not:
1470 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1471 }
1472 }
1473 case Expr::SizeOfAlignOfTypeExprClass: {
1474 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1475 // Special check for void types, which are allowed as an extension
1476 if (Exp->getArgumentType()->isVoidType())
1477 return false;
1478 // alignof always evaluates to a constant.
1479 // FIXME: is sizeof(int[3.0]) a constant expression?
1480 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001481 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001482 return true;
1483 }
1484 return false;
1485 }
1486 case Expr::BinaryOperatorClass: {
1487 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1488
1489 if (Exp->getLHS()->getType()->isArithmeticType() &&
1490 Exp->getRHS()->getType()->isArithmeticType()) {
1491 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1492 CheckArithmeticConstantExpression(Exp->getRHS());
1493 }
1494
Eli Friedman4caf0552008-06-09 05:05:07 +00001495 if (Exp->getLHS()->getType()->isPointerType() &&
1496 Exp->getRHS()->getType()->isPointerType()) {
1497 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1498 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1499
1500 // Only allow a null (constant integer) base; we could
1501 // allow some additional cases if necessary, but this
1502 // is sufficient to cover offsetof-like constructs.
1503 if (!LHSBase && !RHSBase) {
1504 return CheckAddressConstantExpression(Exp->getLHS()) ||
1505 CheckAddressConstantExpression(Exp->getRHS());
1506 }
1507 }
1508
Steve Naroff6594a702008-10-27 11:34:16 +00001509 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001510 return true;
1511 }
1512 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001513 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001514 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001515 if (SubExpr->getType()->isArithmeticType())
1516 return CheckArithmeticConstantExpression(SubExpr);
1517
Eli Friedmanb529d832008-09-02 09:37:00 +00001518 if (SubExpr->getType()->isPointerType()) {
1519 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1520 // If the pointer has a null base, this is an offsetof-like construct
1521 if (!Base)
1522 return CheckAddressConstantExpression(SubExpr);
1523 }
1524
Steve Naroff6594a702008-10-27 11:34:16 +00001525 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001526 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001527 }
1528 case Expr::ConditionalOperatorClass: {
1529 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001530
1531 // If GNU extensions are disabled, we require all operands to be arithmetic
1532 // constant expressions.
1533 if (getLangOptions().NoExtensions) {
1534 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1535 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1536 CheckArithmeticConstantExpression(Exp->getRHS());
1537 }
1538
1539 // Otherwise, we have to emulate some of the behavior of fold here.
1540 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1541 // because it can constant fold things away. To retain compatibility with
1542 // GCC code, we see if we can fold the condition to a constant (which we
1543 // should always be able to do in theory). If so, we only require the
1544 // specified arm of the conditional to be a constant. This is a horrible
1545 // hack, but is require by real world code that uses __builtin_constant_p.
1546 APValue Val;
1547 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1548 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1549 // won't be able to either. Use it to emit the diagnostic though.
1550 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1551 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1552 return Res;
1553 }
1554
1555 // Verify that the side following the condition is also a constant.
1556 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1557 if (Val.getInt() == 0)
1558 std::swap(TrueSide, FalseSide);
1559
1560 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001561 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001562
1563 // Okay, the evaluated side evaluates to a constant, so we accept this.
1564 // Check to see if the other side is obviously not a constant. If so,
1565 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001566 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001567 Diag(Init->getExprLoc(),
1568 diag::ext_typecheck_expression_not_constant_but_accepted,
1569 FalseSide->getSourceRange());
1570 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001571 }
1572 }
1573}
1574
1575bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001576 Init = Init->IgnoreParens();
1577
Eli Friedmanc594b322008-05-20 13:48:25 +00001578 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1579 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1580 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1581
Nuno Lopes9a979c32008-07-07 16:46:50 +00001582 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1583 return CheckForConstantInitializer(e->getInitializer(), DclT);
1584
Eli Friedmanc594b322008-05-20 13:48:25 +00001585 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1586 unsigned numInits = Exp->getNumInits();
1587 for (unsigned i = 0; i < numInits; i++) {
1588 // FIXME: Need to get the type of the declaration for C++,
1589 // because it could be a reference?
1590 if (CheckForConstantInitializer(Exp->getInit(i),
1591 Exp->getInit(i)->getType()))
1592 return true;
1593 }
1594 return false;
1595 }
1596
1597 if (Init->isNullPointerConstant(Context))
1598 return false;
1599 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001600 QualType InitTy = Context.getCanonicalType(Init->getType())
1601 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001602 if (InitTy == Context.BoolTy) {
1603 // Special handling for pointers implicitly cast to bool;
1604 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1605 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1606 Expr* SubE = ICE->getSubExpr();
1607 if (SubE->getType()->isPointerType() ||
1608 SubE->getType()->isArrayType() ||
1609 SubE->getType()->isFunctionType()) {
1610 return CheckAddressConstantExpression(Init);
1611 }
1612 }
1613 } else if (InitTy->isIntegralType()) {
1614 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001615 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001616 SubE = CE->getSubExpr();
1617 // Special check for pointer cast to int; we allow as an extension
1618 // an address constant cast to an integer if the integer
1619 // is of an appropriate width (this sort of code is apparently used
1620 // in some places).
1621 // FIXME: Add pedwarn?
1622 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1623 if (SubE && (SubE->getType()->isPointerType() ||
1624 SubE->getType()->isArrayType() ||
1625 SubE->getType()->isFunctionType())) {
1626 unsigned IntWidth = Context.getTypeSize(Init->getType());
1627 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1628 if (IntWidth >= PointerWidth)
1629 return CheckAddressConstantExpression(Init);
1630 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001631 }
1632
1633 return CheckArithmeticConstantExpression(Init);
1634 }
1635
1636 if (Init->getType()->isPointerType())
1637 return CheckAddressConstantExpression(Init);
1638
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001639 // An array type at the top level that isn't an init-list must
1640 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001641 if (Init->getType()->isArrayType())
1642 return false;
1643
Nuno Lopes73419bf2008-09-01 18:42:41 +00001644 if (Init->getType()->isFunctionType())
1645 return false;
1646
Steve Naroff8af6a452008-10-02 17:12:56 +00001647 // Allow block exprs at top level.
1648 if (Init->getType()->isBlockPointerType())
1649 return false;
1650
Steve Naroff6594a702008-10-27 11:34:16 +00001651 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001652 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001653}
1654
Steve Naroffbb204692007-09-12 14:07:44 +00001655void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001656 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001657 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001658 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001659
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001660 // If there is no declaration, there was an error parsing it. Just ignore
1661 // the initializer.
1662 if (RealDecl == 0) {
1663 delete Init;
1664 return;
1665 }
Steve Naroffbb204692007-09-12 14:07:44 +00001666
Steve Naroff410e3e22007-09-12 20:13:48 +00001667 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1668 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001669 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1670 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001671 RealDecl->setInvalidDecl();
1672 return;
1673 }
Steve Naroffbb204692007-09-12 14:07:44 +00001674 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001675 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001676 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001677 if (VDecl->isBlockVarDecl()) {
1678 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001679 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001680 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001681 VDecl->setInvalidDecl();
1682 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001683 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1684 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001685 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001686
1687 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1688 if (!getLangOptions().CPlusPlus) {
1689 if (SC == VarDecl::Static) // C99 6.7.8p4.
1690 CheckForConstantInitializer(Init, DclT);
1691 }
Steve Naroffbb204692007-09-12 14:07:44 +00001692 }
Steve Naroff248a7532008-04-15 22:42:06 +00001693 } else if (VDecl->isFileVarDecl()) {
1694 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001695 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001696 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001697 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1698 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001699 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001700
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001701 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1702 if (!getLangOptions().CPlusPlus) {
1703 // C99 6.7.8p4. All file scoped initializers need to be constant.
1704 CheckForConstantInitializer(Init, DclT);
1705 }
Steve Naroffbb204692007-09-12 14:07:44 +00001706 }
1707 // If the type changed, it means we had an incomplete type that was
1708 // completed by the initializer. For example:
1709 // int ary[] = { 1, 3, 5 };
1710 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001711 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001712 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001713 Init->setType(DclT);
1714 }
Steve Naroffbb204692007-09-12 14:07:44 +00001715
1716 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001717 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001718 return;
1719}
1720
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001721void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1722 Decl *RealDecl = static_cast<Decl *>(dcl);
1723
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001724 // If there is no declaration, there was an error parsing it. Just ignore it.
1725 if (RealDecl == 0)
1726 return;
1727
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001728 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1729 QualType Type = Var->getType();
1730 // C++ [dcl.init.ref]p3:
1731 // The initializer can be omitted for a reference only in a
1732 // parameter declaration (8.3.5), in the declaration of a
1733 // function return type, in the declaration of a class member
1734 // within its class declaration (9.2), and where the extern
1735 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001736 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001737 Diag(Var->getLocation(),
1738 diag::err_reference_var_requires_init,
1739 Var->getName(),
1740 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor18fe5682008-11-03 20:45:27 +00001741 Var->setInvalidDecl();
1742 return;
1743 }
1744
1745 // C++ [dcl.init]p9:
1746 //
1747 // If no initializer is specified for an object, and the object
1748 // is of (possibly cv-qualified) non-POD class type (or array
1749 // thereof), the object shall be default-initialized; if the
1750 // object is of const-qualified type, the underlying class type
1751 // shall have a user-declared default constructor.
1752 if (getLangOptions().CPlusPlus) {
1753 QualType InitType = Type;
1754 if (const ArrayType *Array = Context.getAsArrayType(Type))
1755 InitType = Array->getElementType();
1756 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001757 const CXXConstructorDecl *Constructor
1758 = PerformInitializationByConstructor(InitType, 0, 0,
1759 Var->getLocation(),
1760 SourceRange(Var->getLocation(),
1761 Var->getLocation()),
1762 Var->getName(),
1763 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001764 if (!Constructor)
1765 Var->setInvalidDecl();
1766 }
1767 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001768
Douglas Gregor818ce482008-10-29 13:50:18 +00001769#if 0
1770 // FIXME: Temporarily disabled because we are not properly parsing
1771 // linkage specifications on declarations, e.g.,
1772 //
1773 // extern "C" const CGPoint CGPointerZero;
1774 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001775 // C++ [dcl.init]p9:
1776 //
1777 // If no initializer is specified for an object, and the
1778 // object is of (possibly cv-qualified) non-POD class type (or
1779 // array thereof), the object shall be default-initialized; if
1780 // the object is of const-qualified type, the underlying class
1781 // type shall have a user-declared default
1782 // constructor. Otherwise, if no initializer is specified for
1783 // an object, the object and its subobjects, if any, have an
1784 // indeterminate initial value; if the object or any of its
1785 // subobjects are of const-qualified type, the program is
1786 // ill-formed.
1787 //
1788 // This isn't technically an error in C, so we don't diagnose it.
1789 //
1790 // FIXME: Actually perform the POD/user-defined default
1791 // constructor check.
1792 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001793 Context.getCanonicalType(Type).isConstQualified() &&
1794 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001795 Diag(Var->getLocation(),
1796 diag::err_const_var_requires_init,
1797 Var->getName(),
1798 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor818ce482008-10-29 13:50:18 +00001799#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001800 }
1801}
1802
Reid Spencer5f016e22007-07-11 17:01:13 +00001803/// The declarators are chained together backwards, reverse the list.
1804Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1805 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001806 Decl *GroupDecl = static_cast<Decl*>(group);
1807 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001808 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001809
1810 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1811 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001812 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001814 else { // reverse the list.
1815 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001816 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001817 Group->setNextDeclarator(NewGroup);
1818 NewGroup = Group;
1819 Group = Next;
1820 }
1821 }
1822 // Perform semantic analysis that depends on having fully processed both
1823 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001824 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001825 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1826 if (!IDecl)
1827 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001828 QualType T = IDecl->getType();
1829
1830 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1831 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001832 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1833 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001834 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001835 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1836 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001837 }
1838 }
1839 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1840 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001841 if (IDecl->isBlockVarDecl() &&
1842 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001843 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001844 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1845 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001846 IDecl->setInvalidDecl();
1847 }
1848 }
1849 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1850 // object that has file scope without an initializer, and without a
1851 // storage-class specifier or with the storage-class specifier "static",
1852 // constitutes a tentative definition. Note: A tentative definition with
1853 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001854 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001855 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001856 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1857 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001858 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001859 // C99 6.9.2p3: If the declaration of an identifier for an object is
1860 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1861 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001862 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1863 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001864 IDecl->setInvalidDecl();
1865 }
1866 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001867 if (IDecl->isFileVarDecl())
1868 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001869 }
1870 return NewGroup;
1871}
Steve Naroffe1223f72007-08-28 03:03:08 +00001872
Chris Lattner04421082008-04-08 04:40:51 +00001873/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1874/// to introduce parameters into function prototype scope.
1875Sema::DeclTy *
1876Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001877 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00001878 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001879
1880 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001881 VarDecl::StorageClass StorageClass = VarDecl::None;
1882 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1883 StorageClass = VarDecl::Register;
1884 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001885 Diag(DS.getStorageClassSpecLoc(),
1886 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001887 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001888 }
1889 if (DS.isThreadSpecified()) {
1890 Diag(DS.getThreadSpecLoc(),
1891 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001892 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001893 }
1894
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001895 // Check that there are no default arguments inside the type of this
1896 // parameter (C++ only).
1897 if (getLangOptions().CPlusPlus)
1898 CheckExtraCXXDefaultArguments(D);
1899
Chris Lattner04421082008-04-08 04:40:51 +00001900 // In this context, we *do not* check D.getInvalidType(). If the declarator
1901 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1902 // though it will not reflect the user specified type.
1903 QualType parmDeclType = GetTypeForDeclarator(D, S);
1904
1905 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1906
Reid Spencer5f016e22007-07-11 17:01:13 +00001907 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1908 // Can this happen for params? We already checked that they don't conflict
1909 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001910 IdentifierInfo *II = D.getIdentifier();
1911 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1912 if (S->isDeclScope(PrevDecl)) {
1913 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1914 dyn_cast<NamedDecl>(PrevDecl)->getName());
1915
1916 // Recover by removing the name
1917 II = 0;
1918 D.SetIdentifier(0, D.getIdentifierLoc());
1919 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001920 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001921
1922 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1923 // Doing the promotion here has a win and a loss. The win is the type for
1924 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1925 // code generator). The loss is the orginal type isn't preserved. For example:
1926 //
1927 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1928 // int blockvardecl[5];
1929 // sizeof(parmvardecl); // size == 4
1930 // sizeof(blockvardecl); // size == 20
1931 // }
1932 //
1933 // For expressions, all implicit conversions are captured using the
1934 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1935 //
1936 // FIXME: If a source translation tool needs to see the original type, then
1937 // we need to consider storing both types (in ParmVarDecl)...
1938 //
Chris Lattnere6327742008-04-02 05:18:44 +00001939 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001940 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001941 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001942 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001943 parmDeclType = Context.getPointerType(parmDeclType);
1944
Chris Lattner04421082008-04-08 04:40:51 +00001945 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1946 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001947 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001948 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001949
Chris Lattner04421082008-04-08 04:40:51 +00001950 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001951 New->setInvalidDecl();
1952
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001953 if (II)
1954 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001955
Chris Lattner3ff30c82008-06-29 00:02:00 +00001956 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001957 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001958
Reid Spencer5f016e22007-07-11 17:01:13 +00001959}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001960
Chris Lattnerb652cea2007-10-09 17:14:05 +00001961Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001962 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001963 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1964 "Not a function declarator!");
1965 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001966
Reid Spencer5f016e22007-07-11 17:01:13 +00001967 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1968 // for a K&R function.
1969 if (!FTI.hasPrototype) {
1970 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001971 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001972 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1973 FTI.ArgInfo[i].Ident->getName());
1974 // Implicitly declare the argument as type 'int' for lack of a better
1975 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001976 DeclSpec DS;
1977 const char* PrevSpec; // unused
1978 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1979 PrevSpec);
1980 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1981 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1982 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001983 }
1984 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001986 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001987 }
1988
1989 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001990
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001991 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001992 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001993}
1994
1995Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1996 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001997 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00001998
1999 // See if this is a redefinition.
2000 const FunctionDecl *Definition;
2001 if (FD->getBody(Definition)) {
2002 Diag(FD->getLocation(), diag::err_redefinition,
2003 FD->getName());
2004 Diag(Definition->getLocation(), diag::err_previous_definition);
2005 }
2006
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002007 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
2008 if (isa<CXXRecordDecl>(CurContext))
2009 MD->setInlineDefinition(true);
2010
Chris Lattnerb048c982008-04-06 04:47:34 +00002011 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00002012
2013 // Check the validity of our function parameters
2014 CheckParmsForFunctionDef(FD);
2015
2016 // Introduce our parameters into the function scope
2017 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2018 ParmVarDecl *Param = FD->getParamDecl(p);
2019 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002020 if (Param->getIdentifier())
2021 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002022 }
Chris Lattner04421082008-04-08 04:40:51 +00002023
Reid Spencer5f016e22007-07-11 17:01:13 +00002024 return FD;
2025}
2026
Steve Naroffd6d054d2007-11-11 23:20:51 +00002027Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2028 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002029 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002030 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002031 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002032 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002033 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002034 } else
2035 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002036 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002037 // Verify and clean out per-function state.
2038
2039 // Check goto/label use.
2040 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2041 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2042 // Verify that we have no forward references left. If so, there was a goto
2043 // or address of a label taken, but no definition of it. Label fwd
2044 // definitions are indicated with a null substmt.
2045 if (I->second->getSubStmt() == 0) {
2046 LabelStmt *L = I->second;
2047 // Emit error.
2048 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2049
2050 // At this point, we have gotos that use the bogus label. Stitch it into
2051 // the function body so that they aren't leaked and that the AST is well
2052 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002053 if (Body) {
2054 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2055 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2056 } else {
2057 // The whole function wasn't parsed correctly, just delete this.
2058 delete L;
2059 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002060 }
2061 }
2062 LabelMap.clear();
2063
Steve Naroffd6d054d2007-11-11 23:20:51 +00002064 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002065}
2066
Reid Spencer5f016e22007-07-11 17:01:13 +00002067/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2068/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002069ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2070 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002071 // Extension in C99. Legal in C90, but warn about it.
2072 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00002073 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00002074 else
Reid Spencer5f016e22007-07-11 17:01:13 +00002075 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2076
2077 // FIXME: handle stuff like:
2078 // void foo() { extern float X(); }
2079 // void bar() { X(); } <-- implicit decl for X in another scope.
2080
2081 // Set a Declarator for the implicit definition: int foo();
2082 const char *Dummy;
2083 DeclSpec DS;
2084 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2085 Error = Error; // Silence warning.
2086 assert(!Error && "Error setting up implicit decl!");
2087 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002088 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002089 D.SetIdentifier(&II, Loc);
2090
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002091 // Insert this function into translation-unit scope.
2092
2093 DeclContext *PrevDC = CurContext;
2094 CurContext = Context.getTranslationUnitDecl();
2095
Steve Naroffe2ef8152008-04-04 14:32:09 +00002096 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002097 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002098 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002099
2100 CurContext = PrevDC;
2101
Steve Naroffe2ef8152008-04-04 14:32:09 +00002102 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002103}
2104
2105
Chris Lattner41af0932007-11-14 06:34:38 +00002106TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002107 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002108 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002109 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002110
2111 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002112 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2113 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002114 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002115 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002116 if (D.getInvalidType())
2117 NewTD->setInvalidDecl();
2118 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002119}
2120
Steve Naroff08d92e42007-09-15 18:49:24 +00002121/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002122/// former case, Name will be non-null. In the later case, Name will be null.
2123/// TagType indicates what kind of tag this is. TK indicates whether this is a
2124/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002125Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002126 SourceLocation KWLoc, const CXXScopeSpec &SS,
2127 IdentifierInfo *Name, SourceLocation NameLoc,
2128 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // If this is a use of an existing tag, it must have a name.
2130 assert((Name != 0 || TK == TK_Definition) &&
2131 "Nameless record must be a definition!");
2132
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002133 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 switch (TagType) {
2135 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002136 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2137 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2138 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2139 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002140 }
2141
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002142 // Two code paths: a new one for structs/unions/classes where we create
2143 // separate decls for forward declarations, and an old (eventually to
2144 // be removed) code path for enums.
2145 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002146 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002147
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002148 DeclContext *DC = CurContext;
2149 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002150
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002151 if (Name && SS.isNotEmpty()) {
2152 // We have a nested-name tag ('struct foo::bar').
2153
2154 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002155 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002156 Name = 0;
2157 goto CreateNewDecl;
2158 }
2159
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002160 DC = static_cast<DeclContext*>(SS.getScopeRep());
2161 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002162 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2163
2164 // A tag 'foo::bar' must already exist.
2165 if (PrevDecl == 0) {
2166 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2167 SS.getRange());
2168 Name = 0;
2169 goto CreateNewDecl;
2170 }
2171 } else {
2172 // If this is a named struct, check to see if there was a previous forward
2173 // declaration or definition.
2174 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2175 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2176 }
2177
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002178 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002179 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2180 "unexpected Decl type");
2181 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002182 // If this is a use of a previous tag, or if the tag is already declared
2183 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002184 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002185 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002186 // Make sure that this wasn't declared as an enum and now used as a
2187 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002188 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002189 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2190 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002191 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002192 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002193 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002194 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002195 // If this is a use or a forward declaration, we're good.
2196 if (TK != TK_Definition)
2197 return PrevDecl;
2198
2199 // Diagnose attempts to redefine a tag.
2200 if (PrevTagDecl->isDefinition()) {
2201 Diag(NameLoc, diag::err_redefinition, Name->getName());
2202 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2203 // If this is a redefinition, recover by making this struct be
2204 // anonymous, which will make any later references get the previous
2205 // definition.
2206 Name = 0;
2207 } else {
2208 // Okay, this is definition of a previously declared or referenced
2209 // tag. Move the location of the decl to be the definition site.
2210 PrevDecl->setLocation(NameLoc);
2211 return PrevDecl;
2212 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002213 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002215 // If we get here, this is a definition of a new struct type in a nested
2216 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2217 // type.
2218 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002219 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002220 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002221 // The tag name clashes with a namespace name, issue an error and
2222 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002223 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2224 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2225 Name = 0;
2226 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002228 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002229
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002230 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002231
2232 // If there is an identifier, use the location of the identifier as the
2233 // location of the decl, otherwise use the location of the struct/union
2234 // keyword.
2235 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2236
2237 // Otherwise, if this is the first time we've seen this tag, create the decl.
2238 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002239 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002240 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2241 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002242 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002243 // If this is an undefined enum, warn.
2244 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002245 } else {
2246 // struct/union/class
2247
Reid Spencer5f016e22007-07-11 17:01:13 +00002248 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2249 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002250 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002251 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002252 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002253 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002254 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002255 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002256
2257 // If this has an identifier, add it to the scope stack.
2258 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002259 // The scope passed in may not be a decl scope. Zip up the scope tree until
2260 // we find one that is.
2261 while ((S->getFlags() & Scope::DeclScope) == 0)
2262 S = S->getParent();
2263
2264 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002265 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002266 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002267
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002268 if (Attr)
2269 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002270 return New;
2271}
2272
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002273/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2274/// the logic for enums, we create separate decls for forward declarations.
2275/// This is called by ActOnTag, but eventually will replace its logic.
2276Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002277 SourceLocation KWLoc, const CXXScopeSpec &SS,
2278 IdentifierInfo *Name, SourceLocation NameLoc,
2279 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002280 DeclContext *DC = CurContext;
2281 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002282
2283 if (Name && SS.isNotEmpty()) {
2284 // We have a nested-name tag ('struct foo::bar').
2285
2286 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002287 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002288 Name = 0;
2289 goto CreateNewDecl;
2290 }
2291
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002292 DC = static_cast<DeclContext*>(SS.getScopeRep());
2293 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002294 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2295
2296 // A tag 'foo::bar' must already exist.
2297 if (PrevDecl == 0) {
2298 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2299 SS.getRange());
2300 Name = 0;
2301 goto CreateNewDecl;
2302 }
2303 } else {
2304 // If this is a named struct, check to see if there was a previous forward
2305 // declaration or definition.
2306 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2307 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2308 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002309
2310 if (PrevDecl) {
2311 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2312 "unexpected Decl type");
2313
2314 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2315 // If this is a use of a previous tag, or if the tag is already declared
2316 // in the same scope (so that the definition/declaration completes or
2317 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002318 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002319 // Make sure that this wasn't declared as an enum and now used as a
2320 // struct or something similar.
2321 if (PrevTagDecl->getTagKind() != Kind) {
2322 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2323 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2324 // Recover by making this an anonymous redefinition.
2325 Name = 0;
2326 PrevDecl = 0;
2327 } else {
2328 // If this is a use, return the original decl.
2329
2330 // FIXME: In the future, return a variant or some other clue
2331 // for the consumer of this Decl to know it doesn't own it.
2332 // For our current ASTs this shouldn't be a problem, but will
2333 // need to be changed with DeclGroups.
2334 if (TK == TK_Reference)
2335 return PrevDecl;
2336
2337 // The new decl is a definition?
2338 if (TK == TK_Definition) {
2339 // Diagnose attempts to redefine a tag.
2340 if (RecordDecl* DefRecord =
2341 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2342 Diag(NameLoc, diag::err_redefinition, Name->getName());
2343 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2344 // If this is a redefinition, recover by making this struct be
2345 // anonymous, which will make any later references get the previous
2346 // definition.
2347 Name = 0;
2348 PrevDecl = 0;
2349 }
2350 // Okay, this is definition of a previously declared or referenced
2351 // tag. We're going to create a new Decl.
2352 }
2353 }
2354 // If we get here we have (another) forward declaration. Just create
2355 // a new decl.
2356 }
2357 else {
2358 // If we get here, this is a definition of a new struct type in a nested
2359 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2360 // new decl/type. We set PrevDecl to NULL so that the Records
2361 // have distinct types.
2362 PrevDecl = 0;
2363 }
2364 } else {
2365 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002366 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002367 // The tag name clashes with a namespace name, issue an error and
2368 // recover by making this tag be anonymous.
2369 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2370 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2371 Name = 0;
2372 }
2373 }
2374 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002375
2376 CreateNewDecl:
2377
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002378 // If there is an identifier, use the location of the identifier as the
2379 // location of the decl, otherwise use the location of the struct/union
2380 // keyword.
2381 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2382
2383 // Otherwise, if this is the first time we've seen this tag, create the decl.
2384 TagDecl *New;
2385
2386 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2387 // struct X { int A; } D; D should chain to X.
2388 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002389 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002390 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002391 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2392 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002393 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002394 dyn_cast_or_null<RecordDecl>(PrevDecl));
2395
2396 // If this has an identifier, add it to the scope stack.
2397 if ((TK == TK_Definition || !PrevDecl) && Name) {
2398 // The scope passed in may not be a decl scope. Zip up the scope tree until
2399 // we find one that is.
2400 while ((S->getFlags() & Scope::DeclScope) == 0)
2401 S = S->getParent();
2402
2403 // Add it to the decl chain.
2404 PushOnScopeChains(New, S);
2405 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002406
2407 // Handle #pragma pack: if the #pragma pack stack has non-default
2408 // alignment, make up a packed attribute for this decl. These
2409 // attributes are checked when the ASTContext lays out the
2410 // structure.
2411 //
2412 // It is important for implementing the correct semantics that this
2413 // happen here (in act on tag decl). The #pragma pack stack is
2414 // maintained as a result of parser callbacks which can occur at
2415 // many points during the parsing of a struct declaration (because
2416 // the #pragma tokens are effectively skipped over during the
2417 // parsing of the struct).
2418 if (unsigned Alignment = PackContext.getAlignment())
2419 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002420
2421 if (Attr)
2422 ProcessDeclAttributeList(New, Attr);
2423
2424 return New;
2425}
2426
2427
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002428/// Collect the instance variables declared in an Objective-C object. Used in
2429/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002430static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002431 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002432 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002433 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2434
2435 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002436 for (ObjCInterfaceDecl::ivar_iterator
2437 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2438
Ted Kremenek01e67792008-08-20 03:26:33 +00002439 ObjCIvarDecl* ID = *I;
2440 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2441 ID->getIdentifier(),
2442 ID->getType(),
2443 ID->getBitWidth()));
2444 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002445}
2446
2447/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2448/// instance variables of ClassName into Decls.
2449void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2450 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002451 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002452 // Check that ClassName is a valid class
2453 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2454 if (!Class) {
2455 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2456 return;
2457 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002458 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002459 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002460}
2461
Eli Friedman1b76ada2008-06-03 21:01:11 +00002462QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
2463 // This method tries to turn a variable array into a constant
2464 // array even when the size isn't an ICE. This is necessary
2465 // for compatibility with code that depends on gcc's buggy
2466 // constant expression folding, like struct {char x[(int)(char*)2];}
2467 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00002468 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002469 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00002470 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2471 llvm::APSInt &Res = Result.getInt();
2472 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2473 return Context.getConstantArrayType(VLATy->getElementType(),
2474 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002475 }
2476 }
2477 return QualType();
2478}
2479
Steve Naroff08d92e42007-09-15 18:49:24 +00002480/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002481/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002482Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002483 SourceLocation DeclStart,
2484 Declarator &D, ExprTy *BitfieldWidth) {
2485 IdentifierInfo *II = D.getIdentifier();
2486 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002487 SourceLocation Loc = DeclStart;
2488 if (II) Loc = D.getIdentifierLoc();
2489
2490 // FIXME: Unnamed fields can be handled in various different ways, for
2491 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002492
Reid Spencer5f016e22007-07-11 17:01:13 +00002493 if (BitWidth) {
2494 // TODO: Validate.
2495 //printf("WARNING: BITFIELDS IGNORED!\n");
2496
2497 // 6.7.2.1p3
2498 // 6.7.2.1p4
2499
2500 } else {
2501 // Not a bitfield.
2502
2503 // validate II.
2504
2505 }
2506
2507 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002508 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2509 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002510
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2512 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002513 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002514 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2515 if (!FixedTy.isNull()) {
2516 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2517 T = FixedTy;
2518 } else {
2519 // FIXME: This diagnostic needs work
2520 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2521 InvalidDecl = true;
2522 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002523 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002525 FieldDecl *NewFD;
2526
2527 if (getLangOptions().CPlusPlus) {
2528 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2529 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2530 Loc, II, T, BitWidth);
2531 if (II)
2532 PushOnScopeChains(NewFD, S);
2533 }
2534 else
2535 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002536
Chris Lattner3ff30c82008-06-29 00:02:00 +00002537 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002538
Steve Naroff5912a352007-08-28 20:14:24 +00002539 if (D.getInvalidType() || InvalidDecl)
2540 NewFD->setInvalidDecl();
2541 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002542}
2543
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002544/// TranslateIvarVisibility - Translate visibility from a token ID to an
2545/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002546static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002547TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002548 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002549 default: assert(0 && "Unknown visitibility kind");
2550 case tok::objc_private: return ObjCIvarDecl::Private;
2551 case tok::objc_public: return ObjCIvarDecl::Public;
2552 case tok::objc_protected: return ObjCIvarDecl::Protected;
2553 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002554 }
2555}
2556
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002557/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2558/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002559Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002560 SourceLocation DeclStart,
2561 Declarator &D, ExprTy *BitfieldWidth,
2562 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002563 IdentifierInfo *II = D.getIdentifier();
2564 Expr *BitWidth = (Expr*)BitfieldWidth;
2565 SourceLocation Loc = DeclStart;
2566 if (II) Loc = D.getIdentifierLoc();
2567
2568 // FIXME: Unnamed fields can be handled in various different ways, for
2569 // example, unnamed unions inject all members into the struct namespace!
2570
2571
2572 if (BitWidth) {
2573 // TODO: Validate.
2574 //printf("WARNING: BITFIELDS IGNORED!\n");
2575
2576 // 6.7.2.1p3
2577 // 6.7.2.1p4
2578
2579 } else {
2580 // Not a bitfield.
2581
2582 // validate II.
2583
2584 }
2585
2586 QualType T = GetTypeForDeclarator(D, S);
2587 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2588 bool InvalidDecl = false;
2589
2590 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2591 // than a variably modified type.
2592 if (T->isVariablyModifiedType()) {
2593 // FIXME: This diagnostic needs work
2594 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2595 InvalidDecl = true;
2596 }
2597
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002598 // Get the visibility (access control) for this ivar.
2599 ObjCIvarDecl::AccessControl ac =
2600 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2601 : ObjCIvarDecl::None;
2602
2603 // Construct the decl.
2604 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002605 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002606
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002607 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002608 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002609
2610 if (D.getInvalidType() || InvalidDecl)
2611 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002612
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002613 return NewID;
2614}
2615
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002616void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002617 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002618 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002619 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002620 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002621 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2622 assert(EnclosingDecl && "missing record or interface decl");
2623 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2624
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002625 if (Record)
2626 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2627 // Diagnose code like:
2628 // struct S { struct S {} X; };
2629 // We discover this when we complete the outer S. Reject and ignore the
2630 // outer S.
2631 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2632 DefRecord->getKindName());
2633 Diag(RecLoc, diag::err_previous_definition);
2634 Record->setInvalidDecl();
2635 return;
2636 }
2637
Reid Spencer5f016e22007-07-11 17:01:13 +00002638 // Verify that all the fields are okay.
2639 unsigned NumNamedMembers = 0;
2640 llvm::SmallVector<FieldDecl*, 32> RecFields;
2641 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002642
Reid Spencer5f016e22007-07-11 17:01:13 +00002643 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002644
Steve Naroff74216642007-09-14 22:20:54 +00002645 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2646 assert(FD && "missing field decl");
2647
2648 // Remember all fields.
2649 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002650
2651 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002652 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002653
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002655 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002656 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002657 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002658 FD->setInvalidDecl();
2659 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002660 continue;
2661 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002662 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2663 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002664 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002665 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002666 FD->setInvalidDecl();
2667 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002668 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002669 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002670 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002671 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002672 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002674 FD->setInvalidDecl();
2675 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002676 continue;
2677 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002678 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002679 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2680 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002681 FD->setInvalidDecl();
2682 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002683 continue;
2684 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002685 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002686 if (Record)
2687 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002688 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002689 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2690 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002691 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2693 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002694 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002695 Record->setHasFlexibleArrayMember(true);
2696 } else {
2697 // If this is a struct/class and this is not the last element, reject
2698 // it. Note that GCC supports variable sized arrays in the middle of
2699 // structures.
2700 if (i != NumFields-1) {
2701 Diag(FD->getLocation(), diag::err_variable_sized_type_in_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 // We support flexible arrays at the end of structs in other structs
2708 // as an extension.
2709 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2710 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002711 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002712 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002713 }
2714 }
2715 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002716 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002717 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002718 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2719 FD->getName());
2720 FD->setInvalidDecl();
2721 EnclosingDecl->setInvalidDecl();
2722 continue;
2723 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002724 // Keep track of the number of named members.
2725 if (IdentifierInfo *II = FD->getIdentifier()) {
2726 // Detect duplicate member names.
2727 if (!FieldIDs.insert(II)) {
2728 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2729 // Find the previous decl.
2730 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002731 for (unsigned i = 0; ; ++i) {
2732 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002733 if (RecFields[i]->getIdentifier() == II) {
2734 PrevLoc = RecFields[i]->getLocation();
2735 break;
2736 }
2737 }
2738 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002739 FD->setInvalidDecl();
2740 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 continue;
2742 }
2743 ++NumNamedMembers;
2744 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002745 }
2746
Reid Spencer5f016e22007-07-11 17:01:13 +00002747 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002748 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002749 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002750 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2751 // Sema::ActOnFinishCXXClassDef.
2752 if (!isa<CXXRecordDecl>(Record))
2753 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002754 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002755 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2756 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2757 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2758 else if (ObjCImplementationDecl *IMPDecl =
2759 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002760 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2761 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002762 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002763 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002764 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002765
2766 if (Attr)
2767 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002768}
2769
Steve Naroff08d92e42007-09-15 18:49:24 +00002770Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 DeclTy *lastEnumConst,
2772 SourceLocation IdLoc, IdentifierInfo *Id,
2773 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002774 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 EnumConstantDecl *LastEnumConst =
2776 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2777 Expr *Val = static_cast<Expr*>(val);
2778
Chris Lattner31e05722007-08-26 06:24:45 +00002779 // The scope passed in may not be a decl scope. Zip up the scope tree until
2780 // we find one that is.
2781 while ((S->getFlags() & Scope::DeclScope) == 0)
2782 S = S->getParent();
2783
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 // Verify that there isn't already something declared with this name in this
2785 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002786 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002787 // When in C++, we may get a TagDecl with the same name; in this case the
2788 // enum constant will 'hide' the tag.
2789 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2790 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002791 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 if (isa<EnumConstantDecl>(PrevDecl))
2793 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2794 else
2795 Diag(IdLoc, diag::err_redefinition, Id->getName());
2796 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002797 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002798 return 0;
2799 }
2800 }
2801
2802 llvm::APSInt EnumVal(32);
2803 QualType EltTy;
2804 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002805 // Make sure to promote the operand type to int.
2806 UsualUnaryConversions(Val);
2807
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2809 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002810 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002811 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2812 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002813 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002814 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002815 } else {
2816 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002818 }
2819
2820 if (!Val) {
2821 if (LastEnumConst) {
2822 // Assign the last value + 1.
2823 EnumVal = LastEnumConst->getInitVal();
2824 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002825
2826 // Check for overflow on increment.
2827 if (EnumVal < LastEnumConst->getInitVal())
2828 Diag(IdLoc, diag::warn_enum_value_overflow);
2829
Chris Lattnerb7416f92007-08-27 17:37:24 +00002830 EltTy = LastEnumConst->getType();
2831 } else {
2832 // First value, set to zero.
2833 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002834 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002835 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002836 }
2837
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002838 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002839 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2840 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002841 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002842
2843 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002844 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002845 return New;
2846}
2847
Steve Naroff02408c62008-08-07 14:08:16 +00002848// FIXME: For consistency with ActOnFields(), we should have the parser
2849// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002850void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002851 DeclTy **Elements, unsigned NumElements) {
2852 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002853
Steve Naroff02408c62008-08-07 14:08:16 +00002854 if (Enum && Enum->isDefinition()) {
2855 // Diagnose code like:
2856 // enum e0 {
2857 // E0 = sizeof(enum e0 { E1 })
2858 // };
2859 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2860 Enum->getName());
2861 Diag(EnumLoc, diag::err_previous_definition);
2862 Enum->setInvalidDecl();
2863 return;
2864 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002865 // TODO: If the result value doesn't fit in an int, it must be a long or long
2866 // long value. ISO C does not support this, but GCC does as an extension,
2867 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002868 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002869
Chris Lattnerac609682007-08-28 06:15:15 +00002870 // Verify that all the values are okay, compute the size of the values, and
2871 // reverse the list.
2872 unsigned NumNegativeBits = 0;
2873 unsigned NumPositiveBits = 0;
2874
2875 // Keep track of whether all elements have type int.
2876 bool AllElementsInt = true;
2877
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 EnumConstantDecl *EltList = 0;
2879 for (unsigned i = 0; i != NumElements; ++i) {
2880 EnumConstantDecl *ECD =
2881 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2882 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002883
2884 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002885 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002886 assert(InitVal.getBitWidth() >= IntWidth &&
2887 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002888 if (InitVal.getBitWidth() > IntWidth) {
2889 llvm::APSInt V(InitVal);
2890 V.trunc(IntWidth);
2891 V.extend(InitVal.getBitWidth());
2892 if (V != InitVal)
2893 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002894 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002895 }
Chris Lattnerac609682007-08-28 06:15:15 +00002896
2897 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002898 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002899 NumPositiveBits = std::max(NumPositiveBits,
2900 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002901 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002902 NumNegativeBits = std::max(NumNegativeBits,
2903 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002904
Chris Lattnerac609682007-08-28 06:15:15 +00002905 // Keep track of whether every enum element has type int (very commmon).
2906 if (AllElementsInt)
2907 AllElementsInt = ECD->getType() == Context.IntTy;
2908
Reid Spencer5f016e22007-07-11 17:01:13 +00002909 ECD->setNextDeclarator(EltList);
2910 EltList = ECD;
2911 }
2912
Chris Lattnerac609682007-08-28 06:15:15 +00002913 // Figure out the type that should be used for this enum.
2914 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2915 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002916 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002917
2918 if (NumNegativeBits) {
2919 // If there is a negative value, figure out the smallest integer type (of
2920 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002921 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002922 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002923 BestWidth = IntWidth;
2924 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002925 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002926
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002927 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002928 BestType = Context.LongTy;
2929 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002930 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002931
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002932 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002933 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2934 BestType = Context.LongLongTy;
2935 }
2936 }
2937 } else {
2938 // If there is no negative value, figure out which of uint, ulong, ulonglong
2939 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002940 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002941 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002942 BestWidth = IntWidth;
2943 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002944 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002945 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002946 } else {
2947 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002948 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002949 "How could an initializer get larger than ULL?");
2950 BestType = Context.UnsignedLongLongTy;
2951 }
2952 }
2953
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002954 // Loop over all of the enumerator constants, changing their types to match
2955 // the type of the enum if needed.
2956 for (unsigned i = 0; i != NumElements; ++i) {
2957 EnumConstantDecl *ECD =
2958 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2959 if (!ECD) continue; // Already issued a diagnostic.
2960
2961 // Standard C says the enumerators have int type, but we allow, as an
2962 // extension, the enumerators to be larger than int size. If each
2963 // enumerator value fits in an int, type it as an int, otherwise type it the
2964 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2965 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002966 if (ECD->getType() == Context.IntTy) {
2967 // Make sure the init value is signed.
2968 llvm::APSInt IV = ECD->getInitVal();
2969 IV.setIsSigned(true);
2970 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002971 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002972 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002973
2974 // Determine whether the value fits into an int.
2975 llvm::APSInt InitVal = ECD->getInitVal();
2976 bool FitsInInt;
2977 if (InitVal.isUnsigned() || !InitVal.isNegative())
2978 FitsInInt = InitVal.getActiveBits() < IntWidth;
2979 else
2980 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2981
2982 // If it fits into an integer type, force it. Otherwise force it to match
2983 // the enum decl type.
2984 QualType NewTy;
2985 unsigned NewWidth;
2986 bool NewSign;
2987 if (FitsInInt) {
2988 NewTy = Context.IntTy;
2989 NewWidth = IntWidth;
2990 NewSign = true;
2991 } else if (ECD->getType() == BestType) {
2992 // Already the right type!
2993 continue;
2994 } else {
2995 NewTy = BestType;
2996 NewWidth = BestWidth;
2997 NewSign = BestType->isSignedIntegerType();
2998 }
2999
3000 // Adjust the APSInt value.
3001 InitVal.extOrTrunc(NewWidth);
3002 InitVal.setIsSigned(NewSign);
3003 ECD->setInitVal(InitVal);
3004
3005 // Adjust the Expr initializer and type.
3006 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
3007 ECD->setType(NewTy);
3008 }
Chris Lattnerac609682007-08-28 06:15:15 +00003009
Chris Lattnere00b18c2007-08-28 18:24:31 +00003010 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003011 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003012}
3013
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003014Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3015 ExprTy *expr) {
3016 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3017
Chris Lattner8e25d862008-03-16 00:16:02 +00003018 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003019}
3020
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003021Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003022 SourceLocation LBrace,
3023 SourceLocation RBrace,
3024 const char *Lang,
3025 unsigned StrSize,
3026 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003027 LinkageSpecDecl::LanguageIDs Language;
3028 Decl *dcl = static_cast<Decl *>(D);
3029 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3030 Language = LinkageSpecDecl::lang_c;
3031 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3032 Language = LinkageSpecDecl::lang_cxx;
3033 else {
3034 Diag(Loc, diag::err_bad_language);
3035 return 0;
3036 }
3037
3038 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003039 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003040}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003041
3042void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3043 ExprTy *alignment, SourceLocation PragmaLoc,
3044 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3045 Expr *Alignment = static_cast<Expr *>(alignment);
3046
3047 // If specified then alignment must be a "small" power of two.
3048 unsigned AlignmentVal = 0;
3049 if (Alignment) {
3050 llvm::APSInt Val;
3051 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3052 !Val.isPowerOf2() ||
3053 Val.getZExtValue() > 16) {
3054 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3055 delete Alignment;
3056 return; // Ignore
3057 }
3058
3059 AlignmentVal = (unsigned) Val.getZExtValue();
3060 }
3061
3062 switch (Kind) {
3063 case Action::PPK_Default: // pack([n])
3064 PackContext.setAlignment(AlignmentVal);
3065 break;
3066
3067 case Action::PPK_Show: // pack(show)
3068 // Show the current alignment, making sure to show the right value
3069 // for the default.
3070 AlignmentVal = PackContext.getAlignment();
3071 // FIXME: This should come from the target.
3072 if (AlignmentVal == 0)
3073 AlignmentVal = 8;
3074 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
3075 break;
3076
3077 case Action::PPK_Push: // pack(push [, id] [, [n])
3078 PackContext.push(Name);
3079 // Set the new alignment if specified.
3080 if (Alignment)
3081 PackContext.setAlignment(AlignmentVal);
3082 break;
3083
3084 case Action::PPK_Pop: // pack(pop [, id] [, n])
3085 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3086 // "#pragma pack(pop, identifier, n) is undefined"
3087 if (Alignment && Name)
3088 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3089
3090 // Do the pop.
3091 if (!PackContext.pop(Name)) {
3092 // If a name was specified then failure indicates the name
3093 // wasn't found. Otherwise failure indicates the stack was
3094 // empty.
3095 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3096 Name ? "no record matching name" : "stack empty");
3097
3098 // FIXME: Warn about popping named records as MSVC does.
3099 } else {
3100 // Pop succeeded, set the new alignment if specified.
3101 if (Alignment)
3102 PackContext.setAlignment(AlignmentVal);
3103 }
3104 break;
3105
3106 default:
3107 assert(0 && "Invalid #pragma pack kind.");
3108 }
3109}
3110
3111bool PragmaPackStack::pop(IdentifierInfo *Name) {
3112 if (Stack.empty())
3113 return false;
3114
3115 // If name is empty just pop top.
3116 if (!Name) {
3117 Alignment = Stack.back().first;
3118 Stack.pop_back();
3119 return true;
3120 }
3121
3122 // Otherwise, find the named record.
3123 for (unsigned i = Stack.size(); i != 0; ) {
3124 --i;
3125 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3126 // Found it, pop up to and including this record.
3127 Alignment = Stack[i].first;
3128 Stack.erase(Stack.begin() + i, Stack.end());
3129 return true;
3130 }
3131 }
3132
3133 return false;
3134}