blob: 40008579a9af7380eedd4c8b875a0775ccc2171f [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"
28using namespace clang;
29
Argyrios Kyrtzidis39caa082008-08-01 10:35:27 +000030Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroffb327ce02008-04-02 14:35:35 +000031 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
32
Douglas Gregor2ce52f32008-04-13 21:07:44 +000033 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
34 isa<ObjCInterfaceDecl>(IIDecl) ||
35 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000036 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000037 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000038}
39
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000040DeclContext *Sema::getDCParent(DeclContext *DC) {
41 // If CurContext is a ObjC method, getParent() will return NULL.
42 if (isa<ObjCMethodDecl>(DC))
43 return Context.getTranslationUnitDecl();
44
45 // A C++ inline method is parsed *after* the topmost class it was declared in
46 // is fully parsed (it's "complete").
47 // The parsing of a C++ inline method happens at the declaration context of
48 // the topmost (non-nested) class it is declared in.
49 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
50 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
51 DC = MD->getParent();
52 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
53 DC = RD;
54
55 // Return the declaration context of the topmost class the inline method is
56 // declared in.
57 return DC;
58 }
59
60 return DC->getParent();
61}
62
Chris Lattner9fdf9c62008-04-22 18:39:57 +000063void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000064 assert(getDCParent(DC) == CurContext &&
65 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000066 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000067}
68
Chris Lattnerb048c982008-04-06 04:47:34 +000069void Sema::PopDeclContext() {
70 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000071 CurContext = getDCParent(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000072}
73
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000074/// Add this decl to the scope shadowed decl chains.
75void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000076 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000077
78 // C++ [basic.scope]p4:
79 // -- exactly one declaration shall declare a class name or
80 // enumeration name that is not a typedef name and the other
81 // declarations shall all refer to the same object or
82 // enumerator, or all refer to functions and function templates;
83 // in this case the class name or enumeration name is hidden.
84 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
85 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000086 IdentifierResolver::iterator
87 I = IdResolver.begin(TD->getIdentifier(),
88 TD->getDeclContext(), false/*LookInParentCtx*/);
89 if (I != IdResolver.end() &&
90 IdResolver.isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000091 // There is already a declaration with the same name in the same
92 // scope. It must be found before we find the new declaration,
93 // so swap the order on the shadowed declaration chain.
94
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000095 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000096 return;
97 }
98 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000099 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000100}
101
Steve Naroffb216c882007-10-09 22:01:59 +0000102void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000103 if (S->decl_empty()) return;
104 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000105
Reid Spencer5f016e22007-07-11 17:01:13 +0000106 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
107 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000108 Decl *TmpD = static_cast<Decl*>(*I);
109 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000110
111 if (isa<CXXFieldDecl>(TmpD)) continue;
112
113 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
114 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000115
Reid Spencer5f016e22007-07-11 17:01:13 +0000116 IdentifierInfo *II = D->getIdentifier();
117 if (!II) continue;
118
Ted Kremeneka89d1972008-09-03 18:03:35 +0000119 // We only want to remove the decls from the identifier decl chains for
120 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000121 if (S->getFnParent() != 0)
122 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000123
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000124 // Chain this decl to the containing DeclContext.
125 D->setNext(CurContext->getDeclChain());
126 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000127 }
128}
129
Steve Naroffe8043c32008-04-01 23:04:06 +0000130/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
131/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000132ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000133 // The third "scope" argument is 0 since we aren't enabling lazy built-in
134 // creation from this context.
135 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000136
Steve Naroffb327ce02008-04-02 14:35:35 +0000137 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000138}
139
Steve Naroffe8043c32008-04-01 23:04:06 +0000140/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000141/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000142Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
143 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000144 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000145 unsigned NS = NSI;
146 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
147 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000148
Reid Spencer5f016e22007-07-11 17:01:13 +0000149 // Scan up the scope chain looking for a decl that matches this identifier
150 // that is in the appropriate namespace. This search should not take long, as
151 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000152 for (IdentifierResolver::iterator
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000153 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000154 if ((*I)->getIdentifierNamespace() & NS)
155 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000156
Reid Spencer5f016e22007-07-11 17:01:13 +0000157 // If we didn't find a use of this identifier, and if the identifier
158 // corresponds to a compiler builtin, create the decl object for the builtin
159 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000160 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000161 if (enableLazyBuiltinCreation) {
162 // If this is a builtin on this (or all) targets, create the decl.
163 if (unsigned BuiltinID = II->getBuiltinID())
164 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
165 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000166 if (getLangOptions().ObjC1) {
167 // @interface and @compatibility_alias introduce typedef-like names.
168 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000169 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000170 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000171 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
172 if (IDI != ObjCInterfaceDecls.end())
173 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000174 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
175 if (I != ObjCAliasDecls.end())
176 return I->second->getClassInterface();
177 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 }
179 return 0;
180}
181
Chris Lattner95e2c712008-05-05 22:18:14 +0000182void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000183 if (!Context.getBuiltinVaListType().isNull())
184 return;
185
186 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000187 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000188 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000189 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
190}
191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
193/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000194ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
195 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 Builtin::ID BID = (Builtin::ID)bid;
197
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000198 if (BID == Builtin::BI__builtin_va_start ||
Chris Lattner95e2c712008-05-05 22:18:14 +0000199 BID == Builtin::BI__builtin_va_copy ||
Chris Lattnerf8396b62008-07-09 17:26:36 +0000200 BID == Builtin::BI__builtin_va_end ||
201 BID == Builtin::BI__builtin_stdarg_start)
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000202 InitBuiltinVaListType();
203
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000204 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000205 FunctionDecl *New = FunctionDecl::Create(Context,
206 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000207 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000208 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000209
Chris Lattner95e2c712008-05-05 22:18:14 +0000210 // Create Decl objects for each parameter, adding them to the
211 // FunctionDecl.
212 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
213 llvm::SmallVector<ParmVarDecl*, 16> Params;
214 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
215 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
216 FT->getArgType(i), VarDecl::None, 0,
217 0));
218 New->setParams(&Params[0], Params.size());
219 }
220
221
222
Chris Lattner7f925cc2008-04-11 07:00:53 +0000223 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000224 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000225 return New;
226}
227
228/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
229/// and scope as a previous declaration 'Old'. Figure out how to resolve this
230/// situation, merging decls or emitting diagnostics as appropriate.
231///
Steve Naroffe8043c32008-04-01 23:04:06 +0000232TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000233 // Allow multiple definitions for ObjC built-in typedefs.
234 // FIXME: Verify the underlying types are equivalent!
235 if (getLangOptions().ObjC1) {
236 const IdentifierInfo *typeIdent = New->getIdentifier();
237 if (typeIdent == Ident_id) {
238 Context.setObjCIdType(New);
239 return New;
240 } else if (typeIdent == Ident_Class) {
241 Context.setObjCClassType(New);
242 return New;
243 } else if (typeIdent == Ident_SEL) {
244 Context.setObjCSelType(New);
245 return New;
246 } else if (typeIdent == Ident_Protocol) {
247 Context.setObjCProtoType(New->getUnderlyingType());
248 return New;
249 }
250 // Fall through - the typedef name was not a builtin type.
251 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000252 // Verify the old decl was also a typedef.
253 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
254 if (!Old) {
255 Diag(New->getLocation(), diag::err_redefinition_different_kind,
256 New->getName());
257 Diag(OldD->getLocation(), diag::err_previous_definition);
258 return New;
259 }
260
Chris Lattner99cb9972008-07-25 18:44:27 +0000261 // If the typedef types are not identical, reject them in all languages and
262 // with any extensions enabled.
263 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
264 Context.getCanonicalType(Old->getUnderlyingType()) !=
265 Context.getCanonicalType(New->getUnderlyingType())) {
266 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
267 New->getUnderlyingType().getAsString(),
268 Old->getUnderlyingType().getAsString());
269 Diag(Old->getLocation(), diag::err_previous_definition);
270 return Old;
271 }
272
Eli Friedman54ecfce2008-06-11 06:20:39 +0000273 if (getLangOptions().Microsoft) return New;
274
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000275 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
276 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
277 // *either* declaration is in a system header. The code below implements
278 // this adhoc compatibility rule. FIXME: The following code will not
279 // work properly when compiling ".i" files (containing preprocessed output).
280 SourceManager &SrcMgr = Context.getSourceManager();
Nico Weber491be732008-08-29 17:02:23 +0000281 if (SrcMgr.isInSystemHeader(Old->getLocation()))
282 return New;
283 if (SrcMgr.isInSystemHeader(New->getLocation()))
284 return New;
Eli Friedman54ecfce2008-06-11 06:20:39 +0000285
Ted Kremenek2d05c082008-05-23 21:28:18 +0000286 Diag(New->getLocation(), diag::err_redefinition, New->getName());
287 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000288 return New;
289}
290
Chris Lattner6b6b5372008-06-26 18:38:35 +0000291/// DeclhasAttr - returns true if decl Declaration already has the target
292/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000293static bool DeclHasAttr(const Decl *decl, const Attr *target) {
294 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
295 if (attr->getKind() == target->getKind())
296 return true;
297
298 return false;
299}
300
301/// MergeAttributes - append attributes from the Old decl to the New one.
302static void MergeAttributes(Decl *New, Decl *Old) {
303 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
304
Chris Lattnerddee4232008-03-03 03:28:21 +0000305 while (attr) {
306 tmp = attr;
307 attr = attr->getNext();
308
309 if (!DeclHasAttr(New, tmp)) {
310 New->addAttr(tmp);
311 } else {
312 tmp->setNext(0);
313 delete(tmp);
314 }
315 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000316
317 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000318}
319
Chris Lattner04421082008-04-08 04:40:51 +0000320/// MergeFunctionDecl - We just parsed a function 'New' from
321/// declarator D which has the same name and scope as a previous
322/// declaration 'Old'. Figure out how to resolve this situation,
323/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000324/// Redeclaration will be set true if thisNew is a redeclaration OldD.
325FunctionDecl *
326Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
327 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000328 // Verify the old decl was also a function.
329 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
330 if (!Old) {
331 Diag(New->getLocation(), diag::err_redefinition_different_kind,
332 New->getName());
333 Diag(OldD->getLocation(), diag::err_previous_definition);
334 return New;
335 }
Chris Lattner04421082008-04-08 04:40:51 +0000336
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000337 QualType OldQType = Context.getCanonicalType(Old->getType());
338 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000339
Chris Lattner04421082008-04-08 04:40:51 +0000340 // C++ [dcl.fct]p3:
341 // All declarations for a function shall agree exactly in both the
342 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000343 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
344 MergeAttributes(New, Old);
345 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000346 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000347 }
Chris Lattner04421082008-04-08 04:40:51 +0000348
349 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000350 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000351 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000352 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000353 MergeAttributes(New, Old);
354 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000355 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000356 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000357
Steve Naroff837618c2008-01-16 15:01:34 +0000358 // A function that has already been declared has been redeclared or defined
359 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000360 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000361 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000362 PrevDiag = diag::err_previous_definition;
363 else if (Old->isImplicit())
364 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000365 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000366 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000367
Reid Spencer5f016e22007-07-11 17:01:13 +0000368 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
369 // TODO: This is totally simplistic. It should handle merging functions
370 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000371 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
372 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 return New;
374}
375
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000376/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000377static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000378 if (VD->isFileVarDecl())
379 return (!VD->getInit() &&
380 (VD->getStorageClass() == VarDecl::None ||
381 VD->getStorageClass() == VarDecl::Static));
382 return false;
383}
384
385/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
386/// when dealing with C "tentative" external object definitions (C99 6.9.2).
387void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
388 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000389 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000390
391 for (IdentifierResolver::iterator
392 I = IdResolver.begin(VD->getIdentifier(),
393 VD->getDeclContext(), false/*LookInParentCtx*/),
394 E = IdResolver.end(); I != E; ++I) {
395 if (*I != VD && IdResolver.isDeclInScope(*I, VD->getDeclContext(), S)) {
396 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
397
Steve Narofff855e6f2008-08-10 15:20:13 +0000398 // Handle the following case:
399 // int a[10];
400 // int a[]; - the code below makes sure we set the correct type.
401 // int a[11]; - this is an error, size isn't 10.
402 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
403 OldDecl->getType()->isConstantArrayType())
404 VD->setType(OldDecl->getType());
405
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000406 // Check for "tentative" definitions. We can't accomplish this in
407 // MergeVarDecl since the initializer hasn't been attached.
408 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
409 continue;
410
411 // Handle __private_extern__ just like extern.
412 if (OldDecl->getStorageClass() != VarDecl::Extern &&
413 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
414 VD->getStorageClass() != VarDecl::Extern &&
415 VD->getStorageClass() != VarDecl::PrivateExtern) {
416 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
417 Diag(OldDecl->getLocation(), diag::err_previous_definition);
418 }
419 }
420 }
421}
422
Reid Spencer5f016e22007-07-11 17:01:13 +0000423/// MergeVarDecl - We just parsed a variable 'New' which has the same name
424/// and scope as a previous declaration 'Old'. Figure out how to resolve this
425/// situation, merging decls or emitting diagnostics as appropriate.
426///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000427/// Tentative definition rules (C99 6.9.2p2) are checked by
428/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
429/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000430///
Steve Naroffe8043c32008-04-01 23:04:06 +0000431VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 // Verify the old decl was also a variable.
433 VarDecl *Old = dyn_cast<VarDecl>(OldD);
434 if (!Old) {
435 Diag(New->getLocation(), diag::err_redefinition_different_kind,
436 New->getName());
437 Diag(OldD->getLocation(), diag::err_previous_definition);
438 return New;
439 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000440
441 MergeAttributes(New, Old);
442
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000444 QualType OldCType = Context.getCanonicalType(Old->getType());
445 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000446 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000447 Diag(New->getLocation(), diag::err_redefinition, New->getName());
448 Diag(Old->getLocation(), diag::err_previous_definition);
449 return New;
450 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000451 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
452 if (New->getStorageClass() == VarDecl::Static &&
453 (Old->getStorageClass() == VarDecl::None ||
454 Old->getStorageClass() == VarDecl::Extern)) {
455 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
456 Diag(Old->getLocation(), diag::err_previous_definition);
457 return New;
458 }
459 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
460 if (New->getStorageClass() != VarDecl::Static &&
461 Old->getStorageClass() == VarDecl::Static) {
462 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
463 Diag(Old->getLocation(), diag::err_previous_definition);
464 return New;
465 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000466 // File scoped variables are analyzed in FinalizeDeclaratorGroup.
467 if (!New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000468 Diag(New->getLocation(), diag::err_redefinition, New->getName());
469 Diag(Old->getLocation(), diag::err_previous_definition);
470 }
471 return New;
472}
473
Chris Lattner04421082008-04-08 04:40:51 +0000474/// CheckParmsForFunctionDef - Check that the parameters of the given
475/// function are appropriate for the definition of a function. This
476/// takes care of any checks that cannot be performed on the
477/// declaration itself, e.g., that the types of each of the function
478/// parameters are complete.
479bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
480 bool HasInvalidParm = false;
481 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
482 ParmVarDecl *Param = FD->getParamDecl(p);
483
484 // C99 6.7.5.3p4: the parameters in a parameter type list in a
485 // function declarator that is part of a function definition of
486 // that function shall not have incomplete type.
487 if (Param->getType()->isIncompleteType() &&
488 !Param->isInvalidDecl()) {
489 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
490 Param->getType().getAsString());
491 Param->setInvalidDecl();
492 HasInvalidParm = true;
493 }
494 }
495
496 return HasInvalidParm;
497}
498
Reid Spencer5f016e22007-07-11 17:01:13 +0000499/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
500/// no declarator (e.g. "struct foo;") is parsed.
501Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
502 // TODO: emit error on 'int;' or 'const enum foo;'.
503 // TODO: emit error on 'typedef int;'
504 // if (!DS.isMissingDeclaratorOk()) Diag(...);
505
Steve Naroff92199282007-11-17 21:37:36 +0000506 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000507}
508
Steve Naroffd0091aa2008-01-10 22:15:12 +0000509bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000510 // Get the type before calling CheckSingleAssignmentConstraints(), since
511 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000512 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000513
Chris Lattner5cf216b2008-01-04 18:04:52 +0000514 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
515 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
516 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000517}
518
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000519bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000520 const ArrayType *AT = Context.getAsArrayType(DeclT);
521
522 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000523 // C99 6.7.8p14. We have an array of character type with unknown size
524 // being initialized to a string literal.
525 llvm::APSInt ConstVal(32);
526 ConstVal = strLiteral->getByteLength() + 1;
527 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000528 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000529 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000530 } else {
531 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000532 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000533 // FIXME: Avoid truncation for 64-bit length strings.
534 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000535 Diag(strLiteral->getSourceRange().getBegin(),
536 diag::warn_initializer_string_for_char_array_too_long,
537 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000538 }
539 // Set type from "char *" to "constant array of char".
540 strLiteral->setType(DeclT);
541 // For now, we always return false (meaning success).
542 return false;
543}
544
545StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000546 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000547 if (AT && AT->getElementType()->isCharType()) {
548 return dyn_cast<StringLiteral>(Init);
549 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000550 return 0;
551}
552
Steve Naroffa9960332008-01-25 00:51:06 +0000553bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000554 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
555 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000556 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroffca107302008-01-21 23:53:58 +0000557 return Diag(VAT->getSizeExpr()->getLocStart(),
558 diag::err_variable_object_no_init,
559 VAT->getSizeExpr()->getSourceRange());
560
Steve Naroff2fdc3742007-12-10 22:44:33 +0000561 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
562 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000563 // FIXME: Handle wide strings
564 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
565 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000566
567 if (DeclType->isArrayType())
568 return Diag(Init->getLocStart(),
569 diag::err_array_init_list_required,
570 Init->getSourceRange());
571
Steve Naroffd0091aa2008-01-10 22:15:12 +0000572 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000573 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000574
Steve Naroff0cca7492008-05-01 22:18:59 +0000575 InitListChecker CheckInitList(this, InitList, DeclType);
576 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000577}
578
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000579Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000580Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000581 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 IdentifierInfo *II = D.getIdentifier();
583
Chris Lattnere80a59c2007-07-25 00:24:17 +0000584 // All of these full declarators require an identifier. If it doesn't have
585 // one, the ParsedFreeStandingDeclSpec action should be used.
586 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000587 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000588 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000589 D.getDeclSpec().getSourceRange(), D.getSourceRange());
590 return 0;
591 }
592
Chris Lattner31e05722007-08-26 06:24:45 +0000593 // The scope passed in may not be a decl scope. Zip up the scope tree until
594 // we find one that is.
595 while ((S->getFlags() & Scope::DeclScope) == 0)
596 S = S->getParent();
597
Reid Spencer5f016e22007-07-11 17:01:13 +0000598 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000599 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000600 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000601 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000602
603 // In C++, the previous declaration we find might be a tag type
604 // (class or enum). In this case, the new declaration will hide the
605 // tag type.
606 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
607 PrevDecl = 0;
608
Chris Lattner41af0932007-11-14 06:34:38 +0000609 QualType R = GetTypeForDeclarator(D, S);
610 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
611
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000613 // Check that there are no default arguments (C++ only).
614 if (getLangOptions().CPlusPlus)
615 CheckExtraCXXDefaultArguments(D);
616
Chris Lattner41af0932007-11-14 06:34:38 +0000617 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000618 if (!NewTD) return 0;
619
620 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000621 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000622 // Merge the decl with the existing one if appropriate. If the decl is
623 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000624 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000625 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
626 if (NewTD == 0) return 0;
627 }
628 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000629 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000630 // C99 6.7.7p2: If a typedef name specifies a variably modified type
631 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000632 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
633 // FIXME: Diagnostic needs to be fixed.
634 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000635 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000636 }
637 }
Chris Lattner41af0932007-11-14 06:34:38 +0000638 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000639 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 switch (D.getDeclSpec().getStorageClassSpec()) {
641 default: assert(0 && "Unknown storage class!");
642 case DeclSpec::SCS_auto:
643 case DeclSpec::SCS_register:
644 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
645 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000646 InvalidDecl = true;
647 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
649 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
650 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000651 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 }
653
Chris Lattnera98e58d2008-03-15 21:24:04 +0000654 bool isInline = D.getDeclSpec().isInlineSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000655 FunctionDecl *NewFD;
656 if (D.getContext() == Declarator::MemberContext) {
657 // This is a C++ method declaration.
658 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
659 D.getIdentifierLoc(), II, R,
660 (SC == FunctionDecl::Static), isInline,
661 LastDeclarator);
662 } else {
663 NewFD = FunctionDecl::Create(Context, CurContext,
664 D.getIdentifierLoc(),
665 II, R, SC, isInline,
666 LastDeclarator);
667 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000668 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000669 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000670
Daniel Dunbara80f8742008-08-05 01:35:17 +0000671 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000672 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000673 // The parser guarantees this is a string.
674 StringLiteral *SE = cast<StringLiteral>(E);
675 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
676 SE->getByteLength())));
677 }
678
Chris Lattner04421082008-04-08 04:40:51 +0000679 // Copy the parameter declarations from the declarator D to
680 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000681 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000682 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
683
684 // Create Decl objects for each parameter, adding them to the
685 // FunctionDecl.
686 llvm::SmallVector<ParmVarDecl*, 16> Params;
687
688 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
689 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000690 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000691 // We let through "const void" here because Sema::GetTypeForDeclarator
692 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000693 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
694 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000695 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
696 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000697 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
698
Chris Lattnerdef026a2008-04-10 02:26:16 +0000699 // In C++, the empty parameter-type-list must be spelled "void"; a
700 // typedef of void is not permitted.
701 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000702 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000703 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
704 }
705
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000706 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000707 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
708 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
709 }
710
711 NewFD->setParams(&Params[0], Params.size());
712 }
713
Steve Naroffffce4d52008-01-09 23:34:55 +0000714 // Merge the decl with the existing one if appropriate. Since C functions
715 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000716 if (PrevDecl &&
717 (!getLangOptions().CPlusPlus ||
718 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) ) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000719 bool Redeclaration = false;
720 NewFD = MergeFunctionDecl(NewFD, PrevDecl, Redeclaration);
Reid Spencer5f016e22007-07-11 17:01:13 +0000721 if (NewFD == 0) return 0;
Douglas Gregorf0097952008-04-21 02:02:58 +0000722 if (Redeclaration) {
Eli Friedman27424962008-05-27 05:07:37 +0000723 NewFD->setPreviousDeclaration(cast<FunctionDecl>(PrevDecl));
Douglas Gregorf0097952008-04-21 02:02:58 +0000724 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 }
726 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000727
728 // In C++, check default arguments now that we have merged decls.
729 if (getLangOptions().CPlusPlus)
730 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000731 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000732 // Check that there are no default arguments (C++ only).
733 if (getLangOptions().CPlusPlus)
734 CheckExtraCXXDefaultArguments(D);
735
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000736 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000737 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
738 D.getIdentifier()->getName());
739 InvalidDecl = true;
740 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000741
742 VarDecl *NewVD;
743 VarDecl::StorageClass SC;
744 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000745 default: assert(0 && "Unknown storage class!");
746 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
747 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
748 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
749 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
750 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
751 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000752 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000753 if (D.getContext() == Declarator::MemberContext) {
754 assert(SC == VarDecl::Static && "Invalid storage class for member!");
755 // This is a static data member for a C++ class.
756 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
757 D.getIdentifierLoc(), II,
758 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000759 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +0000760 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000761 if (S->getFnParent() == 0) {
762 // C99 6.9p2: The storage-class specifiers auto and register shall not
763 // appear in the declaration specifiers in an external declaration.
764 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
765 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
766 R.getAsString());
767 InvalidDecl = true;
768 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000769 }
Daniel Dunbar6f0200e2008-09-08 20:05:47 +0000770 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
771 II, R, SC, LastDeclarator);
772 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +0000773 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000774 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000775 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000776
Daniel Dunbara735ad82008-08-06 00:03:29 +0000777 // Handle GNU asm-label extension (encoded as an attribute).
778 if (Expr *E = (Expr*) D.getAsmLabel()) {
779 // The parser guarantees this is a string.
780 StringLiteral *SE = cast<StringLiteral>(E);
781 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
782 SE->getByteLength())));
783 }
784
Nate Begemanc8e89a82008-03-14 18:07:10 +0000785 // Emit an error if an address space was applied to decl with local storage.
786 // This includes arrays of objects with address space qualifiers, but not
787 // automatic variables that point to other address spaces.
788 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000789 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
790 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
791 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000792 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000793 // Merge the decl with the existing one if appropriate. If the decl is
794 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000795 if (PrevDecl && IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 NewVD = MergeVarDecl(NewVD, PrevDecl);
797 if (NewVD == 0) return 0;
798 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000799 New = NewVD;
800 }
801
802 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000803 if (II)
804 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000805 // If any semantic error occurred, mark the decl as invalid.
806 if (D.getInvalidType() || InvalidDecl)
807 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000808
809 return New;
810}
811
Eli Friedmanc594b322008-05-20 13:48:25 +0000812bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
813 switch (Init->getStmtClass()) {
814 default:
815 Diag(Init->getExprLoc(),
816 diag::err_init_element_not_constant, Init->getSourceRange());
817 return true;
818 case Expr::ParenExprClass: {
819 const ParenExpr* PE = cast<ParenExpr>(Init);
820 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
821 }
822 case Expr::CompoundLiteralExprClass:
823 return cast<CompoundLiteralExpr>(Init)->isFileScope();
824 case Expr::DeclRefExprClass: {
825 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000826 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
827 if (VD->hasGlobalStorage())
828 return false;
829 Diag(Init->getExprLoc(),
830 diag::err_init_element_not_constant, Init->getSourceRange());
831 return true;
832 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000833 if (isa<FunctionDecl>(D))
834 return false;
835 Diag(Init->getExprLoc(),
836 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000837 return true;
838 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000839 case Expr::MemberExprClass: {
840 const MemberExpr *M = cast<MemberExpr>(Init);
841 if (M->isArrow())
842 return CheckAddressConstantExpression(M->getBase());
843 return CheckAddressConstantExpressionLValue(M->getBase());
844 }
845 case Expr::ArraySubscriptExprClass: {
846 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
847 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
848 return CheckAddressConstantExpression(ASE->getBase()) ||
849 CheckArithmeticConstantExpression(ASE->getIdx());
850 }
851 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +0000852 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +0000853 return false;
854 case Expr::UnaryOperatorClass: {
855 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
856
857 // C99 6.6p9
858 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000859 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000860
861 Diag(Init->getExprLoc(),
862 diag::err_init_element_not_constant, Init->getSourceRange());
863 return true;
864 }
865 }
866}
867
868bool Sema::CheckAddressConstantExpression(const Expr* Init) {
869 switch (Init->getStmtClass()) {
870 default:
871 Diag(Init->getExprLoc(),
872 diag::err_init_element_not_constant, Init->getSourceRange());
873 return true;
874 case Expr::ParenExprClass: {
875 const ParenExpr* PE = cast<ParenExpr>(Init);
876 return CheckAddressConstantExpression(PE->getSubExpr());
877 }
878 case Expr::StringLiteralClass:
879 case Expr::ObjCStringLiteralClass:
880 return false;
881 case Expr::CallExprClass: {
882 const CallExpr *CE = cast<CallExpr>(Init);
883 if (CE->isBuiltinConstantExpr())
884 return false;
885 Diag(Init->getExprLoc(),
886 diag::err_init_element_not_constant, Init->getSourceRange());
887 return true;
888 }
889 case Expr::UnaryOperatorClass: {
890 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
891
892 // C99 6.6p9
893 if (Exp->getOpcode() == UnaryOperator::AddrOf)
894 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
895
896 if (Exp->getOpcode() == UnaryOperator::Extension)
897 return CheckAddressConstantExpression(Exp->getSubExpr());
898
899 Diag(Init->getExprLoc(),
900 diag::err_init_element_not_constant, Init->getSourceRange());
901 return true;
902 }
903 case Expr::BinaryOperatorClass: {
904 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
905 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
906
907 Expr *PExp = Exp->getLHS();
908 Expr *IExp = Exp->getRHS();
909 if (IExp->getType()->isPointerType())
910 std::swap(PExp, IExp);
911
912 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
913 return CheckAddressConstantExpression(PExp) ||
914 CheckArithmeticConstantExpression(IExp);
915 }
Eli Friedmanc3f07642008-08-25 20:46:57 +0000916 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000917 case Expr::ExplicitCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +0000918 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +0000919 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
920 // Check for implicit promotion
921 if (SubExpr->getType()->isFunctionType() ||
922 SubExpr->getType()->isArrayType())
923 return CheckAddressConstantExpressionLValue(SubExpr);
924 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000925
926 // Check for pointer->pointer cast
927 if (SubExpr->getType()->isPointerType())
928 return CheckAddressConstantExpression(SubExpr);
929
Eli Friedmanc3f07642008-08-25 20:46:57 +0000930 if (SubExpr->getType()->isIntegralType()) {
931 // Check for the special-case of a pointer->int->pointer cast;
932 // this isn't standard, but some code requires it. See
933 // PR2720 for an example.
934 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
935 if (SubCast->getSubExpr()->getType()->isPointerType()) {
936 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
937 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
938 if (IntWidth >= PointerWidth) {
939 return CheckAddressConstantExpression(SubCast->getSubExpr());
940 }
941 }
942 }
943 }
944 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +0000945 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +0000946 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000947
948 Diag(Init->getExprLoc(),
949 diag::err_init_element_not_constant, Init->getSourceRange());
950 return true;
951 }
952 case Expr::ConditionalOperatorClass: {
953 // FIXME: Should we pedwarn here?
954 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
955 if (!Exp->getCond()->getType()->isArithmeticType()) {
956 Diag(Init->getExprLoc(),
957 diag::err_init_element_not_constant, Init->getSourceRange());
958 return true;
959 }
960 if (CheckArithmeticConstantExpression(Exp->getCond()))
961 return true;
962 if (Exp->getLHS() &&
963 CheckAddressConstantExpression(Exp->getLHS()))
964 return true;
965 return CheckAddressConstantExpression(Exp->getRHS());
966 }
967 case Expr::AddrLabelExprClass:
968 return false;
969 }
970}
971
Eli Friedman4caf0552008-06-09 05:05:07 +0000972static const Expr* FindExpressionBaseAddress(const Expr* E);
973
974static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
975 switch (E->getStmtClass()) {
976 default:
977 return E;
978 case Expr::ParenExprClass: {
979 const ParenExpr* PE = cast<ParenExpr>(E);
980 return FindExpressionBaseAddressLValue(PE->getSubExpr());
981 }
982 case Expr::MemberExprClass: {
983 const MemberExpr *M = cast<MemberExpr>(E);
984 if (M->isArrow())
985 return FindExpressionBaseAddress(M->getBase());
986 return FindExpressionBaseAddressLValue(M->getBase());
987 }
988 case Expr::ArraySubscriptExprClass: {
989 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
990 return FindExpressionBaseAddress(ASE->getBase());
991 }
992 case Expr::UnaryOperatorClass: {
993 const UnaryOperator *Exp = cast<UnaryOperator>(E);
994
995 if (Exp->getOpcode() == UnaryOperator::Deref)
996 return FindExpressionBaseAddress(Exp->getSubExpr());
997
998 return E;
999 }
1000 }
1001}
1002
1003static const Expr* FindExpressionBaseAddress(const Expr* E) {
1004 switch (E->getStmtClass()) {
1005 default:
1006 return E;
1007 case Expr::ParenExprClass: {
1008 const ParenExpr* PE = cast<ParenExpr>(E);
1009 return FindExpressionBaseAddress(PE->getSubExpr());
1010 }
1011 case Expr::UnaryOperatorClass: {
1012 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1013
1014 // C99 6.6p9
1015 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1016 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1017
1018 if (Exp->getOpcode() == UnaryOperator::Extension)
1019 return FindExpressionBaseAddress(Exp->getSubExpr());
1020
1021 return E;
1022 }
1023 case Expr::BinaryOperatorClass: {
1024 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1025
1026 Expr *PExp = Exp->getLHS();
1027 Expr *IExp = Exp->getRHS();
1028 if (IExp->getType()->isPointerType())
1029 std::swap(PExp, IExp);
1030
1031 return FindExpressionBaseAddress(PExp);
1032 }
1033 case Expr::ImplicitCastExprClass: {
1034 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1035
1036 // Check for implicit promotion
1037 if (SubExpr->getType()->isFunctionType() ||
1038 SubExpr->getType()->isArrayType())
1039 return FindExpressionBaseAddressLValue(SubExpr);
1040
1041 // Check for pointer->pointer cast
1042 if (SubExpr->getType()->isPointerType())
1043 return FindExpressionBaseAddress(SubExpr);
1044
1045 // We assume that we have an arithmetic expression here;
1046 // if we don't, we'll figure it out later
1047 return 0;
1048 }
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001049 case Expr::ExplicitCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001050 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1051
1052 // Check for pointer->pointer cast
1053 if (SubExpr->getType()->isPointerType())
1054 return FindExpressionBaseAddress(SubExpr);
1055
1056 // We assume that we have an arithmetic expression here;
1057 // if we don't, we'll figure it out later
1058 return 0;
1059 }
1060 }
1061}
1062
Eli Friedmanc594b322008-05-20 13:48:25 +00001063bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1064 switch (Init->getStmtClass()) {
1065 default:
1066 Diag(Init->getExprLoc(),
1067 diag::err_init_element_not_constant, Init->getSourceRange());
1068 return true;
1069 case Expr::ParenExprClass: {
1070 const ParenExpr* PE = cast<ParenExpr>(Init);
1071 return CheckArithmeticConstantExpression(PE->getSubExpr());
1072 }
1073 case Expr::FloatingLiteralClass:
1074 case Expr::IntegerLiteralClass:
1075 case Expr::CharacterLiteralClass:
1076 case Expr::ImaginaryLiteralClass:
1077 case Expr::TypesCompatibleExprClass:
1078 case Expr::CXXBoolLiteralExprClass:
1079 return false;
1080 case Expr::CallExprClass: {
1081 const CallExpr *CE = cast<CallExpr>(Init);
1082 if (CE->isBuiltinConstantExpr())
1083 return false;
1084 Diag(Init->getExprLoc(),
1085 diag::err_init_element_not_constant, Init->getSourceRange());
1086 return true;
1087 }
1088 case Expr::DeclRefExprClass: {
1089 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1090 if (isa<EnumConstantDecl>(D))
1091 return false;
1092 Diag(Init->getExprLoc(),
1093 diag::err_init_element_not_constant, Init->getSourceRange());
1094 return true;
1095 }
1096 case Expr::CompoundLiteralExprClass:
1097 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1098 // but vectors are allowed to be magic.
1099 if (Init->getType()->isVectorType())
1100 return false;
1101 Diag(Init->getExprLoc(),
1102 diag::err_init_element_not_constant, Init->getSourceRange());
1103 return true;
1104 case Expr::UnaryOperatorClass: {
1105 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1106
1107 switch (Exp->getOpcode()) {
1108 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1109 // See C99 6.6p3.
1110 default:
1111 Diag(Init->getExprLoc(),
1112 diag::err_init_element_not_constant, Init->getSourceRange());
1113 return true;
1114 case UnaryOperator::SizeOf:
1115 case UnaryOperator::AlignOf:
1116 case UnaryOperator::OffsetOf:
1117 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1118 // See C99 6.5.3.4p2 and 6.6p3.
1119 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1120 return false;
1121 Diag(Init->getExprLoc(),
1122 diag::err_init_element_not_constant, Init->getSourceRange());
1123 return true;
1124 case UnaryOperator::Extension:
1125 case UnaryOperator::LNot:
1126 case UnaryOperator::Plus:
1127 case UnaryOperator::Minus:
1128 case UnaryOperator::Not:
1129 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1130 }
1131 }
1132 case Expr::SizeOfAlignOfTypeExprClass: {
1133 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1134 // Special check for void types, which are allowed as an extension
1135 if (Exp->getArgumentType()->isVoidType())
1136 return false;
1137 // alignof always evaluates to a constant.
1138 // FIXME: is sizeof(int[3.0]) a constant expression?
1139 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1140 Diag(Init->getExprLoc(),
1141 diag::err_init_element_not_constant, Init->getSourceRange());
1142 return true;
1143 }
1144 return false;
1145 }
1146 case Expr::BinaryOperatorClass: {
1147 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1148
1149 if (Exp->getLHS()->getType()->isArithmeticType() &&
1150 Exp->getRHS()->getType()->isArithmeticType()) {
1151 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1152 CheckArithmeticConstantExpression(Exp->getRHS());
1153 }
1154
Eli Friedman4caf0552008-06-09 05:05:07 +00001155 if (Exp->getLHS()->getType()->isPointerType() &&
1156 Exp->getRHS()->getType()->isPointerType()) {
1157 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1158 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1159
1160 // Only allow a null (constant integer) base; we could
1161 // allow some additional cases if necessary, but this
1162 // is sufficient to cover offsetof-like constructs.
1163 if (!LHSBase && !RHSBase) {
1164 return CheckAddressConstantExpression(Exp->getLHS()) ||
1165 CheckAddressConstantExpression(Exp->getRHS());
1166 }
1167 }
1168
Eli Friedmanc594b322008-05-20 13:48:25 +00001169 Diag(Init->getExprLoc(),
1170 diag::err_init_element_not_constant, Init->getSourceRange());
1171 return true;
1172 }
1173 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001174 case Expr::ExplicitCastExprClass: {
1175 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001176 if (SubExpr->getType()->isArithmeticType())
1177 return CheckArithmeticConstantExpression(SubExpr);
1178
Eli Friedmanb529d832008-09-02 09:37:00 +00001179 if (SubExpr->getType()->isPointerType()) {
1180 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1181 // If the pointer has a null base, this is an offsetof-like construct
1182 if (!Base)
1183 return CheckAddressConstantExpression(SubExpr);
1184 }
1185
Eli Friedman6d4abe12008-09-01 22:08:17 +00001186 Diag(Init->getExprLoc(),
1187 diag::err_init_element_not_constant, Init->getSourceRange());
1188 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001189 }
1190 case Expr::ConditionalOperatorClass: {
1191 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1192 if (CheckArithmeticConstantExpression(Exp->getCond()))
1193 return true;
1194 if (Exp->getLHS() &&
1195 CheckArithmeticConstantExpression(Exp->getLHS()))
1196 return true;
1197 return CheckArithmeticConstantExpression(Exp->getRHS());
1198 }
1199 }
1200}
1201
1202bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001203 Init = Init->IgnoreParens();
1204
Eli Friedmanc594b322008-05-20 13:48:25 +00001205 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1206 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1207 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1208
Nuno Lopes9a979c32008-07-07 16:46:50 +00001209 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1210 return CheckForConstantInitializer(e->getInitializer(), DclT);
1211
Eli Friedmanc594b322008-05-20 13:48:25 +00001212 if (Init->getType()->isReferenceType()) {
1213 // FIXME: Work out how the heck reference types work
1214 return false;
1215#if 0
1216 // A reference is constant if the address of the expression
1217 // is constant
1218 // We look through initlists here to simplify
1219 // CheckAddressConstantExpressionLValue.
1220 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1221 assert(Exp->getNumInits() > 0 &&
1222 "Refernce initializer cannot be empty");
1223 Init = Exp->getInit(0);
1224 }
1225 return CheckAddressConstantExpressionLValue(Init);
1226#endif
1227 }
1228
1229 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1230 unsigned numInits = Exp->getNumInits();
1231 for (unsigned i = 0; i < numInits; i++) {
1232 // FIXME: Need to get the type of the declaration for C++,
1233 // because it could be a reference?
1234 if (CheckForConstantInitializer(Exp->getInit(i),
1235 Exp->getInit(i)->getType()))
1236 return true;
1237 }
1238 return false;
1239 }
1240
1241 if (Init->isNullPointerConstant(Context))
1242 return false;
1243 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001244 QualType InitTy = Context.getCanonicalType(Init->getType())
1245 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001246 if (InitTy == Context.BoolTy) {
1247 // Special handling for pointers implicitly cast to bool;
1248 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1249 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1250 Expr* SubE = ICE->getSubExpr();
1251 if (SubE->getType()->isPointerType() ||
1252 SubE->getType()->isArrayType() ||
1253 SubE->getType()->isFunctionType()) {
1254 return CheckAddressConstantExpression(Init);
1255 }
1256 }
1257 } else if (InitTy->isIntegralType()) {
1258 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001259 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001260 SubE = CE->getSubExpr();
1261 // Special check for pointer cast to int; we allow as an extension
1262 // an address constant cast to an integer if the integer
1263 // is of an appropriate width (this sort of code is apparently used
1264 // in some places).
1265 // FIXME: Add pedwarn?
1266 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1267 if (SubE && (SubE->getType()->isPointerType() ||
1268 SubE->getType()->isArrayType() ||
1269 SubE->getType()->isFunctionType())) {
1270 unsigned IntWidth = Context.getTypeSize(Init->getType());
1271 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1272 if (IntWidth >= PointerWidth)
1273 return CheckAddressConstantExpression(Init);
1274 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001275 }
1276
1277 return CheckArithmeticConstantExpression(Init);
1278 }
1279
1280 if (Init->getType()->isPointerType())
1281 return CheckAddressConstantExpression(Init);
1282
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001283 // An array type at the top level that isn't an init-list must
1284 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001285 if (Init->getType()->isArrayType())
1286 return false;
1287
Nuno Lopes73419bf2008-09-01 18:42:41 +00001288 if (Init->getType()->isFunctionType())
1289 return false;
1290
Eli Friedmanc594b322008-05-20 13:48:25 +00001291 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1292 Init->getSourceRange());
1293 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001294}
1295
Steve Naroffbb204692007-09-12 14:07:44 +00001296void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001297 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001298 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001299 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001300
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001301 // If there is no declaration, there was an error parsing it. Just ignore
1302 // the initializer.
1303 if (RealDecl == 0) {
1304 delete Init;
1305 return;
1306 }
Steve Naroffbb204692007-09-12 14:07:44 +00001307
Steve Naroff410e3e22007-09-12 20:13:48 +00001308 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1309 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001310 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1311 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001312 RealDecl->setInvalidDecl();
1313 return;
1314 }
Steve Naroffbb204692007-09-12 14:07:44 +00001315 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001316 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001317 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001318 if (VDecl->isBlockVarDecl()) {
1319 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001320 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001321 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001322 VDecl->setInvalidDecl();
1323 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001324 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001325 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001326
1327 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1328 if (!getLangOptions().CPlusPlus) {
1329 if (SC == VarDecl::Static) // C99 6.7.8p4.
1330 CheckForConstantInitializer(Init, DclT);
1331 }
Steve Naroffbb204692007-09-12 14:07:44 +00001332 }
Steve Naroff248a7532008-04-15 22:42:06 +00001333 } else if (VDecl->isFileVarDecl()) {
1334 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001335 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001336 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001337 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001338 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001339
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001340 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1341 if (!getLangOptions().CPlusPlus) {
1342 // C99 6.7.8p4. All file scoped initializers need to be constant.
1343 CheckForConstantInitializer(Init, DclT);
1344 }
Steve Naroffbb204692007-09-12 14:07:44 +00001345 }
1346 // If the type changed, it means we had an incomplete type that was
1347 // completed by the initializer. For example:
1348 // int ary[] = { 1, 3, 5 };
1349 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001350 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001351 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001352 Init->setType(DclT);
1353 }
Steve Naroffbb204692007-09-12 14:07:44 +00001354
1355 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001356 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001357 return;
1358}
1359
Reid Spencer5f016e22007-07-11 17:01:13 +00001360/// The declarators are chained together backwards, reverse the list.
1361Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1362 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001363 Decl *GroupDecl = static_cast<Decl*>(group);
1364 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001365 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001366
1367 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1368 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001369 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001370 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001371 else { // reverse the list.
1372 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001373 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001374 Group->setNextDeclarator(NewGroup);
1375 NewGroup = Group;
1376 Group = Next;
1377 }
1378 }
1379 // Perform semantic analysis that depends on having fully processed both
1380 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001381 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001382 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1383 if (!IDecl)
1384 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001385 QualType T = IDecl->getType();
1386
1387 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1388 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001389 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1390 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001391 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001392 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1393 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001394 }
1395 }
1396 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1397 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001398 if (IDecl->isBlockVarDecl() &&
1399 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001400 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001401 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1402 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001403 IDecl->setInvalidDecl();
1404 }
1405 }
1406 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1407 // object that has file scope without an initializer, and without a
1408 // storage-class specifier or with the storage-class specifier "static",
1409 // constitutes a tentative definition. Note: A tentative definition with
1410 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001411 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001412 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001413 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1414 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001415 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001416 // C99 6.9.2p3: If the declaration of an identifier for an object is
1417 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1418 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001419 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1420 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001421 IDecl->setInvalidDecl();
1422 }
1423 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001424 if (IDecl->isFileVarDecl())
1425 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001426 }
1427 return NewGroup;
1428}
Steve Naroffe1223f72007-08-28 03:03:08 +00001429
Chris Lattner04421082008-04-08 04:40:51 +00001430/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1431/// to introduce parameters into function prototype scope.
1432Sema::DeclTy *
1433Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001434 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001435
1436 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001437 VarDecl::StorageClass StorageClass = VarDecl::None;
1438 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1439 StorageClass = VarDecl::Register;
1440 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001441 Diag(DS.getStorageClassSpecLoc(),
1442 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001443 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001444 }
1445 if (DS.isThreadSpecified()) {
1446 Diag(DS.getThreadSpecLoc(),
1447 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001448 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001449 }
1450
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001451 // Check that there are no default arguments inside the type of this
1452 // parameter (C++ only).
1453 if (getLangOptions().CPlusPlus)
1454 CheckExtraCXXDefaultArguments(D);
1455
Chris Lattner04421082008-04-08 04:40:51 +00001456 // In this context, we *do not* check D.getInvalidType(). If the declarator
1457 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1458 // though it will not reflect the user specified type.
1459 QualType parmDeclType = GetTypeForDeclarator(D, S);
1460
1461 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1462
Reid Spencer5f016e22007-07-11 17:01:13 +00001463 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1464 // Can this happen for params? We already checked that they don't conflict
1465 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001466 IdentifierInfo *II = D.getIdentifier();
1467 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1468 if (S->isDeclScope(PrevDecl)) {
1469 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1470 dyn_cast<NamedDecl>(PrevDecl)->getName());
1471
1472 // Recover by removing the name
1473 II = 0;
1474 D.SetIdentifier(0, D.getIdentifierLoc());
1475 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001476 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001477
1478 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1479 // Doing the promotion here has a win and a loss. The win is the type for
1480 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1481 // code generator). The loss is the orginal type isn't preserved. For example:
1482 //
1483 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1484 // int blockvardecl[5];
1485 // sizeof(parmvardecl); // size == 4
1486 // sizeof(blockvardecl); // size == 20
1487 // }
1488 //
1489 // For expressions, all implicit conversions are captured using the
1490 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1491 //
1492 // FIXME: If a source translation tool needs to see the original type, then
1493 // we need to consider storing both types (in ParmVarDecl)...
1494 //
Chris Lattnere6327742008-04-02 05:18:44 +00001495 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001496 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001497 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001498 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001499 parmDeclType = Context.getPointerType(parmDeclType);
1500
Chris Lattner04421082008-04-08 04:40:51 +00001501 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1502 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001503 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001504 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001505
Chris Lattner04421082008-04-08 04:40:51 +00001506 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001507 New->setInvalidDecl();
1508
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001509 if (II)
1510 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001511
Chris Lattner3ff30c82008-06-29 00:02:00 +00001512 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001513 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001514
Reid Spencer5f016e22007-07-11 17:01:13 +00001515}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001516
Chris Lattnerb652cea2007-10-09 17:14:05 +00001517Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001518 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001519 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1520 "Not a function declarator!");
1521 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001522
Reid Spencer5f016e22007-07-11 17:01:13 +00001523 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1524 // for a K&R function.
1525 if (!FTI.hasPrototype) {
1526 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001527 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001528 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1529 FTI.ArgInfo[i].Ident->getName());
1530 // Implicitly declare the argument as type 'int' for lack of a better
1531 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001532 DeclSpec DS;
1533 const char* PrevSpec; // unused
1534 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1535 PrevSpec);
1536 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1537 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1538 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001539 }
1540 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001541 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001542 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001543 }
1544
1545 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001546
1547 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001548 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001549 GlobalScope);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001550 if (PrevDcl && IdResolver.isDeclInScope(PrevDcl, CurContext)) {
1551 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1552 const FunctionDecl *Definition;
1553 if (FD->getBody(Definition)) {
1554 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1555 D.getIdentifier()->getName());
1556 Diag(Definition->getLocation(), diag::err_previous_definition);
1557 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001558 }
1559 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001560
1561 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001562 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001563}
1564
1565Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1566 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001567 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001568 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001569
1570 // Check the validity of our function parameters
1571 CheckParmsForFunctionDef(FD);
1572
1573 // Introduce our parameters into the function scope
1574 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1575 ParmVarDecl *Param = FD->getParamDecl(p);
1576 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001577 if (Param->getIdentifier())
1578 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001579 }
Chris Lattner04421082008-04-08 04:40:51 +00001580
Reid Spencer5f016e22007-07-11 17:01:13 +00001581 return FD;
1582}
1583
Steve Naroffd6d054d2007-11-11 23:20:51 +00001584Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1585 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001586 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001587 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001588 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001589 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001590 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001591 } else
1592 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001593 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001594 // Verify and clean out per-function state.
1595
1596 // Check goto/label use.
1597 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1598 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1599 // Verify that we have no forward references left. If so, there was a goto
1600 // or address of a label taken, but no definition of it. Label fwd
1601 // definitions are indicated with a null substmt.
1602 if (I->second->getSubStmt() == 0) {
1603 LabelStmt *L = I->second;
1604 // Emit error.
1605 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1606
1607 // At this point, we have gotos that use the bogus label. Stitch it into
1608 // the function body so that they aren't leaked and that the AST is well
1609 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001610 if (Body) {
1611 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1612 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1613 } else {
1614 // The whole function wasn't parsed correctly, just delete this.
1615 delete L;
1616 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001617 }
1618 }
1619 LabelMap.clear();
1620
Steve Naroffd6d054d2007-11-11 23:20:51 +00001621 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001622}
1623
Reid Spencer5f016e22007-07-11 17:01:13 +00001624/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1625/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001626ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1627 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001628 // Extension in C99. Legal in C90, but warn about it.
1629 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001630 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001631 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001632 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1633
1634 // FIXME: handle stuff like:
1635 // void foo() { extern float X(); }
1636 // void bar() { X(); } <-- implicit decl for X in another scope.
1637
1638 // Set a Declarator for the implicit definition: int foo();
1639 const char *Dummy;
1640 DeclSpec DS;
1641 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1642 Error = Error; // Silence warning.
1643 assert(!Error && "Error setting up implicit decl!");
1644 Declarator D(DS, Declarator::BlockContext);
1645 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1646 D.SetIdentifier(&II, Loc);
1647
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001648 // Insert this function into translation-unit scope.
1649
1650 DeclContext *PrevDC = CurContext;
1651 CurContext = Context.getTranslationUnitDecl();
1652
Steve Naroffe2ef8152008-04-04 14:32:09 +00001653 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00001654 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001655 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001656
1657 CurContext = PrevDC;
1658
Steve Naroffe2ef8152008-04-04 14:32:09 +00001659 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001660}
1661
1662
Chris Lattner41af0932007-11-14 06:34:38 +00001663TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001664 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001665 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001666 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001667
1668 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001669 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1670 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001671 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001672 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001673 if (D.getInvalidType())
1674 NewTD->setInvalidDecl();
1675 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001676}
1677
Steve Naroff08d92e42007-09-15 18:49:24 +00001678/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001679/// former case, Name will be non-null. In the later case, Name will be null.
1680/// TagType indicates what kind of tag this is. TK indicates whether this is a
1681/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001682Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001683 SourceLocation KWLoc, IdentifierInfo *Name,
1684 SourceLocation NameLoc, AttributeList *Attr) {
1685 // If this is a use of an existing tag, it must have a name.
1686 assert((Name != 0 || TK == TK_Definition) &&
1687 "Nameless record must be a definition!");
1688
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001689 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001690 switch (TagType) {
1691 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001692 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1693 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1694 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1695 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001696 }
1697
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001698 // Two code paths: a new one for structs/unions/classes where we create
1699 // separate decls for forward declarations, and an old (eventually to
1700 // be removed) code path for enums.
1701 if (Kind != TagDecl::TK_enum)
1702 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
1703
Reid Spencer5f016e22007-07-11 17:01:13 +00001704 // If this is a named struct, check to see if there was a previous forward
1705 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001706 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenek7e8cc572008-09-02 21:26:19 +00001707 ScopedDecl *PrevDecl =
1708 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1709
1710 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001711 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1712 "unexpected Decl type");
1713 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001714 // If this is a use of a previous tag, or if the tag is already declared
1715 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001716 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001717 if (TK == TK_Reference ||
1718 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001719 // Make sure that this wasn't declared as an enum and now used as a
1720 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001721 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001722 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1723 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00001724 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001725 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00001726 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001727 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00001728 // If this is a use or a forward declaration, we're good.
1729 if (TK != TK_Definition)
1730 return PrevDecl;
1731
1732 // Diagnose attempts to redefine a tag.
1733 if (PrevTagDecl->isDefinition()) {
1734 Diag(NameLoc, diag::err_redefinition, Name->getName());
1735 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1736 // If this is a redefinition, recover by making this struct be
1737 // anonymous, which will make any later references get the previous
1738 // definition.
1739 Name = 0;
1740 } else {
1741 // Okay, this is definition of a previously declared or referenced
1742 // tag. Move the location of the decl to be the definition site.
1743 PrevDecl->setLocation(NameLoc);
1744 return PrevDecl;
1745 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001746 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001747 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001748 // If we get here, this is a definition of a new struct type in a nested
1749 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1750 // type.
1751 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001752 // PrevDecl is a namespace.
1753 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00001754 // The tag name clashes with a namespace name, issue an error and
1755 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001756 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1757 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1758 Name = 0;
1759 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001760 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001761 }
1762
1763 // If there is an identifier, use the location of the identifier as the
1764 // location of the decl, otherwise use the location of the struct/union
1765 // keyword.
1766 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1767
1768 // Otherwise, if this is the first time we've seen this tag, create the decl.
1769 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001770 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001771 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1772 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001773 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001774 // If this is an undefined enum, warn.
1775 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001776 } else {
1777 // struct/union/class
1778
Reid Spencer5f016e22007-07-11 17:01:13 +00001779 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1780 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001781 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00001782 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenekdf042e62008-09-05 01:34:33 +00001783 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001784 else
Ted Kremenekdf042e62008-09-05 01:34:33 +00001785 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001786 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001787
1788 // If this has an identifier, add it to the scope stack.
1789 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001790 // The scope passed in may not be a decl scope. Zip up the scope tree until
1791 // we find one that is.
1792 while ((S->getFlags() & Scope::DeclScope) == 0)
1793 S = S->getParent();
1794
1795 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001796 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001797 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001798
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001799 if (Attr)
1800 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001801 return New;
1802}
1803
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001804/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
1805/// the logic for enums, we create separate decls for forward declarations.
1806/// This is called by ActOnTag, but eventually will replace its logic.
1807Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
1808 SourceLocation KWLoc, IdentifierInfo *Name,
1809 SourceLocation NameLoc, AttributeList *Attr) {
1810
1811 // If this is a named struct, check to see if there was a previous forward
1812 // declaration or definition.
1813 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1814 ScopedDecl *PrevDecl =
1815 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1816
1817 if (PrevDecl) {
1818 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1819 "unexpected Decl type");
1820
1821 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1822 // If this is a use of a previous tag, or if the tag is already declared
1823 // in the same scope (so that the definition/declaration completes or
1824 // rementions the tag), reuse the decl.
1825 if (TK == TK_Reference ||
1826 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1827 // Make sure that this wasn't declared as an enum and now used as a
1828 // struct or something similar.
1829 if (PrevTagDecl->getTagKind() != Kind) {
1830 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1831 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1832 // Recover by making this an anonymous redefinition.
1833 Name = 0;
1834 PrevDecl = 0;
1835 } else {
1836 // If this is a use, return the original decl.
1837
1838 // FIXME: In the future, return a variant or some other clue
1839 // for the consumer of this Decl to know it doesn't own it.
1840 // For our current ASTs this shouldn't be a problem, but will
1841 // need to be changed with DeclGroups.
1842 if (TK == TK_Reference)
1843 return PrevDecl;
1844
1845 // The new decl is a definition?
1846 if (TK == TK_Definition) {
1847 // Diagnose attempts to redefine a tag.
1848 if (RecordDecl* DefRecord =
1849 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
1850 Diag(NameLoc, diag::err_redefinition, Name->getName());
1851 Diag(DefRecord->getLocation(), diag::err_previous_definition);
1852 // If this is a redefinition, recover by making this struct be
1853 // anonymous, which will make any later references get the previous
1854 // definition.
1855 Name = 0;
1856 PrevDecl = 0;
1857 }
1858 // Okay, this is definition of a previously declared or referenced
1859 // tag. We're going to create a new Decl.
1860 }
1861 }
1862 // If we get here we have (another) forward declaration. Just create
1863 // a new decl.
1864 }
1865 else {
1866 // If we get here, this is a definition of a new struct type in a nested
1867 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
1868 // new decl/type. We set PrevDecl to NULL so that the Records
1869 // have distinct types.
1870 PrevDecl = 0;
1871 }
1872 } else {
1873 // PrevDecl is a namespace.
1874 if (IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
1875 // The tag name clashes with a namespace name, issue an error and
1876 // recover by making this tag be anonymous.
1877 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1878 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1879 Name = 0;
1880 }
1881 }
1882 }
1883
1884 // If there is an identifier, use the location of the identifier as the
1885 // location of the decl, otherwise use the location of the struct/union
1886 // keyword.
1887 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1888
1889 // Otherwise, if this is the first time we've seen this tag, create the decl.
1890 TagDecl *New;
1891
1892 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1893 // struct X { int A; } D; D should chain to X.
1894 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00001895 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001896 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1897 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
1898 else
1899 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1900 dyn_cast_or_null<RecordDecl>(PrevDecl));
1901
1902 // If this has an identifier, add it to the scope stack.
1903 if ((TK == TK_Definition || !PrevDecl) && Name) {
1904 // The scope passed in may not be a decl scope. Zip up the scope tree until
1905 // we find one that is.
1906 while ((S->getFlags() & Scope::DeclScope) == 0)
1907 S = S->getParent();
1908
1909 // Add it to the decl chain.
1910 PushOnScopeChains(New, S);
1911 }
1912
1913 if (Attr)
1914 ProcessDeclAttributeList(New, Attr);
1915
1916 return New;
1917}
1918
1919
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001920/// Collect the instance variables declared in an Objective-C object. Used in
1921/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00001922static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001923 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001924 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00001925 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1926
1927 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00001928 for (ObjCInterfaceDecl::ivar_iterator
1929 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1930
Ted Kremenek01e67792008-08-20 03:26:33 +00001931 ObjCIvarDecl* ID = *I;
1932 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1933 ID->getIdentifier(),
1934 ID->getType(),
1935 ID->getBitWidth()));
1936 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001937}
1938
1939/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1940/// instance variables of ClassName into Decls.
1941void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1942 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001943 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001944 // Check that ClassName is a valid class
1945 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1946 if (!Class) {
1947 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1948 return;
1949 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001950 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00001951 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001952}
1953
Eli Friedman1b76ada2008-06-03 21:01:11 +00001954QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1955 // This method tries to turn a variable array into a constant
1956 // array even when the size isn't an ICE. This is necessary
1957 // for compatibility with code that depends on gcc's buggy
1958 // constant expression folding, like struct {char x[(int)(char*)2];}
1959 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00001960 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00001961 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00001962 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1963 llvm::APSInt &Res = Result.getInt();
1964 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1965 return Context.getConstantArrayType(VLATy->getElementType(),
1966 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00001967 }
1968 }
1969 return QualType();
1970}
1971
Steve Naroff08d92e42007-09-15 18:49:24 +00001972/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00001973/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00001974Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00001975 SourceLocation DeclStart,
1976 Declarator &D, ExprTy *BitfieldWidth) {
1977 IdentifierInfo *II = D.getIdentifier();
1978 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 SourceLocation Loc = DeclStart;
1980 if (II) Loc = D.getIdentifierLoc();
1981
1982 // FIXME: Unnamed fields can be handled in various different ways, for
1983 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00001984
Reid Spencer5f016e22007-07-11 17:01:13 +00001985 if (BitWidth) {
1986 // TODO: Validate.
1987 //printf("WARNING: BITFIELDS IGNORED!\n");
1988
1989 // 6.7.2.1p3
1990 // 6.7.2.1p4
1991
1992 } else {
1993 // Not a bitfield.
1994
1995 // validate II.
1996
1997 }
1998
1999 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002000 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2001 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002002
Reid Spencer5f016e22007-07-11 17:01:13 +00002003 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2004 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002005 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002006 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2007 if (!FixedTy.isNull()) {
2008 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2009 T = FixedTy;
2010 } else {
2011 // FIXME: This diagnostic needs work
2012 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2013 InvalidDecl = true;
2014 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002017 FieldDecl *NewFD;
2018
2019 if (getLangOptions().CPlusPlus) {
2020 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2021 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2022 Loc, II, T, BitWidth);
2023 if (II)
2024 PushOnScopeChains(NewFD, S);
2025 }
2026 else
2027 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002028
Chris Lattner3ff30c82008-06-29 00:02:00 +00002029 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002030
Steve Naroff5912a352007-08-28 20:14:24 +00002031 if (D.getInvalidType() || InvalidDecl)
2032 NewFD->setInvalidDecl();
2033 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002034}
2035
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002036/// TranslateIvarVisibility - Translate visibility from a token ID to an
2037/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002038static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002039TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002040 switch (ivarVisibility) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002041 case tok::objc_private: return ObjCIvarDecl::Private;
2042 case tok::objc_public: return ObjCIvarDecl::Public;
2043 case tok::objc_protected: return ObjCIvarDecl::Protected;
2044 case tok::objc_package: return ObjCIvarDecl::Package;
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002045 default: assert(false && "Unknown visitibility kind");
Steve Narofff13271f2007-09-14 23:09:53 +00002046 }
2047}
2048
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002049/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2050/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002051Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002052 SourceLocation DeclStart,
2053 Declarator &D, ExprTy *BitfieldWidth,
2054 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002055 IdentifierInfo *II = D.getIdentifier();
2056 Expr *BitWidth = (Expr*)BitfieldWidth;
2057 SourceLocation Loc = DeclStart;
2058 if (II) Loc = D.getIdentifierLoc();
2059
2060 // FIXME: Unnamed fields can be handled in various different ways, for
2061 // example, unnamed unions inject all members into the struct namespace!
2062
2063
2064 if (BitWidth) {
2065 // TODO: Validate.
2066 //printf("WARNING: BITFIELDS IGNORED!\n");
2067
2068 // 6.7.2.1p3
2069 // 6.7.2.1p4
2070
2071 } else {
2072 // Not a bitfield.
2073
2074 // validate II.
2075
2076 }
2077
2078 QualType T = GetTypeForDeclarator(D, S);
2079 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2080 bool InvalidDecl = false;
2081
2082 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2083 // than a variably modified type.
2084 if (T->isVariablyModifiedType()) {
2085 // FIXME: This diagnostic needs work
2086 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2087 InvalidDecl = true;
2088 }
2089
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002090 // Get the visibility (access control) for this ivar.
2091 ObjCIvarDecl::AccessControl ac =
2092 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2093 : ObjCIvarDecl::None;
2094
2095 // Construct the decl.
2096 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002097 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002098
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002099 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002100 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002101
2102 if (D.getInvalidType() || InvalidDecl)
2103 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002104
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002105 return NewID;
2106}
2107
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002108void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002109 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002110 DeclTy **Fields, unsigned NumFields,
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002111 SourceLocation LBrac, SourceLocation RBrac) {
Steve Naroff74216642007-09-14 22:20:54 +00002112 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2113 assert(EnclosingDecl && "missing record or interface decl");
2114 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2115
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002116 if (Record)
2117 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2118 // Diagnose code like:
2119 // struct S { struct S {} X; };
2120 // We discover this when we complete the outer S. Reject and ignore the
2121 // outer S.
2122 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2123 DefRecord->getKindName());
2124 Diag(RecLoc, diag::err_previous_definition);
2125 Record->setInvalidDecl();
2126 return;
2127 }
2128
Reid Spencer5f016e22007-07-11 17:01:13 +00002129 // Verify that all the fields are okay.
2130 unsigned NumNamedMembers = 0;
2131 llvm::SmallVector<FieldDecl*, 32> RecFields;
2132 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002133
Reid Spencer5f016e22007-07-11 17:01:13 +00002134 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002135
Steve Naroff74216642007-09-14 22:20:54 +00002136 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2137 assert(FD && "missing field decl");
2138
2139 // Remember all fields.
2140 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002141
2142 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002143 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002144
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002146 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002147 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002149 FD->setInvalidDecl();
2150 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002151 continue;
2152 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2154 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002155 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002156 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002157 FD->setInvalidDecl();
2158 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002159 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002160 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002161 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002162 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002163 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002164 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002165 FD->setInvalidDecl();
2166 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002167 continue;
2168 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002169 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002170 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2171 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002172 FD->setInvalidDecl();
2173 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002174 continue;
2175 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002177 if (Record)
2178 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002180 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2181 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002182 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002183 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2184 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002185 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002186 Record->setHasFlexibleArrayMember(true);
2187 } else {
2188 // If this is a struct/class and this is not the last element, reject
2189 // it. Note that GCC supports variable sized arrays in the middle of
2190 // structures.
2191 if (i != NumFields-1) {
2192 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2193 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002194 FD->setInvalidDecl();
2195 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002196 continue;
2197 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 // We support flexible arrays at the end of structs in other structs
2199 // as an extension.
2200 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2201 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002202 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002203 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002204 }
2205 }
2206 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002207 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002208 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002209 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2210 FD->getName());
2211 FD->setInvalidDecl();
2212 EnclosingDecl->setInvalidDecl();
2213 continue;
2214 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002215 // Keep track of the number of named members.
2216 if (IdentifierInfo *II = FD->getIdentifier()) {
2217 // Detect duplicate member names.
2218 if (!FieldIDs.insert(II)) {
2219 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2220 // Find the previous decl.
2221 SourceLocation PrevLoc;
2222 for (unsigned i = 0, e = RecFields.size(); ; ++i) {
2223 assert(i != e && "Didn't find previous def!");
2224 if (RecFields[i]->getIdentifier() == II) {
2225 PrevLoc = RecFields[i]->getLocation();
2226 break;
2227 }
2228 }
2229 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002230 FD->setInvalidDecl();
2231 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002232 continue;
2233 }
2234 ++NumNamedMembers;
2235 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002236 }
2237
Reid Spencer5f016e22007-07-11 17:01:13 +00002238 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002239 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002240 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002241 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2242 // Sema::ActOnFinishCXXClassDef.
2243 if (!isa<CXXRecordDecl>(Record))
2244 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002245 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002246 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2247 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2248 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2249 else if (ObjCImplementationDecl *IMPDecl =
2250 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002251 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2252 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002253 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002254 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002255 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002256}
2257
Steve Naroff08d92e42007-09-15 18:49:24 +00002258Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002259 DeclTy *lastEnumConst,
2260 SourceLocation IdLoc, IdentifierInfo *Id,
2261 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002262 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002263 EnumConstantDecl *LastEnumConst =
2264 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2265 Expr *Val = static_cast<Expr*>(val);
2266
Chris Lattner31e05722007-08-26 06:24:45 +00002267 // The scope passed in may not be a decl scope. Zip up the scope tree until
2268 // we find one that is.
2269 while ((S->getFlags() & Scope::DeclScope) == 0)
2270 S = S->getParent();
2271
Reid Spencer5f016e22007-07-11 17:01:13 +00002272 // Verify that there isn't already something declared with this name in this
2273 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002274 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002275 // When in C++, we may get a TagDecl with the same name; in this case the
2276 // enum constant will 'hide' the tag.
2277 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2278 "Received TagDecl when not in C++!");
2279 if (!isa<TagDecl>(PrevDecl) &&
2280 IdResolver.isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 if (isa<EnumConstantDecl>(PrevDecl))
2282 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2283 else
2284 Diag(IdLoc, diag::err_redefinition, Id->getName());
2285 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002286 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002287 return 0;
2288 }
2289 }
2290
2291 llvm::APSInt EnumVal(32);
2292 QualType EltTy;
2293 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002294 // Make sure to promote the operand type to int.
2295 UsualUnaryConversions(Val);
2296
Reid Spencer5f016e22007-07-11 17:01:13 +00002297 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2298 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002299 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002300 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2301 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002302 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002303 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002304 } else {
2305 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002307 }
2308
2309 if (!Val) {
2310 if (LastEnumConst) {
2311 // Assign the last value + 1.
2312 EnumVal = LastEnumConst->getInitVal();
2313 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002314
2315 // Check for overflow on increment.
2316 if (EnumVal < LastEnumConst->getInitVal())
2317 Diag(IdLoc, diag::warn_enum_value_overflow);
2318
Chris Lattnerb7416f92007-08-27 17:37:24 +00002319 EltTy = LastEnumConst->getType();
2320 } else {
2321 // First value, set to zero.
2322 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002323 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002324 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002325 }
2326
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002327 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002328 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2329 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002330 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002331
2332 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002333 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002334 return New;
2335}
2336
Steve Naroff02408c62008-08-07 14:08:16 +00002337// FIXME: For consistency with ActOnFields(), we should have the parser
2338// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002339void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002340 DeclTy **Elements, unsigned NumElements) {
2341 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002342
Steve Naroff02408c62008-08-07 14:08:16 +00002343 if (Enum && Enum->isDefinition()) {
2344 // Diagnose code like:
2345 // enum e0 {
2346 // E0 = sizeof(enum e0 { E1 })
2347 // };
2348 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2349 Enum->getName());
2350 Diag(EnumLoc, diag::err_previous_definition);
2351 Enum->setInvalidDecl();
2352 return;
2353 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002354 // TODO: If the result value doesn't fit in an int, it must be a long or long
2355 // long value. ISO C does not support this, but GCC does as an extension,
2356 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002357 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002358
Chris Lattnerac609682007-08-28 06:15:15 +00002359 // Verify that all the values are okay, compute the size of the values, and
2360 // reverse the list.
2361 unsigned NumNegativeBits = 0;
2362 unsigned NumPositiveBits = 0;
2363
2364 // Keep track of whether all elements have type int.
2365 bool AllElementsInt = true;
2366
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 EnumConstantDecl *EltList = 0;
2368 for (unsigned i = 0; i != NumElements; ++i) {
2369 EnumConstantDecl *ECD =
2370 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2371 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002372
2373 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002374 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002375 assert(InitVal.getBitWidth() >= IntWidth &&
2376 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002377 if (InitVal.getBitWidth() > IntWidth) {
2378 llvm::APSInt V(InitVal);
2379 V.trunc(IntWidth);
2380 V.extend(InitVal.getBitWidth());
2381 if (V != InitVal)
2382 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002383 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002384 }
Chris Lattnerac609682007-08-28 06:15:15 +00002385
2386 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002387 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002388 NumPositiveBits = std::max(NumPositiveBits,
2389 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002390 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002391 NumNegativeBits = std::max(NumNegativeBits,
2392 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002393
Chris Lattnerac609682007-08-28 06:15:15 +00002394 // Keep track of whether every enum element has type int (very commmon).
2395 if (AllElementsInt)
2396 AllElementsInt = ECD->getType() == Context.IntTy;
2397
Reid Spencer5f016e22007-07-11 17:01:13 +00002398 ECD->setNextDeclarator(EltList);
2399 EltList = ECD;
2400 }
2401
Chris Lattnerac609682007-08-28 06:15:15 +00002402 // Figure out the type that should be used for this enum.
2403 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2404 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002405 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002406
2407 if (NumNegativeBits) {
2408 // If there is a negative value, figure out the smallest integer type (of
2409 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002410 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002411 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002412 BestWidth = IntWidth;
2413 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002414 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002415
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002416 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002417 BestType = Context.LongTy;
2418 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002419 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002420
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002421 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002422 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2423 BestType = Context.LongLongTy;
2424 }
2425 }
2426 } else {
2427 // If there is no negative value, figure out which of uint, ulong, ulonglong
2428 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002429 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002430 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002431 BestWidth = IntWidth;
2432 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002433 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002434 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002435 } else {
2436 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002437 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002438 "How could an initializer get larger than ULL?");
2439 BestType = Context.UnsignedLongLongTy;
2440 }
2441 }
2442
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002443 // Loop over all of the enumerator constants, changing their types to match
2444 // the type of the enum if needed.
2445 for (unsigned i = 0; i != NumElements; ++i) {
2446 EnumConstantDecl *ECD =
2447 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2448 if (!ECD) continue; // Already issued a diagnostic.
2449
2450 // Standard C says the enumerators have int type, but we allow, as an
2451 // extension, the enumerators to be larger than int size. If each
2452 // enumerator value fits in an int, type it as an int, otherwise type it the
2453 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2454 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002455 if (ECD->getType() == Context.IntTy) {
2456 // Make sure the init value is signed.
2457 llvm::APSInt IV = ECD->getInitVal();
2458 IV.setIsSigned(true);
2459 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002460 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002461 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002462
2463 // Determine whether the value fits into an int.
2464 llvm::APSInt InitVal = ECD->getInitVal();
2465 bool FitsInInt;
2466 if (InitVal.isUnsigned() || !InitVal.isNegative())
2467 FitsInInt = InitVal.getActiveBits() < IntWidth;
2468 else
2469 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2470
2471 // If it fits into an integer type, force it. Otherwise force it to match
2472 // the enum decl type.
2473 QualType NewTy;
2474 unsigned NewWidth;
2475 bool NewSign;
2476 if (FitsInInt) {
2477 NewTy = Context.IntTy;
2478 NewWidth = IntWidth;
2479 NewSign = true;
2480 } else if (ECD->getType() == BestType) {
2481 // Already the right type!
2482 continue;
2483 } else {
2484 NewTy = BestType;
2485 NewWidth = BestWidth;
2486 NewSign = BestType->isSignedIntegerType();
2487 }
2488
2489 // Adjust the APSInt value.
2490 InitVal.extOrTrunc(NewWidth);
2491 InitVal.setIsSigned(NewSign);
2492 ECD->setInitVal(InitVal);
2493
2494 // Adjust the Expr initializer and type.
2495 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2496 ECD->setType(NewTy);
2497 }
Chris Lattnerac609682007-08-28 06:15:15 +00002498
Chris Lattnere00b18c2007-08-28 18:24:31 +00002499 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002500 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002501}
2502
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002503Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2504 ExprTy *expr) {
2505 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2506
Chris Lattner8e25d862008-03-16 00:16:02 +00002507 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002508}
2509
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002510Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002511 SourceLocation LBrace,
2512 SourceLocation RBrace,
2513 const char *Lang,
2514 unsigned StrSize,
2515 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002516 LinkageSpecDecl::LanguageIDs Language;
2517 Decl *dcl = static_cast<Decl *>(D);
2518 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2519 Language = LinkageSpecDecl::lang_c;
2520 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2521 Language = LinkageSpecDecl::lang_cxx;
2522 else {
2523 Diag(Loc, diag::err_bad_language);
2524 return 0;
2525 }
2526
2527 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002528 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002529}