blob: fee732f2f56ca10e8fe14fc202d738a1a8d94c7e [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
Daniel Dunbar4cde9272008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000029using namespace clang;
30
Argyrios Kyrtzidis39caa082008-08-01 10:35:27 +000031Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroffb327ce02008-04-02 14:35:35 +000032 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
33
Douglas Gregor2ce52f32008-04-13 21:07:44 +000034 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
35 isa<ObjCInterfaceDecl>(IIDecl) ||
36 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000037 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000038 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000039}
40
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000041DeclContext *Sema::getDCParent(DeclContext *DC) {
42 // If CurContext is a ObjC method, getParent() will return NULL.
43 if (isa<ObjCMethodDecl>(DC))
44 return Context.getTranslationUnitDecl();
45
46 // A C++ inline method is parsed *after* the topmost class it was declared in
47 // is fully parsed (it's "complete").
48 // The parsing of a C++ inline method happens at the declaration context of
49 // the topmost (non-nested) class it is declared in.
50 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
51 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
52 DC = MD->getParent();
53 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
54 DC = RD;
55
56 // Return the declaration context of the topmost class the inline method is
57 // declared in.
58 return DC;
59 }
60
61 return DC->getParent();
62}
63
Chris Lattner9fdf9c62008-04-22 18:39:57 +000064void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000065 assert(getDCParent(DC) == CurContext &&
66 "The next DeclContext should be directly contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000067 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000068}
69
Chris Lattnerb048c982008-04-06 04:47:34 +000070void Sema::PopDeclContext() {
71 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000072 CurContext = getDCParent(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000073}
74
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000075/// Add this decl to the scope shadowed decl chains.
76void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000077 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000078
79 // C++ [basic.scope]p4:
80 // -- exactly one declaration shall declare a class name or
81 // enumeration name that is not a typedef name and the other
82 // declarations shall all refer to the same object or
83 // enumerator, or all refer to functions and function templates;
84 // in this case the class name or enumeration name is hidden.
85 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
86 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000087 IdentifierResolver::iterator
88 I = IdResolver.begin(TD->getIdentifier(),
89 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +000090 if (I != IdResolver.end() && 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
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000198 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000199 InitBuiltinVaListType();
200
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000201 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000202 FunctionDecl *New = FunctionDecl::Create(Context,
203 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000204 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000205 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000206
Chris Lattner95e2c712008-05-05 22:18:14 +0000207 // Create Decl objects for each parameter, adding them to the
208 // FunctionDecl.
209 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
210 llvm::SmallVector<ParmVarDecl*, 16> Params;
211 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
212 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
213 FT->getArgType(i), VarDecl::None, 0,
214 0));
215 New->setParams(&Params[0], Params.size());
216 }
217
218
219
Chris Lattner7f925cc2008-04-11 07:00:53 +0000220 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000221 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000222 return New;
223}
224
225/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
226/// and scope as a previous declaration 'Old'. Figure out how to resolve this
227/// situation, merging decls or emitting diagnostics as appropriate.
228///
Steve Naroffe8043c32008-04-01 23:04:06 +0000229TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000230 // Allow multiple definitions for ObjC built-in typedefs.
231 // FIXME: Verify the underlying types are equivalent!
232 if (getLangOptions().ObjC1) {
233 const IdentifierInfo *typeIdent = New->getIdentifier();
234 if (typeIdent == Ident_id) {
235 Context.setObjCIdType(New);
236 return New;
237 } else if (typeIdent == Ident_Class) {
238 Context.setObjCClassType(New);
239 return New;
240 } else if (typeIdent == Ident_SEL) {
241 Context.setObjCSelType(New);
242 return New;
243 } else if (typeIdent == Ident_Protocol) {
244 Context.setObjCProtoType(New->getUnderlyingType());
245 return New;
246 }
247 // Fall through - the typedef name was not a builtin type.
248 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000249 // Verify the old decl was also a typedef.
250 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
251 if (!Old) {
252 Diag(New->getLocation(), diag::err_redefinition_different_kind,
253 New->getName());
254 Diag(OldD->getLocation(), diag::err_previous_definition);
255 return New;
256 }
257
Chris Lattner99cb9972008-07-25 18:44:27 +0000258 // If the typedef types are not identical, reject them in all languages and
259 // with any extensions enabled.
260 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
261 Context.getCanonicalType(Old->getUnderlyingType()) !=
262 Context.getCanonicalType(New->getUnderlyingType())) {
263 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
264 New->getUnderlyingType().getAsString(),
265 Old->getUnderlyingType().getAsString());
266 Diag(Old->getLocation(), diag::err_previous_definition);
267 return Old;
268 }
269
Eli Friedman54ecfce2008-06-11 06:20:39 +0000270 if (getLangOptions().Microsoft) return New;
271
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000272 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
273 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
274 // *either* declaration is in a system header. The code below implements
275 // this adhoc compatibility rule. FIXME: The following code will not
276 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000277 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
278 SourceManager &SrcMgr = Context.getSourceManager();
279 if (SrcMgr.isInSystemHeader(Old->getLocation()))
280 return New;
281 if (SrcMgr.isInSystemHeader(New->getLocation()))
282 return New;
283 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000284
Ted Kremenek2d05c082008-05-23 21:28:18 +0000285 Diag(New->getLocation(), diag::err_redefinition, New->getName());
286 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000287 return New;
288}
289
Chris Lattner6b6b5372008-06-26 18:38:35 +0000290/// DeclhasAttr - returns true if decl Declaration already has the target
291/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000292static bool DeclHasAttr(const Decl *decl, const Attr *target) {
293 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
294 if (attr->getKind() == target->getKind())
295 return true;
296
297 return false;
298}
299
300/// MergeAttributes - append attributes from the Old decl to the New one.
301static void MergeAttributes(Decl *New, Decl *Old) {
302 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
303
Chris Lattnerddee4232008-03-03 03:28:21 +0000304 while (attr) {
305 tmp = attr;
306 attr = attr->getNext();
307
308 if (!DeclHasAttr(New, tmp)) {
309 New->addAttr(tmp);
310 } else {
311 tmp->setNext(0);
312 delete(tmp);
313 }
314 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000315
316 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000317}
318
Chris Lattner04421082008-04-08 04:40:51 +0000319/// MergeFunctionDecl - We just parsed a function 'New' from
320/// declarator D which has the same name and scope as a previous
321/// declaration 'Old'. Figure out how to resolve this situation,
322/// merging decls or emitting diagnostics as appropriate.
Douglas Gregorf0097952008-04-21 02:02:58 +0000323/// Redeclaration will be set true if thisNew is a redeclaration OldD.
324FunctionDecl *
325Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
326 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000327 // Verify the old decl was also a function.
328 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
329 if (!Old) {
330 Diag(New->getLocation(), diag::err_redefinition_different_kind,
331 New->getName());
332 Diag(OldD->getLocation(), diag::err_previous_definition);
333 return New;
334 }
Chris Lattner04421082008-04-08 04:40:51 +0000335
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000336 QualType OldQType = Context.getCanonicalType(Old->getType());
337 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000338
Chris Lattner04421082008-04-08 04:40:51 +0000339 // C++ [dcl.fct]p3:
340 // All declarations for a function shall agree exactly in both the
341 // return type and the parameter-type-list.
Douglas Gregorf0097952008-04-21 02:02:58 +0000342 if (getLangOptions().CPlusPlus && OldQType == NewQType) {
343 MergeAttributes(New, Old);
344 Redeclaration = true;
Chris Lattner04421082008-04-08 04:40:51 +0000345 return MergeCXXFunctionDecl(New, Old);
Douglas Gregorf0097952008-04-21 02:02:58 +0000346 }
Chris Lattner04421082008-04-08 04:40:51 +0000347
348 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000349 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000350 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000351 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000352 MergeAttributes(New, Old);
353 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000354 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000355 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000356
Steve Naroff837618c2008-01-16 15:01:34 +0000357 // A function that has already been declared has been redeclared or defined
358 // with a different type- show appropriate diagnostic
Steve Naroffe2ef8152008-04-04 14:32:09 +0000359 diag::kind PrevDiag;
Douglas Gregorf0097952008-04-21 02:02:58 +0000360 if (Old->isThisDeclarationADefinition())
Steve Naroffe2ef8152008-04-04 14:32:09 +0000361 PrevDiag = diag::err_previous_definition;
362 else if (Old->isImplicit())
363 PrevDiag = diag::err_previous_implicit_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000364 else
Steve Naroffe2ef8152008-04-04 14:32:09 +0000365 PrevDiag = diag::err_previous_declaration;
Steve Naroff837618c2008-01-16 15:01:34 +0000366
Reid Spencer5f016e22007-07-11 17:01:13 +0000367 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
368 // TODO: This is totally simplistic. It should handle merging functions
369 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000370 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
371 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000372 return New;
373}
374
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000375/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000376static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000377 if (VD->isFileVarDecl())
378 return (!VD->getInit() &&
379 (VD->getStorageClass() == VarDecl::None ||
380 VD->getStorageClass() == VarDecl::Static));
381 return false;
382}
383
384/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
385/// when dealing with C "tentative" external object definitions (C99 6.9.2).
386void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
387 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000388 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000389
390 for (IdentifierResolver::iterator
391 I = IdResolver.begin(VD->getIdentifier(),
392 VD->getDeclContext(), false/*LookInParentCtx*/),
393 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000394 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000395 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
396
Steve Narofff855e6f2008-08-10 15:20:13 +0000397 // Handle the following case:
398 // int a[10];
399 // int a[]; - the code below makes sure we set the correct type.
400 // int a[11]; - this is an error, size isn't 10.
401 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
402 OldDecl->getType()->isConstantArrayType())
403 VD->setType(OldDecl->getType());
404
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000405 // Check for "tentative" definitions. We can't accomplish this in
406 // MergeVarDecl since the initializer hasn't been attached.
407 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
408 continue;
409
410 // Handle __private_extern__ just like extern.
411 if (OldDecl->getStorageClass() != VarDecl::Extern &&
412 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
413 VD->getStorageClass() != VarDecl::Extern &&
414 VD->getStorageClass() != VarDecl::PrivateExtern) {
415 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
416 Diag(OldDecl->getLocation(), diag::err_previous_definition);
417 }
418 }
419 }
420}
421
Reid Spencer5f016e22007-07-11 17:01:13 +0000422/// MergeVarDecl - We just parsed a variable 'New' which has the same name
423/// and scope as a previous declaration 'Old'. Figure out how to resolve this
424/// situation, merging decls or emitting diagnostics as appropriate.
425///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000426/// Tentative definition rules (C99 6.9.2p2) are checked by
427/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
428/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000429///
Steve Naroffe8043c32008-04-01 23:04:06 +0000430VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 // Verify the old decl was also a variable.
432 VarDecl *Old = dyn_cast<VarDecl>(OldD);
433 if (!Old) {
434 Diag(New->getLocation(), diag::err_redefinition_different_kind,
435 New->getName());
436 Diag(OldD->getLocation(), diag::err_previous_definition);
437 return New;
438 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000439
440 MergeAttributes(New, Old);
441
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000443 QualType OldCType = Context.getCanonicalType(Old->getType());
444 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000445 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 Diag(New->getLocation(), diag::err_redefinition, New->getName());
447 Diag(Old->getLocation(), diag::err_previous_definition);
448 return New;
449 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000450 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
451 if (New->getStorageClass() == VarDecl::Static &&
452 (Old->getStorageClass() == VarDecl::None ||
453 Old->getStorageClass() == VarDecl::Extern)) {
454 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
455 Diag(Old->getLocation(), diag::err_previous_definition);
456 return New;
457 }
458 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
459 if (New->getStorageClass() != VarDecl::Static &&
460 Old->getStorageClass() == VarDecl::Static) {
461 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
462 Diag(Old->getLocation(), diag::err_previous_definition);
463 return New;
464 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000465 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
466 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 Diag(New->getLocation(), diag::err_redefinition, New->getName());
468 Diag(Old->getLocation(), diag::err_previous_definition);
469 }
470 return New;
471}
472
Chris Lattner04421082008-04-08 04:40:51 +0000473/// CheckParmsForFunctionDef - Check that the parameters of the given
474/// function are appropriate for the definition of a function. This
475/// takes care of any checks that cannot be performed on the
476/// declaration itself, e.g., that the types of each of the function
477/// parameters are complete.
478bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
479 bool HasInvalidParm = false;
480 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
481 ParmVarDecl *Param = FD->getParamDecl(p);
482
483 // C99 6.7.5.3p4: the parameters in a parameter type list in a
484 // function declarator that is part of a function definition of
485 // that function shall not have incomplete type.
486 if (Param->getType()->isIncompleteType() &&
487 !Param->isInvalidDecl()) {
488 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
489 Param->getType().getAsString());
490 Param->setInvalidDecl();
491 HasInvalidParm = true;
492 }
493 }
494
495 return HasInvalidParm;
496}
497
Reid Spencer5f016e22007-07-11 17:01:13 +0000498/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
499/// no declarator (e.g. "struct foo;") is parsed.
500Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
501 // TODO: emit error on 'int;' or 'const enum foo;'.
502 // TODO: emit error on 'typedef int;'
503 // if (!DS.isMissingDeclaratorOk()) Diag(...);
504
Steve Naroff92199282007-11-17 21:37:36 +0000505 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000506}
507
Steve Naroffd0091aa2008-01-10 22:15:12 +0000508bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000509 // Get the type before calling CheckSingleAssignmentConstraints(), since
510 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000511 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000512
Chris Lattner5cf216b2008-01-04 18:04:52 +0000513 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
514 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
515 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000516}
517
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000518bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000519 const ArrayType *AT = Context.getAsArrayType(DeclT);
520
521 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000522 // C99 6.7.8p14. We have an array of character type with unknown size
523 // being initialized to a string literal.
524 llvm::APSInt ConstVal(32);
525 ConstVal = strLiteral->getByteLength() + 1;
526 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000527 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000528 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000529 } else {
530 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000531 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000532 // FIXME: Avoid truncation for 64-bit length strings.
533 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000534 Diag(strLiteral->getSourceRange().getBegin(),
535 diag::warn_initializer_string_for_char_array_too_long,
536 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000537 }
538 // Set type from "char *" to "constant array of char".
539 strLiteral->setType(DeclT);
540 // For now, we always return false (meaning success).
541 return false;
542}
543
544StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000545 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000546 if (AT && AT->getElementType()->isCharType()) {
547 return dyn_cast<StringLiteral>(Init);
548 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000549 return 0;
550}
551
Steve Naroffa9960332008-01-25 00:51:06 +0000552bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000553 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
554 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000555 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroffca107302008-01-21 23:53:58 +0000556 return Diag(VAT->getSizeExpr()->getLocStart(),
557 diag::err_variable_object_no_init,
558 VAT->getSizeExpr()->getSourceRange());
559
Steve Naroff2fdc3742007-12-10 22:44:33 +0000560 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
561 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000562 // FIXME: Handle wide strings
563 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
564 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000565
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000566 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000567 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 Kyrtzidis15a12d02008-09-09 21:18:04 +0000624 if (PrevDecl && 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(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000665 II, R, SC, isInline, LastDeclarator,
666 // FIXME: Move to DeclGroup...
667 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000668 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000669 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000670 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000671
Daniel Dunbara80f8742008-08-05 01:35:17 +0000672 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000673 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000674 // The parser guarantees this is a string.
675 StringLiteral *SE = cast<StringLiteral>(E);
676 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
677 SE->getByteLength())));
678 }
679
Chris Lattner04421082008-04-08 04:40:51 +0000680 // Copy the parameter declarations from the declarator D to
681 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000682 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000683 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
684
685 // Create Decl objects for each parameter, adding them to the
686 // FunctionDecl.
687 llvm::SmallVector<ParmVarDecl*, 16> Params;
688
689 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
690 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000691 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000692 // We let through "const void" here because Sema::GetTypeForDeclarator
693 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000694 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
695 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000696 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
697 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000698 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
699
Chris Lattnerdef026a2008-04-10 02:26:16 +0000700 // In C++, the empty parameter-type-list must be spelled "void"; a
701 // typedef of void is not permitted.
702 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000703 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000704 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
705 }
706
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000707 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000708 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
709 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
710 }
711
712 NewFD->setParams(&Params[0], Params.size());
713 }
714
Steve Naroffffce4d52008-01-09 23:34:55 +0000715 // Merge the decl with the existing one if appropriate. Since C functions
716 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000717 if (PrevDecl &&
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000718 (!getLangOptions().CPlusPlus||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(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000771 II, R, SC, LastDeclarator,
772 // FIXME: Move to DeclGroup...
773 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar6f0200e2008-09-08 20:05:47 +0000774 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +0000775 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000776 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000777 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000778
Daniel Dunbara735ad82008-08-06 00:03:29 +0000779 // Handle GNU asm-label extension (encoded as an attribute).
780 if (Expr *E = (Expr*) D.getAsmLabel()) {
781 // The parser guarantees this is a string.
782 StringLiteral *SE = cast<StringLiteral>(E);
783 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
784 SE->getByteLength())));
785 }
786
Nate Begemanc8e89a82008-03-14 18:07:10 +0000787 // Emit an error if an address space was applied to decl with local storage.
788 // This includes arrays of objects with address space qualifiers, but not
789 // automatic variables that point to other address spaces.
790 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000791 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
792 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
793 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000794 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000795 // Merge the decl with the existing one if appropriate. If the decl is
796 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000797 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000798 NewVD = MergeVarDecl(NewVD, PrevDecl);
799 if (NewVD == 0) return 0;
800 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000801 New = NewVD;
802 }
803
804 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000805 if (II)
806 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000807 // If any semantic error occurred, mark the decl as invalid.
808 if (D.getInvalidType() || InvalidDecl)
809 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000810
811 return New;
812}
813
Eli Friedmanc594b322008-05-20 13:48:25 +0000814bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
815 switch (Init->getStmtClass()) {
816 default:
817 Diag(Init->getExprLoc(),
818 diag::err_init_element_not_constant, Init->getSourceRange());
819 return true;
820 case Expr::ParenExprClass: {
821 const ParenExpr* PE = cast<ParenExpr>(Init);
822 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
823 }
824 case Expr::CompoundLiteralExprClass:
825 return cast<CompoundLiteralExpr>(Init)->isFileScope();
826 case Expr::DeclRefExprClass: {
827 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000828 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
829 if (VD->hasGlobalStorage())
830 return false;
831 Diag(Init->getExprLoc(),
832 diag::err_init_element_not_constant, Init->getSourceRange());
833 return true;
834 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000835 if (isa<FunctionDecl>(D))
836 return false;
837 Diag(Init->getExprLoc(),
838 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000839 return true;
840 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000841 case Expr::MemberExprClass: {
842 const MemberExpr *M = cast<MemberExpr>(Init);
843 if (M->isArrow())
844 return CheckAddressConstantExpression(M->getBase());
845 return CheckAddressConstantExpressionLValue(M->getBase());
846 }
847 case Expr::ArraySubscriptExprClass: {
848 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
849 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
850 return CheckAddressConstantExpression(ASE->getBase()) ||
851 CheckArithmeticConstantExpression(ASE->getIdx());
852 }
853 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +0000854 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +0000855 return false;
856 case Expr::UnaryOperatorClass: {
857 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
858
859 // C99 6.6p9
860 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000861 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000862
863 Diag(Init->getExprLoc(),
864 diag::err_init_element_not_constant, Init->getSourceRange());
865 return true;
866 }
867 }
868}
869
870bool Sema::CheckAddressConstantExpression(const Expr* Init) {
871 switch (Init->getStmtClass()) {
872 default:
873 Diag(Init->getExprLoc(),
874 diag::err_init_element_not_constant, Init->getSourceRange());
875 return true;
Chris Lattner506ff882008-10-06 07:26:43 +0000876 case Expr::ParenExprClass:
877 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000878 case Expr::StringLiteralClass:
879 case Expr::ObjCStringLiteralClass:
880 return false;
Chris Lattner506ff882008-10-06 07:26:43 +0000881 case Expr::CallExprClass:
882 // __builtin___CFStringMakeConstantString is a valid constant l-value.
883 if (cast<CallExpr>(Init)->isBuiltinCall() ==
884 Builtin::BI__builtin___CFStringMakeConstantString)
885 return false;
886
887 Diag(Init->getExprLoc(),
888 diag::err_init_element_not_constant, Init->getSourceRange());
889 return true;
890
Eli Friedmanc594b322008-05-20 13:48:25 +0000891 case Expr::UnaryOperatorClass: {
892 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
893
894 // C99 6.6p9
895 if (Exp->getOpcode() == UnaryOperator::AddrOf)
896 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
897
898 if (Exp->getOpcode() == UnaryOperator::Extension)
899 return CheckAddressConstantExpression(Exp->getSubExpr());
900
901 Diag(Init->getExprLoc(),
902 diag::err_init_element_not_constant, Init->getSourceRange());
903 return true;
904 }
905 case Expr::BinaryOperatorClass: {
906 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
907 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
908
909 Expr *PExp = Exp->getLHS();
910 Expr *IExp = Exp->getRHS();
911 if (IExp->getType()->isPointerType())
912 std::swap(PExp, IExp);
913
914 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
915 return CheckAddressConstantExpression(PExp) ||
916 CheckArithmeticConstantExpression(IExp);
917 }
Eli Friedmanc3f07642008-08-25 20:46:57 +0000918 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +0000919 case Expr::ExplicitCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +0000920 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +0000921 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
922 // Check for implicit promotion
923 if (SubExpr->getType()->isFunctionType() ||
924 SubExpr->getType()->isArrayType())
925 return CheckAddressConstantExpressionLValue(SubExpr);
926 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000927
928 // Check for pointer->pointer cast
929 if (SubExpr->getType()->isPointerType())
930 return CheckAddressConstantExpression(SubExpr);
931
Eli Friedmanc3f07642008-08-25 20:46:57 +0000932 if (SubExpr->getType()->isIntegralType()) {
933 // Check for the special-case of a pointer->int->pointer cast;
934 // this isn't standard, but some code requires it. See
935 // PR2720 for an example.
936 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
937 if (SubCast->getSubExpr()->getType()->isPointerType()) {
938 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
939 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
940 if (IntWidth >= PointerWidth) {
941 return CheckAddressConstantExpression(SubCast->getSubExpr());
942 }
943 }
944 }
945 }
946 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +0000947 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +0000948 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000949
950 Diag(Init->getExprLoc(),
951 diag::err_init_element_not_constant, Init->getSourceRange());
952 return true;
953 }
954 case Expr::ConditionalOperatorClass: {
955 // FIXME: Should we pedwarn here?
956 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
957 if (!Exp->getCond()->getType()->isArithmeticType()) {
958 Diag(Init->getExprLoc(),
959 diag::err_init_element_not_constant, Init->getSourceRange());
960 return true;
961 }
962 if (CheckArithmeticConstantExpression(Exp->getCond()))
963 return true;
964 if (Exp->getLHS() &&
965 CheckAddressConstantExpression(Exp->getLHS()))
966 return true;
967 return CheckAddressConstantExpression(Exp->getRHS());
968 }
969 case Expr::AddrLabelExprClass:
970 return false;
971 }
972}
973
Eli Friedman4caf0552008-06-09 05:05:07 +0000974static const Expr* FindExpressionBaseAddress(const Expr* E);
975
976static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
977 switch (E->getStmtClass()) {
978 default:
979 return E;
980 case Expr::ParenExprClass: {
981 const ParenExpr* PE = cast<ParenExpr>(E);
982 return FindExpressionBaseAddressLValue(PE->getSubExpr());
983 }
984 case Expr::MemberExprClass: {
985 const MemberExpr *M = cast<MemberExpr>(E);
986 if (M->isArrow())
987 return FindExpressionBaseAddress(M->getBase());
988 return FindExpressionBaseAddressLValue(M->getBase());
989 }
990 case Expr::ArraySubscriptExprClass: {
991 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
992 return FindExpressionBaseAddress(ASE->getBase());
993 }
994 case Expr::UnaryOperatorClass: {
995 const UnaryOperator *Exp = cast<UnaryOperator>(E);
996
997 if (Exp->getOpcode() == UnaryOperator::Deref)
998 return FindExpressionBaseAddress(Exp->getSubExpr());
999
1000 return E;
1001 }
1002 }
1003}
1004
1005static const Expr* FindExpressionBaseAddress(const Expr* E) {
1006 switch (E->getStmtClass()) {
1007 default:
1008 return E;
1009 case Expr::ParenExprClass: {
1010 const ParenExpr* PE = cast<ParenExpr>(E);
1011 return FindExpressionBaseAddress(PE->getSubExpr());
1012 }
1013 case Expr::UnaryOperatorClass: {
1014 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1015
1016 // C99 6.6p9
1017 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1018 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1019
1020 if (Exp->getOpcode() == UnaryOperator::Extension)
1021 return FindExpressionBaseAddress(Exp->getSubExpr());
1022
1023 return E;
1024 }
1025 case Expr::BinaryOperatorClass: {
1026 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1027
1028 Expr *PExp = Exp->getLHS();
1029 Expr *IExp = Exp->getRHS();
1030 if (IExp->getType()->isPointerType())
1031 std::swap(PExp, IExp);
1032
1033 return FindExpressionBaseAddress(PExp);
1034 }
1035 case Expr::ImplicitCastExprClass: {
1036 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1037
1038 // Check for implicit promotion
1039 if (SubExpr->getType()->isFunctionType() ||
1040 SubExpr->getType()->isArrayType())
1041 return FindExpressionBaseAddressLValue(SubExpr);
1042
1043 // Check for pointer->pointer cast
1044 if (SubExpr->getType()->isPointerType())
1045 return FindExpressionBaseAddress(SubExpr);
1046
1047 // We assume that we have an arithmetic expression here;
1048 // if we don't, we'll figure it out later
1049 return 0;
1050 }
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001051 case Expr::ExplicitCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001052 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1053
1054 // Check for pointer->pointer cast
1055 if (SubExpr->getType()->isPointerType())
1056 return FindExpressionBaseAddress(SubExpr);
1057
1058 // We assume that we have an arithmetic expression here;
1059 // if we don't, we'll figure it out later
1060 return 0;
1061 }
1062 }
1063}
1064
Eli Friedmanc594b322008-05-20 13:48:25 +00001065bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1066 switch (Init->getStmtClass()) {
1067 default:
1068 Diag(Init->getExprLoc(),
1069 diag::err_init_element_not_constant, Init->getSourceRange());
1070 return true;
1071 case Expr::ParenExprClass: {
1072 const ParenExpr* PE = cast<ParenExpr>(Init);
1073 return CheckArithmeticConstantExpression(PE->getSubExpr());
1074 }
1075 case Expr::FloatingLiteralClass:
1076 case Expr::IntegerLiteralClass:
1077 case Expr::CharacterLiteralClass:
1078 case Expr::ImaginaryLiteralClass:
1079 case Expr::TypesCompatibleExprClass:
1080 case Expr::CXXBoolLiteralExprClass:
1081 return false;
1082 case Expr::CallExprClass: {
1083 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001084
1085 // Allow any constant foldable calls to builtins.
1086 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001087 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001088
Eli Friedmanc594b322008-05-20 13:48:25 +00001089 Diag(Init->getExprLoc(),
1090 diag::err_init_element_not_constant, Init->getSourceRange());
1091 return true;
1092 }
1093 case Expr::DeclRefExprClass: {
1094 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1095 if (isa<EnumConstantDecl>(D))
1096 return false;
1097 Diag(Init->getExprLoc(),
1098 diag::err_init_element_not_constant, Init->getSourceRange());
1099 return true;
1100 }
1101 case Expr::CompoundLiteralExprClass:
1102 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1103 // but vectors are allowed to be magic.
1104 if (Init->getType()->isVectorType())
1105 return false;
1106 Diag(Init->getExprLoc(),
1107 diag::err_init_element_not_constant, Init->getSourceRange());
1108 return true;
1109 case Expr::UnaryOperatorClass: {
1110 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1111
1112 switch (Exp->getOpcode()) {
1113 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1114 // See C99 6.6p3.
1115 default:
1116 Diag(Init->getExprLoc(),
1117 diag::err_init_element_not_constant, Init->getSourceRange());
1118 return true;
1119 case UnaryOperator::SizeOf:
1120 case UnaryOperator::AlignOf:
1121 case UnaryOperator::OffsetOf:
1122 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1123 // See C99 6.5.3.4p2 and 6.6p3.
1124 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1125 return false;
1126 Diag(Init->getExprLoc(),
1127 diag::err_init_element_not_constant, Init->getSourceRange());
1128 return true;
1129 case UnaryOperator::Extension:
1130 case UnaryOperator::LNot:
1131 case UnaryOperator::Plus:
1132 case UnaryOperator::Minus:
1133 case UnaryOperator::Not:
1134 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1135 }
1136 }
1137 case Expr::SizeOfAlignOfTypeExprClass: {
1138 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1139 // Special check for void types, which are allowed as an extension
1140 if (Exp->getArgumentType()->isVoidType())
1141 return false;
1142 // alignof always evaluates to a constant.
1143 // FIXME: is sizeof(int[3.0]) a constant expression?
1144 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1145 Diag(Init->getExprLoc(),
1146 diag::err_init_element_not_constant, Init->getSourceRange());
1147 return true;
1148 }
1149 return false;
1150 }
1151 case Expr::BinaryOperatorClass: {
1152 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1153
1154 if (Exp->getLHS()->getType()->isArithmeticType() &&
1155 Exp->getRHS()->getType()->isArithmeticType()) {
1156 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1157 CheckArithmeticConstantExpression(Exp->getRHS());
1158 }
1159
Eli Friedman4caf0552008-06-09 05:05:07 +00001160 if (Exp->getLHS()->getType()->isPointerType() &&
1161 Exp->getRHS()->getType()->isPointerType()) {
1162 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1163 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1164
1165 // Only allow a null (constant integer) base; we could
1166 // allow some additional cases if necessary, but this
1167 // is sufficient to cover offsetof-like constructs.
1168 if (!LHSBase && !RHSBase) {
1169 return CheckAddressConstantExpression(Exp->getLHS()) ||
1170 CheckAddressConstantExpression(Exp->getRHS());
1171 }
1172 }
1173
Eli Friedmanc594b322008-05-20 13:48:25 +00001174 Diag(Init->getExprLoc(),
1175 diag::err_init_element_not_constant, Init->getSourceRange());
1176 return true;
1177 }
1178 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001179 case Expr::ExplicitCastExprClass: {
1180 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001181 if (SubExpr->getType()->isArithmeticType())
1182 return CheckArithmeticConstantExpression(SubExpr);
1183
Eli Friedmanb529d832008-09-02 09:37:00 +00001184 if (SubExpr->getType()->isPointerType()) {
1185 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1186 // If the pointer has a null base, this is an offsetof-like construct
1187 if (!Base)
1188 return CheckAddressConstantExpression(SubExpr);
1189 }
1190
Eli Friedman6d4abe12008-09-01 22:08:17 +00001191 Diag(Init->getExprLoc(),
1192 diag::err_init_element_not_constant, Init->getSourceRange());
1193 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001194 }
1195 case Expr::ConditionalOperatorClass: {
1196 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001197
1198 // If GNU extensions are disabled, we require all operands to be arithmetic
1199 // constant expressions.
1200 if (getLangOptions().NoExtensions) {
1201 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1202 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1203 CheckArithmeticConstantExpression(Exp->getRHS());
1204 }
1205
1206 // Otherwise, we have to emulate some of the behavior of fold here.
1207 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1208 // because it can constant fold things away. To retain compatibility with
1209 // GCC code, we see if we can fold the condition to a constant (which we
1210 // should always be able to do in theory). If so, we only require the
1211 // specified arm of the conditional to be a constant. This is a horrible
1212 // hack, but is require by real world code that uses __builtin_constant_p.
1213 APValue Val;
1214 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1215 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1216 // won't be able to either. Use it to emit the diagnostic though.
1217 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1218 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1219 return Res;
1220 }
1221
1222 // Verify that the side following the condition is also a constant.
1223 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1224 if (Val.getInt() == 0)
1225 std::swap(TrueSide, FalseSide);
1226
1227 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001228 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001229
1230 // Okay, the evaluated side evaluates to a constant, so we accept this.
1231 // Check to see if the other side is obviously not a constant. If so,
1232 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001233 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001234 Diag(Init->getExprLoc(),
1235 diag::ext_typecheck_expression_not_constant_but_accepted,
1236 FalseSide->getSourceRange());
1237 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001238 }
1239 }
1240}
1241
1242bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001243 Init = Init->IgnoreParens();
1244
Eli Friedmanc594b322008-05-20 13:48:25 +00001245 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1246 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1247 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1248
Nuno Lopes9a979c32008-07-07 16:46:50 +00001249 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1250 return CheckForConstantInitializer(e->getInitializer(), DclT);
1251
Eli Friedmanc594b322008-05-20 13:48:25 +00001252 if (Init->getType()->isReferenceType()) {
Chris Lattner46cfefa2008-10-06 05:42:39 +00001253 // FIXME: Work out how the heck references work.
Eli Friedmanc594b322008-05-20 13:48:25 +00001254 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001255 }
1256
1257 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1258 unsigned numInits = Exp->getNumInits();
1259 for (unsigned i = 0; i < numInits; i++) {
1260 // FIXME: Need to get the type of the declaration for C++,
1261 // because it could be a reference?
1262 if (CheckForConstantInitializer(Exp->getInit(i),
1263 Exp->getInit(i)->getType()))
1264 return true;
1265 }
1266 return false;
1267 }
1268
1269 if (Init->isNullPointerConstant(Context))
1270 return false;
1271 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001272 QualType InitTy = Context.getCanonicalType(Init->getType())
1273 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001274 if (InitTy == Context.BoolTy) {
1275 // Special handling for pointers implicitly cast to bool;
1276 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1277 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1278 Expr* SubE = ICE->getSubExpr();
1279 if (SubE->getType()->isPointerType() ||
1280 SubE->getType()->isArrayType() ||
1281 SubE->getType()->isFunctionType()) {
1282 return CheckAddressConstantExpression(Init);
1283 }
1284 }
1285 } else if (InitTy->isIntegralType()) {
1286 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001287 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001288 SubE = CE->getSubExpr();
1289 // Special check for pointer cast to int; we allow as an extension
1290 // an address constant cast to an integer if the integer
1291 // is of an appropriate width (this sort of code is apparently used
1292 // in some places).
1293 // FIXME: Add pedwarn?
1294 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1295 if (SubE && (SubE->getType()->isPointerType() ||
1296 SubE->getType()->isArrayType() ||
1297 SubE->getType()->isFunctionType())) {
1298 unsigned IntWidth = Context.getTypeSize(Init->getType());
1299 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1300 if (IntWidth >= PointerWidth)
1301 return CheckAddressConstantExpression(Init);
1302 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001303 }
1304
1305 return CheckArithmeticConstantExpression(Init);
1306 }
1307
1308 if (Init->getType()->isPointerType())
1309 return CheckAddressConstantExpression(Init);
1310
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001311 // An array type at the top level that isn't an init-list must
1312 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001313 if (Init->getType()->isArrayType())
1314 return false;
1315
Nuno Lopes73419bf2008-09-01 18:42:41 +00001316 if (Init->getType()->isFunctionType())
1317 return false;
1318
Steve Naroff8af6a452008-10-02 17:12:56 +00001319 // Allow block exprs at top level.
1320 if (Init->getType()->isBlockPointerType())
1321 return false;
1322
Eli Friedmanc594b322008-05-20 13:48:25 +00001323 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1324 Init->getSourceRange());
1325 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001326}
1327
Steve Naroffbb204692007-09-12 14:07:44 +00001328void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001329 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001330 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001331 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001332
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001333 // If there is no declaration, there was an error parsing it. Just ignore
1334 // the initializer.
1335 if (RealDecl == 0) {
1336 delete Init;
1337 return;
1338 }
Steve Naroffbb204692007-09-12 14:07:44 +00001339
Steve Naroff410e3e22007-09-12 20:13:48 +00001340 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1341 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001342 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1343 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001344 RealDecl->setInvalidDecl();
1345 return;
1346 }
Steve Naroffbb204692007-09-12 14:07:44 +00001347 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001348 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001349 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001350 if (VDecl->isBlockVarDecl()) {
1351 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001352 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001353 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001354 VDecl->setInvalidDecl();
1355 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001356 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001357 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001358
1359 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1360 if (!getLangOptions().CPlusPlus) {
1361 if (SC == VarDecl::Static) // C99 6.7.8p4.
1362 CheckForConstantInitializer(Init, DclT);
1363 }
Steve Naroffbb204692007-09-12 14:07:44 +00001364 }
Steve Naroff248a7532008-04-15 22:42:06 +00001365 } else if (VDecl->isFileVarDecl()) {
1366 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001367 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001368 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001369 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001370 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001371
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001372 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1373 if (!getLangOptions().CPlusPlus) {
1374 // C99 6.7.8p4. All file scoped initializers need to be constant.
1375 CheckForConstantInitializer(Init, DclT);
1376 }
Steve Naroffbb204692007-09-12 14:07:44 +00001377 }
1378 // If the type changed, it means we had an incomplete type that was
1379 // completed by the initializer. For example:
1380 // int ary[] = { 1, 3, 5 };
1381 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001382 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001383 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001384 Init->setType(DclT);
1385 }
Steve Naroffbb204692007-09-12 14:07:44 +00001386
1387 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001388 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001389 return;
1390}
1391
Reid Spencer5f016e22007-07-11 17:01:13 +00001392/// The declarators are chained together backwards, reverse the list.
1393Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1394 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001395 Decl *GroupDecl = static_cast<Decl*>(group);
1396 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001397 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001398
1399 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1400 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001401 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001402 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001403 else { // reverse the list.
1404 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001405 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001406 Group->setNextDeclarator(NewGroup);
1407 NewGroup = Group;
1408 Group = Next;
1409 }
1410 }
1411 // Perform semantic analysis that depends on having fully processed both
1412 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001413 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001414 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1415 if (!IDecl)
1416 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001417 QualType T = IDecl->getType();
1418
1419 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1420 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001421 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1422 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001423 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001424 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1425 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001426 }
1427 }
1428 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1429 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001430 if (IDecl->isBlockVarDecl() &&
1431 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001432 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001433 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1434 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001435 IDecl->setInvalidDecl();
1436 }
1437 }
1438 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1439 // object that has file scope without an initializer, and without a
1440 // storage-class specifier or with the storage-class specifier "static",
1441 // constitutes a tentative definition. Note: A tentative definition with
1442 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001443 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001444 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001445 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1446 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001447 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001448 // C99 6.9.2p3: If the declaration of an identifier for an object is
1449 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1450 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001451 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1452 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001453 IDecl->setInvalidDecl();
1454 }
1455 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001456 if (IDecl->isFileVarDecl())
1457 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001458 }
1459 return NewGroup;
1460}
Steve Naroffe1223f72007-08-28 03:03:08 +00001461
Chris Lattner04421082008-04-08 04:40:51 +00001462/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1463/// to introduce parameters into function prototype scope.
1464Sema::DeclTy *
1465Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001466 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001467
1468 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001469 VarDecl::StorageClass StorageClass = VarDecl::None;
1470 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1471 StorageClass = VarDecl::Register;
1472 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001473 Diag(DS.getStorageClassSpecLoc(),
1474 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001475 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001476 }
1477 if (DS.isThreadSpecified()) {
1478 Diag(DS.getThreadSpecLoc(),
1479 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001480 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001481 }
1482
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001483 // Check that there are no default arguments inside the type of this
1484 // parameter (C++ only).
1485 if (getLangOptions().CPlusPlus)
1486 CheckExtraCXXDefaultArguments(D);
1487
Chris Lattner04421082008-04-08 04:40:51 +00001488 // In this context, we *do not* check D.getInvalidType(). If the declarator
1489 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1490 // though it will not reflect the user specified type.
1491 QualType parmDeclType = GetTypeForDeclarator(D, S);
1492
1493 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1494
Reid Spencer5f016e22007-07-11 17:01:13 +00001495 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1496 // Can this happen for params? We already checked that they don't conflict
1497 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001498 IdentifierInfo *II = D.getIdentifier();
1499 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1500 if (S->isDeclScope(PrevDecl)) {
1501 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1502 dyn_cast<NamedDecl>(PrevDecl)->getName());
1503
1504 // Recover by removing the name
1505 II = 0;
1506 D.SetIdentifier(0, D.getIdentifierLoc());
1507 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001508 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001509
1510 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1511 // Doing the promotion here has a win and a loss. The win is the type for
1512 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1513 // code generator). The loss is the orginal type isn't preserved. For example:
1514 //
1515 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1516 // int blockvardecl[5];
1517 // sizeof(parmvardecl); // size == 4
1518 // sizeof(blockvardecl); // size == 20
1519 // }
1520 //
1521 // For expressions, all implicit conversions are captured using the
1522 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1523 //
1524 // FIXME: If a source translation tool needs to see the original type, then
1525 // we need to consider storing both types (in ParmVarDecl)...
1526 //
Chris Lattnere6327742008-04-02 05:18:44 +00001527 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001528 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001529 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001530 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001531 parmDeclType = Context.getPointerType(parmDeclType);
1532
Chris Lattner04421082008-04-08 04:40:51 +00001533 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1534 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001535 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001536 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001537
Chris Lattner04421082008-04-08 04:40:51 +00001538 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001539 New->setInvalidDecl();
1540
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001541 if (II)
1542 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001543
Chris Lattner3ff30c82008-06-29 00:02:00 +00001544 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001545 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001546
Reid Spencer5f016e22007-07-11 17:01:13 +00001547}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001548
Chris Lattnerb652cea2007-10-09 17:14:05 +00001549Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001550 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001551 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1552 "Not a function declarator!");
1553 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001554
Reid Spencer5f016e22007-07-11 17:01:13 +00001555 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1556 // for a K&R function.
1557 if (!FTI.hasPrototype) {
1558 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001559 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001560 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1561 FTI.ArgInfo[i].Ident->getName());
1562 // Implicitly declare the argument as type 'int' for lack of a better
1563 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001564 DeclSpec DS;
1565 const char* PrevSpec; // unused
1566 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1567 PrevSpec);
1568 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1569 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1570 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001571 }
1572 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001573 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001574 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001575 }
1576
1577 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001578
1579 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001580 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001581 GlobalScope);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001582 if (PrevDcl && isDeclInScope(PrevDcl, CurContext)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001583 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1584 const FunctionDecl *Definition;
1585 if (FD->getBody(Definition)) {
1586 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1587 D.getIdentifier()->getName());
1588 Diag(Definition->getLocation(), diag::err_previous_definition);
1589 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001590 }
1591 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001592
1593 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001594 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001595}
1596
1597Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1598 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001599 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001600 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001601
1602 // Check the validity of our function parameters
1603 CheckParmsForFunctionDef(FD);
1604
1605 // Introduce our parameters into the function scope
1606 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1607 ParmVarDecl *Param = FD->getParamDecl(p);
1608 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001609 if (Param->getIdentifier())
1610 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 }
Chris Lattner04421082008-04-08 04:40:51 +00001612
Reid Spencer5f016e22007-07-11 17:01:13 +00001613 return FD;
1614}
1615
Steve Naroffd6d054d2007-11-11 23:20:51 +00001616Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1617 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001618 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001619 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001620 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001621 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001622 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001623 } else
1624 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001625 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001626 // Verify and clean out per-function state.
1627
1628 // Check goto/label use.
1629 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1630 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1631 // Verify that we have no forward references left. If so, there was a goto
1632 // or address of a label taken, but no definition of it. Label fwd
1633 // definitions are indicated with a null substmt.
1634 if (I->second->getSubStmt() == 0) {
1635 LabelStmt *L = I->second;
1636 // Emit error.
1637 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1638
1639 // At this point, we have gotos that use the bogus label. Stitch it into
1640 // the function body so that they aren't leaked and that the AST is well
1641 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001642 if (Body) {
1643 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1644 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1645 } else {
1646 // The whole function wasn't parsed correctly, just delete this.
1647 delete L;
1648 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001649 }
1650 }
1651 LabelMap.clear();
1652
Steve Naroffd6d054d2007-11-11 23:20:51 +00001653 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001654}
1655
Reid Spencer5f016e22007-07-11 17:01:13 +00001656/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1657/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001658ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1659 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001660 // Extension in C99. Legal in C90, but warn about it.
1661 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001662 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001663 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001664 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1665
1666 // FIXME: handle stuff like:
1667 // void foo() { extern float X(); }
1668 // void bar() { X(); } <-- implicit decl for X in another scope.
1669
1670 // Set a Declarator for the implicit definition: int foo();
1671 const char *Dummy;
1672 DeclSpec DS;
1673 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1674 Error = Error; // Silence warning.
1675 assert(!Error && "Error setting up implicit decl!");
1676 Declarator D(DS, Declarator::BlockContext);
1677 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1678 D.SetIdentifier(&II, Loc);
1679
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001680 // Insert this function into translation-unit scope.
1681
1682 DeclContext *PrevDC = CurContext;
1683 CurContext = Context.getTranslationUnitDecl();
1684
Steve Naroffe2ef8152008-04-04 14:32:09 +00001685 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00001686 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001687 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001688
1689 CurContext = PrevDC;
1690
Steve Naroffe2ef8152008-04-04 14:32:09 +00001691 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001692}
1693
1694
Chris Lattner41af0932007-11-14 06:34:38 +00001695TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001696 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001697 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001698 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001699
1700 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001701 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1702 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001703 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001704 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001705 if (D.getInvalidType())
1706 NewTD->setInvalidDecl();
1707 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001708}
1709
Steve Naroff08d92e42007-09-15 18:49:24 +00001710/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001711/// former case, Name will be non-null. In the later case, Name will be null.
1712/// TagType indicates what kind of tag this is. TK indicates whether this is a
1713/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001714Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001715 SourceLocation KWLoc, IdentifierInfo *Name,
1716 SourceLocation NameLoc, AttributeList *Attr) {
1717 // If this is a use of an existing tag, it must have a name.
1718 assert((Name != 0 || TK == TK_Definition) &&
1719 "Nameless record must be a definition!");
1720
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001721 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001722 switch (TagType) {
1723 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001724 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1725 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1726 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1727 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001728 }
1729
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001730 // Two code paths: a new one for structs/unions/classes where we create
1731 // separate decls for forward declarations, and an old (eventually to
1732 // be removed) code path for enums.
1733 if (Kind != TagDecl::TK_enum)
1734 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
1735
Reid Spencer5f016e22007-07-11 17:01:13 +00001736 // If this is a named struct, check to see if there was a previous forward
1737 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001738 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenek7e8cc572008-09-02 21:26:19 +00001739 ScopedDecl *PrevDecl =
1740 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1741
1742 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001743 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1744 "unexpected Decl type");
1745 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001746 // If this is a use of a previous tag, or if the tag is already declared
1747 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001748 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001749 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001750 // Make sure that this wasn't declared as an enum and now used as a
1751 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001752 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001753 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1754 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00001755 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001756 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00001757 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001758 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00001759 // If this is a use or a forward declaration, we're good.
1760 if (TK != TK_Definition)
1761 return PrevDecl;
1762
1763 // Diagnose attempts to redefine a tag.
1764 if (PrevTagDecl->isDefinition()) {
1765 Diag(NameLoc, diag::err_redefinition, Name->getName());
1766 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1767 // If this is a redefinition, recover by making this struct be
1768 // anonymous, which will make any later references get the previous
1769 // definition.
1770 Name = 0;
1771 } else {
1772 // Okay, this is definition of a previously declared or referenced
1773 // tag. Move the location of the decl to be the definition site.
1774 PrevDecl->setLocation(NameLoc);
1775 return PrevDecl;
1776 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001777 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001779 // If we get here, this is a definition of a new struct type in a nested
1780 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1781 // type.
1782 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001783 // PrevDecl is a namespace.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001784 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00001785 // The tag name clashes with a namespace name, issue an error and
1786 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001787 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1788 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1789 Name = 0;
1790 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001791 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001792 }
1793
1794 // If there is an identifier, use the location of the identifier as the
1795 // location of the decl, otherwise use the location of the struct/union
1796 // keyword.
1797 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1798
1799 // Otherwise, if this is the first time we've seen this tag, create the decl.
1800 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001801 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001802 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1803 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001804 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001805 // If this is an undefined enum, warn.
1806 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001807 } else {
1808 // struct/union/class
1809
Reid Spencer5f016e22007-07-11 17:01:13 +00001810 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1811 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001812 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00001813 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenekdf042e62008-09-05 01:34:33 +00001814 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001815 else
Ted Kremenekdf042e62008-09-05 01:34:33 +00001816 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001817 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001818
1819 // If this has an identifier, add it to the scope stack.
1820 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001821 // The scope passed in may not be a decl scope. Zip up the scope tree until
1822 // we find one that is.
1823 while ((S->getFlags() & Scope::DeclScope) == 0)
1824 S = S->getParent();
1825
1826 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001827 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001828 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001829
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001830 if (Attr)
1831 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001832 return New;
1833}
1834
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001835/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
1836/// the logic for enums, we create separate decls for forward declarations.
1837/// This is called by ActOnTag, but eventually will replace its logic.
1838Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
1839 SourceLocation KWLoc, IdentifierInfo *Name,
1840 SourceLocation NameLoc, AttributeList *Attr) {
1841
1842 // If this is a named struct, check to see if there was a previous forward
1843 // declaration or definition.
1844 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1845 ScopedDecl *PrevDecl =
1846 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1847
1848 if (PrevDecl) {
1849 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1850 "unexpected Decl type");
1851
1852 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1853 // If this is a use of a previous tag, or if the tag is already declared
1854 // in the same scope (so that the definition/declaration completes or
1855 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001856 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001857 // Make sure that this wasn't declared as an enum and now used as a
1858 // struct or something similar.
1859 if (PrevTagDecl->getTagKind() != Kind) {
1860 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1861 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1862 // Recover by making this an anonymous redefinition.
1863 Name = 0;
1864 PrevDecl = 0;
1865 } else {
1866 // If this is a use, return the original decl.
1867
1868 // FIXME: In the future, return a variant or some other clue
1869 // for the consumer of this Decl to know it doesn't own it.
1870 // For our current ASTs this shouldn't be a problem, but will
1871 // need to be changed with DeclGroups.
1872 if (TK == TK_Reference)
1873 return PrevDecl;
1874
1875 // The new decl is a definition?
1876 if (TK == TK_Definition) {
1877 // Diagnose attempts to redefine a tag.
1878 if (RecordDecl* DefRecord =
1879 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
1880 Diag(NameLoc, diag::err_redefinition, Name->getName());
1881 Diag(DefRecord->getLocation(), diag::err_previous_definition);
1882 // If this is a redefinition, recover by making this struct be
1883 // anonymous, which will make any later references get the previous
1884 // definition.
1885 Name = 0;
1886 PrevDecl = 0;
1887 }
1888 // Okay, this is definition of a previously declared or referenced
1889 // tag. We're going to create a new Decl.
1890 }
1891 }
1892 // If we get here we have (another) forward declaration. Just create
1893 // a new decl.
1894 }
1895 else {
1896 // If we get here, this is a definition of a new struct type in a nested
1897 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
1898 // new decl/type. We set PrevDecl to NULL so that the Records
1899 // have distinct types.
1900 PrevDecl = 0;
1901 }
1902 } else {
1903 // PrevDecl is a namespace.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001904 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001905 // The tag name clashes with a namespace name, issue an error and
1906 // recover by making this tag be anonymous.
1907 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1908 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1909 Name = 0;
1910 }
1911 }
1912 }
1913
1914 // If there is an identifier, use the location of the identifier as the
1915 // location of the decl, otherwise use the location of the struct/union
1916 // keyword.
1917 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1918
1919 // Otherwise, if this is the first time we've seen this tag, create the decl.
1920 TagDecl *New;
1921
1922 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1923 // struct X { int A; } D; D should chain to X.
1924 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00001925 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001926 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1927 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
1928 else
1929 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
1930 dyn_cast_or_null<RecordDecl>(PrevDecl));
1931
1932 // If this has an identifier, add it to the scope stack.
1933 if ((TK == TK_Definition || !PrevDecl) && Name) {
1934 // The scope passed in may not be a decl scope. Zip up the scope tree until
1935 // we find one that is.
1936 while ((S->getFlags() & Scope::DeclScope) == 0)
1937 S = S->getParent();
1938
1939 // Add it to the decl chain.
1940 PushOnScopeChains(New, S);
1941 }
1942
1943 if (Attr)
1944 ProcessDeclAttributeList(New, Attr);
1945
1946 return New;
1947}
1948
1949
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001950/// Collect the instance variables declared in an Objective-C object. Used in
1951/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00001952static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001953 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001954 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00001955 CollectIvars(Class->getSuperClass(), Ctx, ivars);
1956
1957 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00001958 for (ObjCInterfaceDecl::ivar_iterator
1959 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
1960
Ted Kremenek01e67792008-08-20 03:26:33 +00001961 ObjCIvarDecl* ID = *I;
1962 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
1963 ID->getIdentifier(),
1964 ID->getType(),
1965 ID->getBitWidth()));
1966 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001967}
1968
1969/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
1970/// instance variables of ClassName into Decls.
1971void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
1972 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00001973 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001974 // Check that ClassName is a valid class
1975 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
1976 if (!Class) {
1977 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
1978 return;
1979 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001980 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00001981 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00001982}
1983
Eli Friedman1b76ada2008-06-03 21:01:11 +00001984QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
1985 // This method tries to turn a variable array into a constant
1986 // array even when the size isn't an ICE. This is necessary
1987 // for compatibility with code that depends on gcc's buggy
1988 // constant expression folding, like struct {char x[(int)(char*)2];}
1989 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00001990 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00001991 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00001992 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
1993 llvm::APSInt &Res = Result.getInt();
1994 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
1995 return Context.getConstantArrayType(VLATy->getElementType(),
1996 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00001997 }
1998 }
1999 return QualType();
2000}
2001
Steve Naroff08d92e42007-09-15 18:49:24 +00002002/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002003/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002004Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002005 SourceLocation DeclStart,
2006 Declarator &D, ExprTy *BitfieldWidth) {
2007 IdentifierInfo *II = D.getIdentifier();
2008 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002009 SourceLocation Loc = DeclStart;
2010 if (II) Loc = D.getIdentifierLoc();
2011
2012 // FIXME: Unnamed fields can be handled in various different ways, for
2013 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002014
Reid Spencer5f016e22007-07-11 17:01:13 +00002015 if (BitWidth) {
2016 // TODO: Validate.
2017 //printf("WARNING: BITFIELDS IGNORED!\n");
2018
2019 // 6.7.2.1p3
2020 // 6.7.2.1p4
2021
2022 } else {
2023 // Not a bitfield.
2024
2025 // validate II.
2026
2027 }
2028
2029 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002030 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2031 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002032
Reid Spencer5f016e22007-07-11 17:01:13 +00002033 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2034 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002035 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002036 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2037 if (!FixedTy.isNull()) {
2038 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2039 T = FixedTy;
2040 } else {
2041 // FIXME: This diagnostic needs work
2042 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2043 InvalidDecl = true;
2044 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002045 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002047 FieldDecl *NewFD;
2048
2049 if (getLangOptions().CPlusPlus) {
2050 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2051 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2052 Loc, II, T, BitWidth);
2053 if (II)
2054 PushOnScopeChains(NewFD, S);
2055 }
2056 else
2057 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002058
Chris Lattner3ff30c82008-06-29 00:02:00 +00002059 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002060
Steve Naroff5912a352007-08-28 20:14:24 +00002061 if (D.getInvalidType() || InvalidDecl)
2062 NewFD->setInvalidDecl();
2063 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002064}
2065
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002066/// TranslateIvarVisibility - Translate visibility from a token ID to an
2067/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002068static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002069TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002070 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002071 default: assert(0 && "Unknown visitibility kind");
2072 case tok::objc_private: return ObjCIvarDecl::Private;
2073 case tok::objc_public: return ObjCIvarDecl::Public;
2074 case tok::objc_protected: return ObjCIvarDecl::Protected;
2075 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002076 }
2077}
2078
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002079/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2080/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002081Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002082 SourceLocation DeclStart,
2083 Declarator &D, ExprTy *BitfieldWidth,
2084 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002085 IdentifierInfo *II = D.getIdentifier();
2086 Expr *BitWidth = (Expr*)BitfieldWidth;
2087 SourceLocation Loc = DeclStart;
2088 if (II) Loc = D.getIdentifierLoc();
2089
2090 // FIXME: Unnamed fields can be handled in various different ways, for
2091 // example, unnamed unions inject all members into the struct namespace!
2092
2093
2094 if (BitWidth) {
2095 // TODO: Validate.
2096 //printf("WARNING: BITFIELDS IGNORED!\n");
2097
2098 // 6.7.2.1p3
2099 // 6.7.2.1p4
2100
2101 } else {
2102 // Not a bitfield.
2103
2104 // validate II.
2105
2106 }
2107
2108 QualType T = GetTypeForDeclarator(D, S);
2109 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2110 bool InvalidDecl = false;
2111
2112 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2113 // than a variably modified type.
2114 if (T->isVariablyModifiedType()) {
2115 // FIXME: This diagnostic needs work
2116 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2117 InvalidDecl = true;
2118 }
2119
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002120 // Get the visibility (access control) for this ivar.
2121 ObjCIvarDecl::AccessControl ac =
2122 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2123 : ObjCIvarDecl::None;
2124
2125 // Construct the decl.
2126 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002127 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002128
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002129 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002130 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002131
2132 if (D.getInvalidType() || InvalidDecl)
2133 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002134
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002135 return NewID;
2136}
2137
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002138void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002139 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002140 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002141 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002142 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002143 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2144 assert(EnclosingDecl && "missing record or interface decl");
2145 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2146
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002147 if (Record)
2148 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2149 // Diagnose code like:
2150 // struct S { struct S {} X; };
2151 // We discover this when we complete the outer S. Reject and ignore the
2152 // outer S.
2153 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2154 DefRecord->getKindName());
2155 Diag(RecLoc, diag::err_previous_definition);
2156 Record->setInvalidDecl();
2157 return;
2158 }
2159
Reid Spencer5f016e22007-07-11 17:01:13 +00002160 // Verify that all the fields are okay.
2161 unsigned NumNamedMembers = 0;
2162 llvm::SmallVector<FieldDecl*, 32> RecFields;
2163 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002164
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002166
Steve Naroff74216642007-09-14 22:20:54 +00002167 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2168 assert(FD && "missing field decl");
2169
2170 // Remember all fields.
2171 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002172
2173 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002174 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002175
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002177 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002178 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002179 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002180 FD->setInvalidDecl();
2181 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002182 continue;
2183 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002184 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2185 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002186 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002187 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002188 FD->setInvalidDecl();
2189 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002190 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002191 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002192 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002193 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002194 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002195 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002196 FD->setInvalidDecl();
2197 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 continue;
2199 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002200 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002201 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2202 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002203 FD->setInvalidDecl();
2204 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002205 continue;
2206 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002207 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002208 if (Record)
2209 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002210 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002211 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2212 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002213 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002214 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2215 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002216 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002217 Record->setHasFlexibleArrayMember(true);
2218 } else {
2219 // If this is a struct/class and this is not the last element, reject
2220 // it. Note that GCC supports variable sized arrays in the middle of
2221 // structures.
2222 if (i != NumFields-1) {
2223 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2224 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002225 FD->setInvalidDecl();
2226 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002227 continue;
2228 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002229 // We support flexible arrays at the end of structs in other structs
2230 // as an extension.
2231 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2232 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002233 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002234 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002235 }
2236 }
2237 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002238 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002239 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002240 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2241 FD->getName());
2242 FD->setInvalidDecl();
2243 EnclosingDecl->setInvalidDecl();
2244 continue;
2245 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002246 // Keep track of the number of named members.
2247 if (IdentifierInfo *II = FD->getIdentifier()) {
2248 // Detect duplicate member names.
2249 if (!FieldIDs.insert(II)) {
2250 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2251 // Find the previous decl.
2252 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002253 for (unsigned i = 0; ; ++i) {
2254 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002255 if (RecFields[i]->getIdentifier() == II) {
2256 PrevLoc = RecFields[i]->getLocation();
2257 break;
2258 }
2259 }
2260 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002261 FD->setInvalidDecl();
2262 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002263 continue;
2264 }
2265 ++NumNamedMembers;
2266 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002267 }
2268
Reid Spencer5f016e22007-07-11 17:01:13 +00002269 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002270 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002271 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002272 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2273 // Sema::ActOnFinishCXXClassDef.
2274 if (!isa<CXXRecordDecl>(Record))
2275 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002276 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002277 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2278 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2279 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2280 else if (ObjCImplementationDecl *IMPDecl =
2281 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002282 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2283 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002284 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002285 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002286 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002287
2288 if (Attr)
2289 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002290}
2291
Steve Naroff08d92e42007-09-15 18:49:24 +00002292Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002293 DeclTy *lastEnumConst,
2294 SourceLocation IdLoc, IdentifierInfo *Id,
2295 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002296 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002297 EnumConstantDecl *LastEnumConst =
2298 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2299 Expr *Val = static_cast<Expr*>(val);
2300
Chris Lattner31e05722007-08-26 06:24:45 +00002301 // The scope passed in may not be a decl scope. Zip up the scope tree until
2302 // we find one that is.
2303 while ((S->getFlags() & Scope::DeclScope) == 0)
2304 S = S->getParent();
2305
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 // Verify that there isn't already something declared with this name in this
2307 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002308 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002309 // When in C++, we may get a TagDecl with the same name; in this case the
2310 // enum constant will 'hide' the tag.
2311 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2312 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002313 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002314 if (isa<EnumConstantDecl>(PrevDecl))
2315 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2316 else
2317 Diag(IdLoc, diag::err_redefinition, Id->getName());
2318 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002319 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002320 return 0;
2321 }
2322 }
2323
2324 llvm::APSInt EnumVal(32);
2325 QualType EltTy;
2326 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002327 // Make sure to promote the operand type to int.
2328 UsualUnaryConversions(Val);
2329
Reid Spencer5f016e22007-07-11 17:01:13 +00002330 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2331 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002332 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2334 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002335 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002336 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002337 } else {
2338 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002340 }
2341
2342 if (!Val) {
2343 if (LastEnumConst) {
2344 // Assign the last value + 1.
2345 EnumVal = LastEnumConst->getInitVal();
2346 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002347
2348 // Check for overflow on increment.
2349 if (EnumVal < LastEnumConst->getInitVal())
2350 Diag(IdLoc, diag::warn_enum_value_overflow);
2351
Chris Lattnerb7416f92007-08-27 17:37:24 +00002352 EltTy = LastEnumConst->getType();
2353 } else {
2354 // First value, set to zero.
2355 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002356 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002357 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002358 }
2359
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002360 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002361 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2362 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002363 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002364
2365 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002366 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 return New;
2368}
2369
Steve Naroff02408c62008-08-07 14:08:16 +00002370// FIXME: For consistency with ActOnFields(), we should have the parser
2371// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002372void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 DeclTy **Elements, unsigned NumElements) {
2374 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002375
Steve Naroff02408c62008-08-07 14:08:16 +00002376 if (Enum && Enum->isDefinition()) {
2377 // Diagnose code like:
2378 // enum e0 {
2379 // E0 = sizeof(enum e0 { E1 })
2380 // };
2381 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2382 Enum->getName());
2383 Diag(EnumLoc, diag::err_previous_definition);
2384 Enum->setInvalidDecl();
2385 return;
2386 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002387 // TODO: If the result value doesn't fit in an int, it must be a long or long
2388 // long value. ISO C does not support this, but GCC does as an extension,
2389 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002390 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002391
Chris Lattnerac609682007-08-28 06:15:15 +00002392 // Verify that all the values are okay, compute the size of the values, and
2393 // reverse the list.
2394 unsigned NumNegativeBits = 0;
2395 unsigned NumPositiveBits = 0;
2396
2397 // Keep track of whether all elements have type int.
2398 bool AllElementsInt = true;
2399
Reid Spencer5f016e22007-07-11 17:01:13 +00002400 EnumConstantDecl *EltList = 0;
2401 for (unsigned i = 0; i != NumElements; ++i) {
2402 EnumConstantDecl *ECD =
2403 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2404 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002405
2406 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002407 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002408 assert(InitVal.getBitWidth() >= IntWidth &&
2409 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002410 if (InitVal.getBitWidth() > IntWidth) {
2411 llvm::APSInt V(InitVal);
2412 V.trunc(IntWidth);
2413 V.extend(InitVal.getBitWidth());
2414 if (V != InitVal)
2415 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002416 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002417 }
Chris Lattnerac609682007-08-28 06:15:15 +00002418
2419 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002420 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002421 NumPositiveBits = std::max(NumPositiveBits,
2422 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002423 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002424 NumNegativeBits = std::max(NumNegativeBits,
2425 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002426
Chris Lattnerac609682007-08-28 06:15:15 +00002427 // Keep track of whether every enum element has type int (very commmon).
2428 if (AllElementsInt)
2429 AllElementsInt = ECD->getType() == Context.IntTy;
2430
Reid Spencer5f016e22007-07-11 17:01:13 +00002431 ECD->setNextDeclarator(EltList);
2432 EltList = ECD;
2433 }
2434
Chris Lattnerac609682007-08-28 06:15:15 +00002435 // Figure out the type that should be used for this enum.
2436 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2437 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002438 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002439
2440 if (NumNegativeBits) {
2441 // If there is a negative value, figure out the smallest integer type (of
2442 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002443 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002444 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002445 BestWidth = IntWidth;
2446 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002447 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002448
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002449 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002450 BestType = Context.LongTy;
2451 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002452 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002453
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002454 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002455 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2456 BestType = Context.LongLongTy;
2457 }
2458 }
2459 } else {
2460 // If there is no negative value, figure out which of uint, ulong, ulonglong
2461 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002462 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002463 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002464 BestWidth = IntWidth;
2465 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002466 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002467 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002468 } else {
2469 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002470 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002471 "How could an initializer get larger than ULL?");
2472 BestType = Context.UnsignedLongLongTy;
2473 }
2474 }
2475
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002476 // Loop over all of the enumerator constants, changing their types to match
2477 // the type of the enum if needed.
2478 for (unsigned i = 0; i != NumElements; ++i) {
2479 EnumConstantDecl *ECD =
2480 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2481 if (!ECD) continue; // Already issued a diagnostic.
2482
2483 // Standard C says the enumerators have int type, but we allow, as an
2484 // extension, the enumerators to be larger than int size. If each
2485 // enumerator value fits in an int, type it as an int, otherwise type it the
2486 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2487 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002488 if (ECD->getType() == Context.IntTy) {
2489 // Make sure the init value is signed.
2490 llvm::APSInt IV = ECD->getInitVal();
2491 IV.setIsSigned(true);
2492 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002493 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002494 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002495
2496 // Determine whether the value fits into an int.
2497 llvm::APSInt InitVal = ECD->getInitVal();
2498 bool FitsInInt;
2499 if (InitVal.isUnsigned() || !InitVal.isNegative())
2500 FitsInInt = InitVal.getActiveBits() < IntWidth;
2501 else
2502 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2503
2504 // If it fits into an integer type, force it. Otherwise force it to match
2505 // the enum decl type.
2506 QualType NewTy;
2507 unsigned NewWidth;
2508 bool NewSign;
2509 if (FitsInInt) {
2510 NewTy = Context.IntTy;
2511 NewWidth = IntWidth;
2512 NewSign = true;
2513 } else if (ECD->getType() == BestType) {
2514 // Already the right type!
2515 continue;
2516 } else {
2517 NewTy = BestType;
2518 NewWidth = BestWidth;
2519 NewSign = BestType->isSignedIntegerType();
2520 }
2521
2522 // Adjust the APSInt value.
2523 InitVal.extOrTrunc(NewWidth);
2524 InitVal.setIsSigned(NewSign);
2525 ECD->setInitVal(InitVal);
2526
2527 // Adjust the Expr initializer and type.
2528 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2529 ECD->setType(NewTy);
2530 }
Chris Lattnerac609682007-08-28 06:15:15 +00002531
Chris Lattnere00b18c2007-08-28 18:24:31 +00002532 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002533 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002534}
2535
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002536Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2537 ExprTy *expr) {
2538 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2539
Chris Lattner8e25d862008-03-16 00:16:02 +00002540 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002541}
2542
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002543Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002544 SourceLocation LBrace,
2545 SourceLocation RBrace,
2546 const char *Lang,
2547 unsigned StrSize,
2548 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002549 LinkageSpecDecl::LanguageIDs Language;
2550 Decl *dcl = static_cast<Decl *>(D);
2551 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2552 Language = LinkageSpecDecl::lang_c;
2553 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2554 Language = LinkageSpecDecl::lang_cxx;
2555 else {
2556 Diag(Loc, diag::err_bad_language);
2557 return 0;
2558 }
2559
2560 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002561 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002562}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00002563
2564void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
2565 ExprTy *alignment, SourceLocation PragmaLoc,
2566 SourceLocation LParenLoc, SourceLocation RParenLoc) {
2567 Expr *Alignment = static_cast<Expr *>(alignment);
2568
2569 // If specified then alignment must be a "small" power of two.
2570 unsigned AlignmentVal = 0;
2571 if (Alignment) {
2572 llvm::APSInt Val;
2573 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
2574 !Val.isPowerOf2() ||
2575 Val.getZExtValue() > 16) {
2576 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
2577 delete Alignment;
2578 return; // Ignore
2579 }
2580
2581 AlignmentVal = (unsigned) Val.getZExtValue();
2582 }
2583
2584 switch (Kind) {
2585 case Action::PPK_Default: // pack([n])
2586 PackContext.setAlignment(AlignmentVal);
2587 break;
2588
2589 case Action::PPK_Show: // pack(show)
2590 // Show the current alignment, making sure to show the right value
2591 // for the default.
2592 AlignmentVal = PackContext.getAlignment();
2593 // FIXME: This should come from the target.
2594 if (AlignmentVal == 0)
2595 AlignmentVal = 8;
2596 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
2597 break;
2598
2599 case Action::PPK_Push: // pack(push [, id] [, [n])
2600 PackContext.push(Name);
2601 // Set the new alignment if specified.
2602 if (Alignment)
2603 PackContext.setAlignment(AlignmentVal);
2604 break;
2605
2606 case Action::PPK_Pop: // pack(pop [, id] [, n])
2607 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
2608 // "#pragma pack(pop, identifier, n) is undefined"
2609 if (Alignment && Name)
2610 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
2611
2612 // Do the pop.
2613 if (!PackContext.pop(Name)) {
2614 // If a name was specified then failure indicates the name
2615 // wasn't found. Otherwise failure indicates the stack was
2616 // empty.
2617 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
2618 Name ? "no record matching name" : "stack empty");
2619
2620 // FIXME: Warn about popping named records as MSVC does.
2621 } else {
2622 // Pop succeeded, set the new alignment if specified.
2623 if (Alignment)
2624 PackContext.setAlignment(AlignmentVal);
2625 }
2626 break;
2627
2628 default:
2629 assert(0 && "Invalid #pragma pack kind.");
2630 }
2631}
2632
2633bool PragmaPackStack::pop(IdentifierInfo *Name) {
2634 if (Stack.empty())
2635 return false;
2636
2637 // If name is empty just pop top.
2638 if (!Name) {
2639 Alignment = Stack.back().first;
2640 Stack.pop_back();
2641 return true;
2642 }
2643
2644 // Otherwise, find the named record.
2645 for (unsigned i = Stack.size(); i != 0; ) {
2646 --i;
2647 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
2648 // Found it, pop up to and including this record.
2649 Alignment = Stack[i].first;
2650 Stack.erase(Stack.begin() + i, Stack.end());
2651 return true;
2652 }
2653 }
2654
2655 return false;
2656}