blob: 3e4e2c5b2c156dcdb7a8b50685c2da33c94c5fd5 [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 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +000098 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
99 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000100 // We are pushing the name of a function, which might be an
101 // overloaded name.
102 IdentifierResolver::iterator
103 I = IdResolver.begin(FD->getIdentifier(),
104 FD->getDeclContext(), false/*LookInParentCtx*/);
105 if (I != IdResolver.end() &&
106 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
107 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
108 // There is already a declaration with the same name in the same
109 // scope. It must be a function or an overloaded function.
110 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
111 if (!Ovl) {
112 // We haven't yet overloaded this function. Take the existing
113 // FunctionDecl and put it into an OverloadedFunctionDecl.
114 Ovl = OverloadedFunctionDecl::Create(Context,
115 FD->getDeclContext(),
116 FD->getIdentifier());
117 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
118
119 // Remove the name binding to the existing FunctionDecl...
120 IdResolver.RemoveDecl(*I);
121
122 // ... and put the OverloadedFunctionDecl in its place.
123 IdResolver.AddDecl(Ovl);
124 }
125
126 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
127 // to its list of overloads.
128 Ovl->addOverload(FD);
129
130 return;
131 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000132 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000134 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000135}
136
Steve Naroffb216c882007-10-09 22:01:59 +0000137void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000138 if (S->decl_empty()) return;
139 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000140
Reid Spencer5f016e22007-07-11 17:01:13 +0000141 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
142 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000143 Decl *TmpD = static_cast<Decl*>(*I);
144 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000145
146 if (isa<CXXFieldDecl>(TmpD)) continue;
147
148 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
149 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000150
Reid Spencer5f016e22007-07-11 17:01:13 +0000151 IdentifierInfo *II = D->getIdentifier();
152 if (!II) continue;
153
Ted Kremeneka89d1972008-09-03 18:03:35 +0000154 // We only want to remove the decls from the identifier decl chains for
155 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000156 if (S->getFnParent() != 0)
157 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000158
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000159 // Chain this decl to the containing DeclContext.
160 D->setNext(CurContext->getDeclChain());
161 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 }
163}
164
Steve Naroffe8043c32008-04-01 23:04:06 +0000165/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
166/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000167ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000168 // The third "scope" argument is 0 since we aren't enabling lazy built-in
169 // creation from this context.
170 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000171
Steve Naroffb327ce02008-04-02 14:35:35 +0000172 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000173}
174
Steve Naroffe8043c32008-04-01 23:04:06 +0000175/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000176/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000177Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
178 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000179 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000180 unsigned NS = NSI;
181 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
182 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000183
Reid Spencer5f016e22007-07-11 17:01:13 +0000184 // Scan up the scope chain looking for a decl that matches this identifier
185 // that is in the appropriate namespace. This search should not take long, as
186 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000187 for (IdentifierResolver::iterator
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000188 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000189 if ((*I)->getIdentifierNamespace() & NS)
190 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 // If we didn't find a use of this identifier, and if the identifier
193 // corresponds to a compiler builtin, create the decl object for the builtin
194 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000195 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000196 if (enableLazyBuiltinCreation) {
197 // If this is a builtin on this (or all) targets, create the decl.
198 if (unsigned BuiltinID = II->getBuiltinID())
199 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
200 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000201 if (getLangOptions().ObjC1) {
202 // @interface and @compatibility_alias introduce typedef-like names.
203 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000204 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000205 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000206 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
207 if (IDI != ObjCInterfaceDecls.end())
208 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000209 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
210 if (I != ObjCAliasDecls.end())
211 return I->second->getClassInterface();
212 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 }
214 return 0;
215}
216
Chris Lattner95e2c712008-05-05 22:18:14 +0000217void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000218 if (!Context.getBuiltinVaListType().isNull())
219 return;
220
221 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000222 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000223 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000224 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
225}
226
Reid Spencer5f016e22007-07-11 17:01:13 +0000227/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
228/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000229ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
230 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000231 Builtin::ID BID = (Builtin::ID)bid;
232
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000233 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000234 InitBuiltinVaListType();
235
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000236 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000237 FunctionDecl *New = FunctionDecl::Create(Context,
238 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000239 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000240 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000241
Chris Lattner95e2c712008-05-05 22:18:14 +0000242 // Create Decl objects for each parameter, adding them to the
243 // FunctionDecl.
244 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
245 llvm::SmallVector<ParmVarDecl*, 16> Params;
246 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
247 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
248 FT->getArgType(i), VarDecl::None, 0,
249 0));
250 New->setParams(&Params[0], Params.size());
251 }
252
253
254
Chris Lattner7f925cc2008-04-11 07:00:53 +0000255 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000256 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000257 return New;
258}
259
260/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
261/// and scope as a previous declaration 'Old'. Figure out how to resolve this
262/// situation, merging decls or emitting diagnostics as appropriate.
263///
Steve Naroffe8043c32008-04-01 23:04:06 +0000264TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000265 // Allow multiple definitions for ObjC built-in typedefs.
266 // FIXME: Verify the underlying types are equivalent!
267 if (getLangOptions().ObjC1) {
268 const IdentifierInfo *typeIdent = New->getIdentifier();
269 if (typeIdent == Ident_id) {
270 Context.setObjCIdType(New);
271 return New;
272 } else if (typeIdent == Ident_Class) {
273 Context.setObjCClassType(New);
274 return New;
275 } else if (typeIdent == Ident_SEL) {
276 Context.setObjCSelType(New);
277 return New;
278 } else if (typeIdent == Ident_Protocol) {
279 Context.setObjCProtoType(New->getUnderlyingType());
280 return New;
281 }
282 // Fall through - the typedef name was not a builtin type.
283 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000284 // Verify the old decl was also a typedef.
285 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
286 if (!Old) {
287 Diag(New->getLocation(), diag::err_redefinition_different_kind,
288 New->getName());
289 Diag(OldD->getLocation(), diag::err_previous_definition);
290 return New;
291 }
292
Chris Lattner99cb9972008-07-25 18:44:27 +0000293 // If the typedef types are not identical, reject them in all languages and
294 // with any extensions enabled.
295 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
296 Context.getCanonicalType(Old->getUnderlyingType()) !=
297 Context.getCanonicalType(New->getUnderlyingType())) {
298 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
299 New->getUnderlyingType().getAsString(),
300 Old->getUnderlyingType().getAsString());
301 Diag(Old->getLocation(), diag::err_previous_definition);
302 return Old;
303 }
304
Eli Friedman54ecfce2008-06-11 06:20:39 +0000305 if (getLangOptions().Microsoft) return New;
306
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000307 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
308 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
309 // *either* declaration is in a system header. The code below implements
310 // this adhoc compatibility rule. FIXME: The following code will not
311 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000312 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
313 SourceManager &SrcMgr = Context.getSourceManager();
314 if (SrcMgr.isInSystemHeader(Old->getLocation()))
315 return New;
316 if (SrcMgr.isInSystemHeader(New->getLocation()))
317 return New;
318 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000319
Ted Kremenek2d05c082008-05-23 21:28:18 +0000320 Diag(New->getLocation(), diag::err_redefinition, New->getName());
321 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000322 return New;
323}
324
Chris Lattner6b6b5372008-06-26 18:38:35 +0000325/// DeclhasAttr - returns true if decl Declaration already has the target
326/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000327static bool DeclHasAttr(const Decl *decl, const Attr *target) {
328 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
329 if (attr->getKind() == target->getKind())
330 return true;
331
332 return false;
333}
334
335/// MergeAttributes - append attributes from the Old decl to the New one.
336static void MergeAttributes(Decl *New, Decl *Old) {
337 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
338
Chris Lattnerddee4232008-03-03 03:28:21 +0000339 while (attr) {
340 tmp = attr;
341 attr = attr->getNext();
342
343 if (!DeclHasAttr(New, tmp)) {
344 New->addAttr(tmp);
345 } else {
346 tmp->setNext(0);
347 delete(tmp);
348 }
349 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000350
351 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000352}
353
Chris Lattner04421082008-04-08 04:40:51 +0000354/// MergeFunctionDecl - We just parsed a function 'New' from
355/// declarator D which has the same name and scope as a previous
356/// declaration 'Old'. Figure out how to resolve this situation,
357/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000358/// Redeclaration will be set true if this New is a redeclaration OldD.
359///
360/// In C++, New and Old must be declarations that are not
361/// overloaded. Use IsOverload to determine whether New and Old are
362/// overloaded, and to select the Old declaration that New should be
363/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000364FunctionDecl *
365Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000366 assert(!isa<OverloadedFunctionDecl>(OldD) &&
367 "Cannot merge with an overloaded function declaration");
368
Douglas Gregorf0097952008-04-21 02:02:58 +0000369 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000370 // Verify the old decl was also a function.
371 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
372 if (!Old) {
373 Diag(New->getLocation(), diag::err_redefinition_different_kind,
374 New->getName());
375 Diag(OldD->getLocation(), diag::err_previous_definition);
376 return New;
377 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000378
379 // Determine whether the previous declaration was a definition,
380 // implicit declaration, or a declaration.
381 diag::kind PrevDiag;
382 if (Old->isThisDeclarationADefinition())
383 PrevDiag = diag::err_previous_definition;
384 else if (Old->isImplicit())
385 PrevDiag = diag::err_previous_implicit_declaration;
386 else
387 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000388
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000389 QualType OldQType = Context.getCanonicalType(Old->getType());
390 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000391
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000392 if (getLangOptions().CPlusPlus) {
393 // (C++98 13.1p2):
394 // Certain function declarations cannot be overloaded:
395 // -- Function declarations that differ only in the return type
396 // cannot be overloaded.
397 QualType OldReturnType
398 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
399 QualType NewReturnType
400 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
401 if (OldReturnType != NewReturnType) {
402 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
403 Diag(Old->getLocation(), PrevDiag);
404 return New;
405 }
406
407 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
408 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
409 if (OldMethod && NewMethod) {
410 // -- Member function declarations with the same name and the
411 // same parameter types cannot be overloaded if any of them
412 // is a static member function declaration.
413 if (OldMethod->isStatic() || NewMethod->isStatic()) {
414 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
415 Diag(Old->getLocation(), PrevDiag);
416 return New;
417 }
418 }
419
420 // (C++98 8.3.5p3):
421 // All declarations for a function shall agree exactly in both the
422 // return type and the parameter-type-list.
423 if (OldQType == NewQType) {
424 // We have a redeclaration.
425 MergeAttributes(New, Old);
426 Redeclaration = true;
427 return MergeCXXFunctionDecl(New, Old);
428 }
429
430 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000431 }
Chris Lattner04421082008-04-08 04:40:51 +0000432
433 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000434 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000435 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000436 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000437 MergeAttributes(New, Old);
438 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000439 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000440 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000441
Steve Naroff837618c2008-01-16 15:01:34 +0000442 // A function that has already been declared has been redeclared or defined
443 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000444
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
446 // TODO: This is totally simplistic. It should handle merging functions
447 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000448 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
449 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000450 return New;
451}
452
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000453/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000454static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000455 if (VD->isFileVarDecl())
456 return (!VD->getInit() &&
457 (VD->getStorageClass() == VarDecl::None ||
458 VD->getStorageClass() == VarDecl::Static));
459 return false;
460}
461
462/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
463/// when dealing with C "tentative" external object definitions (C99 6.9.2).
464void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
465 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000466 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000467
468 for (IdentifierResolver::iterator
469 I = IdResolver.begin(VD->getIdentifier(),
470 VD->getDeclContext(), false/*LookInParentCtx*/),
471 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000472 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000473 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
474
Steve Narofff855e6f2008-08-10 15:20:13 +0000475 // Handle the following case:
476 // int a[10];
477 // int a[]; - the code below makes sure we set the correct type.
478 // int a[11]; - this is an error, size isn't 10.
479 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
480 OldDecl->getType()->isConstantArrayType())
481 VD->setType(OldDecl->getType());
482
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000483 // Check for "tentative" definitions. We can't accomplish this in
484 // MergeVarDecl since the initializer hasn't been attached.
485 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
486 continue;
487
488 // Handle __private_extern__ just like extern.
489 if (OldDecl->getStorageClass() != VarDecl::Extern &&
490 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
491 VD->getStorageClass() != VarDecl::Extern &&
492 VD->getStorageClass() != VarDecl::PrivateExtern) {
493 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
494 Diag(OldDecl->getLocation(), diag::err_previous_definition);
495 }
496 }
497 }
498}
499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500/// MergeVarDecl - We just parsed a variable 'New' which has the same name
501/// and scope as a previous declaration 'Old'. Figure out how to resolve this
502/// situation, merging decls or emitting diagnostics as appropriate.
503///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000504/// Tentative definition rules (C99 6.9.2p2) are checked by
505/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
506/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000507///
Steve Naroffe8043c32008-04-01 23:04:06 +0000508VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000509 // Verify the old decl was also a variable.
510 VarDecl *Old = dyn_cast<VarDecl>(OldD);
511 if (!Old) {
512 Diag(New->getLocation(), diag::err_redefinition_different_kind,
513 New->getName());
514 Diag(OldD->getLocation(), diag::err_previous_definition);
515 return New;
516 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000517
518 MergeAttributes(New, Old);
519
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000521 QualType OldCType = Context.getCanonicalType(Old->getType());
522 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000523 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000524 Diag(New->getLocation(), diag::err_redefinition, New->getName());
525 Diag(Old->getLocation(), diag::err_previous_definition);
526 return New;
527 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000528 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
529 if (New->getStorageClass() == VarDecl::Static &&
530 (Old->getStorageClass() == VarDecl::None ||
531 Old->getStorageClass() == VarDecl::Extern)) {
532 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
533 Diag(Old->getLocation(), diag::err_previous_definition);
534 return New;
535 }
536 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
537 if (New->getStorageClass() != VarDecl::Static &&
538 Old->getStorageClass() == VarDecl::Static) {
539 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
540 Diag(Old->getLocation(), diag::err_previous_definition);
541 return New;
542 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000543 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
544 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 Diag(New->getLocation(), diag::err_redefinition, New->getName());
546 Diag(Old->getLocation(), diag::err_previous_definition);
547 }
548 return New;
549}
550
Chris Lattner04421082008-04-08 04:40:51 +0000551/// CheckParmsForFunctionDef - Check that the parameters of the given
552/// function are appropriate for the definition of a function. This
553/// takes care of any checks that cannot be performed on the
554/// declaration itself, e.g., that the types of each of the function
555/// parameters are complete.
556bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
557 bool HasInvalidParm = false;
558 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
559 ParmVarDecl *Param = FD->getParamDecl(p);
560
561 // C99 6.7.5.3p4: the parameters in a parameter type list in a
562 // function declarator that is part of a function definition of
563 // that function shall not have incomplete type.
564 if (Param->getType()->isIncompleteType() &&
565 !Param->isInvalidDecl()) {
566 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
567 Param->getType().getAsString());
568 Param->setInvalidDecl();
569 HasInvalidParm = true;
570 }
571 }
572
573 return HasInvalidParm;
574}
575
Reid Spencer5f016e22007-07-11 17:01:13 +0000576/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
577/// no declarator (e.g. "struct foo;") is parsed.
578Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
579 // TODO: emit error on 'int;' or 'const enum foo;'.
580 // TODO: emit error on 'typedef int;'
581 // if (!DS.isMissingDeclaratorOk()) Diag(...);
582
Steve Naroff92199282007-11-17 21:37:36 +0000583 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000584}
585
Steve Naroffd0091aa2008-01-10 22:15:12 +0000586bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000587 // Get the type before calling CheckSingleAssignmentConstraints(), since
588 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000589 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000590
Chris Lattner5cf216b2008-01-04 18:04:52 +0000591 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
592 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
593 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000594}
595
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000596bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000597 const ArrayType *AT = Context.getAsArrayType(DeclT);
598
599 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000600 // C99 6.7.8p14. We have an array of character type with unknown size
601 // being initialized to a string literal.
602 llvm::APSInt ConstVal(32);
603 ConstVal = strLiteral->getByteLength() + 1;
604 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000605 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000606 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000607 } else {
608 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000609 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000610 // FIXME: Avoid truncation for 64-bit length strings.
611 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000612 Diag(strLiteral->getSourceRange().getBegin(),
613 diag::warn_initializer_string_for_char_array_too_long,
614 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000615 }
616 // Set type from "char *" to "constant array of char".
617 strLiteral->setType(DeclT);
618 // For now, we always return false (meaning success).
619 return false;
620}
621
622StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000623 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000624 if (AT && AT->getElementType()->isCharType()) {
625 return dyn_cast<StringLiteral>(Init);
626 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000627 return 0;
628}
629
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000630bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
631 SourceLocation InitLoc,
632 std::string InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000633 // C++ [dcl.init.ref]p1:
634 // A variable declared to be a T&, that is “reference to type T”
635 // (8.3.2), shall be initialized by an object, or function, of
636 // type T or by an object that can be converted into a T.
637 if (DeclType->isReferenceType())
638 return CheckReferenceInit(Init, DeclType);
639
Steve Naroffca107302008-01-21 23:53:58 +0000640 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
641 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000642 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000643 return Diag(InitLoc,
Steve Naroffca107302008-01-21 23:53:58 +0000644 diag::err_variable_object_no_init,
645 VAT->getSizeExpr()->getSourceRange());
646
Steve Naroff2fdc3742007-12-10 22:44:33 +0000647 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
648 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000649 // FIXME: Handle wide strings
650 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
651 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000652
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000653 // C++ [dcl.init]p14:
654 // -- If the destination type is a (possibly cv-qualified) class
655 // type:
656 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
657 QualType DeclTypeC = Context.getCanonicalType(DeclType);
658 QualType InitTypeC = Context.getCanonicalType(Init->getType());
659
660 // -- If the initialization is direct-initialization, or if it is
661 // copy-initialization where the cv-unqualified version of the
662 // source type is the same class as, or a derived class of, the
663 // class of the destination, constructors are considered.
664 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
665 IsDerivedFrom(InitTypeC, DeclTypeC)) {
666 CXXConstructorDecl *Constructor
667 = PerformInitializationByConstructor(DeclType, &Init, 1,
668 InitLoc, Init->getSourceRange(),
669 InitEntity, IK_Copy);
670 return Constructor == 0;
671 }
672
673 // -- Otherwise (i.e., for the remaining copy-initialization
674 // cases), user-defined conversion sequences that can
675 // convert from the source type to the destination type or
676 // (when a conversion function is used) to a derived class
677 // thereof are enumerated as described in 13.3.1.4, and the
678 // best one is chosen through overload resolution
679 // (13.3). If the conversion cannot be done or is
680 // ambiguous, the initialization is ill-formed. The
681 // function selected is called with the initializer
682 // expression as its argument; if the function is a
683 // constructor, the call initializes a temporary of the
684 // destination type.
685 // FIXME: We're pretending to do copy elision here; return to
686 // this when we have ASTs for such things.
687 if (PerformImplicitConversion(Init, DeclType))
688 return Diag(InitLoc,
689 diag::err_typecheck_convert_incompatible,
690 DeclType.getAsString(), InitEntity,
691 "initializing",
692 Init->getSourceRange());
693 else
694 return false;
695 }
696
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000697 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000698 if (DeclType->isArrayType())
699 return Diag(Init->getLocStart(),
700 diag::err_array_init_list_required,
701 Init->getSourceRange());
702
Steve Naroffd0091aa2008-01-10 22:15:12 +0000703 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000704 } else if (getLangOptions().CPlusPlus) {
705 // C++ [dcl.init]p14:
706 // [...] If the class is an aggregate (8.5.1), and the initializer
707 // is a brace-enclosed list, see 8.5.1.
708 //
709 // Note: 8.5.1 is handled below; here, we diagnose the case where
710 // we have an initializer list and a destination type that is not
711 // an aggregate.
712 // FIXME: In C++0x, this is yet another form of initialization.
713 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
714 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
715 if (!ClassDecl->isAggregate())
716 return Diag(InitLoc,
717 diag::err_init_non_aggr_init_list,
718 DeclType.getAsString(),
719 Init->getSourceRange());
720 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000721 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000722
Steve Naroff0cca7492008-05-01 22:18:59 +0000723 InitListChecker CheckInitList(this, InitList, DeclType);
724 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000725}
726
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000727Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000728Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000729 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000730 IdentifierInfo *II = D.getIdentifier();
731
Chris Lattnere80a59c2007-07-25 00:24:17 +0000732 // All of these full declarators require an identifier. If it doesn't have
733 // one, the ParsedFreeStandingDeclSpec action should be used.
734 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000735 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000736 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000737 D.getDeclSpec().getSourceRange(), D.getSourceRange());
738 return 0;
739 }
740
Chris Lattner31e05722007-08-26 06:24:45 +0000741 // The scope passed in may not be a decl scope. Zip up the scope tree until
742 // we find one that is.
743 while ((S->getFlags() & Scope::DeclScope) == 0)
744 S = S->getParent();
745
Reid Spencer5f016e22007-07-11 17:01:13 +0000746 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000747 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000748 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000749 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000750
751 // In C++, the previous declaration we find might be a tag type
752 // (class or enum). In this case, the new declaration will hide the
753 // tag type.
754 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
755 PrevDecl = 0;
756
Chris Lattner41af0932007-11-14 06:34:38 +0000757 QualType R = GetTypeForDeclarator(D, S);
758 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
759
Reid Spencer5f016e22007-07-11 17:01:13 +0000760 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000761 // Check that there are no default arguments (C++ only).
762 if (getLangOptions().CPlusPlus)
763 CheckExtraCXXDefaultArguments(D);
764
Chris Lattner41af0932007-11-14 06:34:38 +0000765 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000766 if (!NewTD) return 0;
767
768 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000769 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000770 // Merge the decl with the existing one if appropriate. If the decl is
771 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000772 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000773 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
774 if (NewTD == 0) return 0;
775 }
776 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000777 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000778 // C99 6.7.7p2: If a typedef name specifies a variably modified type
779 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000780 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
781 // FIXME: Diagnostic needs to be fixed.
782 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000783 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000784 }
785 }
Chris Lattner41af0932007-11-14 06:34:38 +0000786 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000787 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000788 switch (D.getDeclSpec().getStorageClassSpec()) {
789 default: assert(0 && "Unknown storage class!");
790 case DeclSpec::SCS_auto:
791 case DeclSpec::SCS_register:
792 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
793 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000794 InvalidDecl = true;
795 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000796 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
797 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
798 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000799 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000800 }
801
Chris Lattnera98e58d2008-03-15 21:24:04 +0000802 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000803 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000804 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
805
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000806 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000807 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000808 // This is a C++ constructor declaration.
809 assert(D.getContext() == Declarator::MemberContext &&
810 "Constructors can only be declared in a member context");
811
Douglas Gregor42a552f2008-11-05 20:51:48 +0000812 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000813
814 // Create the new declaration
815 NewFD = CXXConstructorDecl::Create(Context,
816 cast<CXXRecordDecl>(CurContext),
817 D.getIdentifierLoc(), II, R,
818 isExplicit, isInline,
819 /*isImplicitlyDeclared=*/false);
820
Douglas Gregor42a552f2008-11-05 20:51:48 +0000821 if (isInvalidDecl)
822 NewFD->setInvalidDecl();
823 } else if (D.getKind() == Declarator::DK_Destructor) {
824 // This is a C++ destructor declaration.
825 assert(D.getContext() == Declarator::MemberContext &&
826 "Destructor can only be declared in a member context");
827
828 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
829
830 NewFD = CXXDestructorDecl::Create(Context,
831 cast<CXXRecordDecl>(CurContext),
832 D.getIdentifierLoc(), II, R,
833 isInline,
834 /*isImplicitlyDeclared=*/false);
835
836 if (isInvalidDecl)
837 NewFD->setInvalidDecl();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000838 } else if (D.getContext() == Declarator::MemberContext) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000839 // This is a C++ method declaration.
840 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
841 D.getIdentifierLoc(), II, R,
842 (SC == FunctionDecl::Static), isInline,
843 LastDeclarator);
844 } else {
845 NewFD = FunctionDecl::Create(Context, CurContext,
846 D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000847 II, R, SC, isInline, LastDeclarator,
848 // FIXME: Move to DeclGroup...
849 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000850 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000851 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000852 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000853
Daniel Dunbara80f8742008-08-05 01:35:17 +0000854 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000855 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000856 // The parser guarantees this is a string.
857 StringLiteral *SE = cast<StringLiteral>(E);
858 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
859 SE->getByteLength())));
860 }
861
Chris Lattner04421082008-04-08 04:40:51 +0000862 // Copy the parameter declarations from the declarator D to
863 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000864 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000865 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
866
867 // Create Decl objects for each parameter, adding them to the
868 // FunctionDecl.
869 llvm::SmallVector<ParmVarDecl*, 16> Params;
870
871 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
872 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000873 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000874 // We let through "const void" here because Sema::GetTypeForDeclarator
875 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000876 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
877 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000878 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
879 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000880 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
881
Chris Lattnerdef026a2008-04-10 02:26:16 +0000882 // In C++, the empty parameter-type-list must be spelled "void"; a
883 // typedef of void is not permitted.
884 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000885 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000886 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
887 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000888 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000889 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
890 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
891 }
892
893 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +0000894 } else if (R->getAsTypedefType()) {
895 // When we're declaring a function with a typedef, as in the
896 // following example, we'll need to synthesize (unnamed)
897 // parameters for use in the declaration.
898 //
899 // @code
900 // typedef void fn(int);
901 // fn f;
902 // @endcode
903 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
904 if (!FT) {
905 // This is a typedef of a function with no prototype, so we
906 // don't need to do anything.
907 } else if ((FT->getNumArgs() == 0) ||
908 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
909 FT->getArgType(0)->isVoidType())) {
910 // This is a zero-argument function. We don't need to do anything.
911 } else {
912 // Synthesize a parameter for each argument type.
913 llvm::SmallVector<ParmVarDecl*, 16> Params;
914 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
915 ArgType != FT->arg_type_end(); ++ArgType) {
916 Params.push_back(ParmVarDecl::Create(Context, CurContext,
917 SourceLocation(), 0,
918 *ArgType, VarDecl::None,
919 0, 0));
920 }
921
922 NewFD->setParams(&Params[0], Params.size());
923 }
Chris Lattner04421082008-04-08 04:40:51 +0000924 }
925
Douglas Gregor42a552f2008-11-05 20:51:48 +0000926 // C++ constructors and destructors are handled by separate
927 // routines, since they don't require any declaration merging (C++
928 // [class.mfct]p2) and they aren't ever pushed into scope, because
929 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
930 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
931 return ActOnConstructorDeclarator(Constructor);
932 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
933 return ActOnDestructorDeclarator(Destructor);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000934
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +0000935 // Extra checking for C++ overloaded operators (C++ [over.oper]).
936 if (NewFD->isOverloadedOperator() &&
937 CheckOverloadedOperatorDeclaration(NewFD))
938 NewFD->setInvalidDecl();
939
Steve Naroffffce4d52008-01-09 23:34:55 +0000940 // Merge the decl with the existing one if appropriate. Since C functions
941 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000942 if (PrevDecl &&
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000943 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000944 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000945
946 // If C++, determine whether NewFD is an overload of PrevDecl or
947 // a declaration that requires merging. If it's an overload,
948 // there's no more work to do here; we'll just add the new
949 // function to the scope.
950 OverloadedFunctionDecl::function_iterator MatchedDecl;
951 if (!getLangOptions().CPlusPlus ||
952 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
953 Decl *OldDecl = PrevDecl;
954
955 // If PrevDecl was an overloaded function, extract the
956 // FunctionDecl that matched.
957 if (isa<OverloadedFunctionDecl>(PrevDecl))
958 OldDecl = *MatchedDecl;
959
960 // NewFD and PrevDecl represent declarations that need to be
961 // merged.
962 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
963
964 if (NewFD == 0) return 0;
965 if (Redeclaration) {
966 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
967
968 if (OldDecl == PrevDecl) {
969 // Remove the name binding for the previous
970 // declaration. We'll add the binding back later, but then
971 // it will refer to the new declaration (which will
972 // contain more information).
973 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
974 } else {
975 // We need to update the OverloadedFunctionDecl with the
976 // latest declaration of this function, so that name
977 // lookup will always refer to the latest declaration of
978 // this function.
979 *MatchedDecl = NewFD;
980
981 // Add the redeclaration to the current scope, since we'll
982 // be skipping PushOnScopeChains.
983 S->AddDecl(NewFD);
984
985 return NewFD;
986 }
987 }
Douglas Gregorf0097952008-04-21 02:02:58 +0000988 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000989 }
990 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000991
992 // In C++, check default arguments now that we have merged decls.
993 if (getLangOptions().CPlusPlus)
994 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000995 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000996 // Check that there are no default arguments (C++ only).
997 if (getLangOptions().CPlusPlus)
998 CheckExtraCXXDefaultArguments(D);
999
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001000 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001001 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1002 D.getIdentifier()->getName());
1003 InvalidDecl = true;
1004 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001005
1006 VarDecl *NewVD;
1007 VarDecl::StorageClass SC;
1008 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001009 default: assert(0 && "Unknown storage class!");
1010 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1011 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1012 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1013 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1014 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1015 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001016 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001017 if (D.getContext() == Declarator::MemberContext) {
1018 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1019 // This is a static data member for a C++ class.
1020 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1021 D.getIdentifierLoc(), II,
1022 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001023 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001024 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001025 if (S->getFnParent() == 0) {
1026 // C99 6.9p2: The storage-class specifiers auto and register shall not
1027 // appear in the declaration specifiers in an external declaration.
1028 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1029 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1030 R.getAsString());
1031 InvalidDecl = true;
1032 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001033 }
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001034 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001035 II, R, SC, LastDeclarator,
1036 // FIXME: Move to DeclGroup...
1037 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001038 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001039 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001040 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001041 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001042
Daniel Dunbara735ad82008-08-06 00:03:29 +00001043 // Handle GNU asm-label extension (encoded as an attribute).
1044 if (Expr *E = (Expr*) D.getAsmLabel()) {
1045 // The parser guarantees this is a string.
1046 StringLiteral *SE = cast<StringLiteral>(E);
1047 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1048 SE->getByteLength())));
1049 }
1050
Nate Begemanc8e89a82008-03-14 18:07:10 +00001051 // Emit an error if an address space was applied to decl with local storage.
1052 // This includes arrays of objects with address space qualifiers, but not
1053 // automatic variables that point to other address spaces.
1054 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001055 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1056 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1057 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001058 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001059 // Merge the decl with the existing one if appropriate. If the decl is
1060 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001061 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001062 NewVD = MergeVarDecl(NewVD, PrevDecl);
1063 if (NewVD == 0) return 0;
1064 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001065 New = NewVD;
1066 }
1067
1068 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001069 if (II)
1070 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001071 // If any semantic error occurred, mark the decl as invalid.
1072 if (D.getInvalidType() || InvalidDecl)
1073 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001074
1075 return New;
1076}
1077
Steve Naroff6594a702008-10-27 11:34:16 +00001078void Sema::InitializerElementNotConstant(const Expr *Init) {
1079 Diag(Init->getExprLoc(),
1080 diag::err_init_element_not_constant, Init->getSourceRange());
1081}
1082
Eli Friedmanc594b322008-05-20 13:48:25 +00001083bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1084 switch (Init->getStmtClass()) {
1085 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001086 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001087 return true;
1088 case Expr::ParenExprClass: {
1089 const ParenExpr* PE = cast<ParenExpr>(Init);
1090 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1091 }
1092 case Expr::CompoundLiteralExprClass:
1093 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1094 case Expr::DeclRefExprClass: {
1095 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001096 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1097 if (VD->hasGlobalStorage())
1098 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001099 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001100 return true;
1101 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001102 if (isa<FunctionDecl>(D))
1103 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001104 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001105 return true;
1106 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001107 case Expr::MemberExprClass: {
1108 const MemberExpr *M = cast<MemberExpr>(Init);
1109 if (M->isArrow())
1110 return CheckAddressConstantExpression(M->getBase());
1111 return CheckAddressConstantExpressionLValue(M->getBase());
1112 }
1113 case Expr::ArraySubscriptExprClass: {
1114 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1115 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1116 return CheckAddressConstantExpression(ASE->getBase()) ||
1117 CheckArithmeticConstantExpression(ASE->getIdx());
1118 }
1119 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001120 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001121 return false;
1122 case Expr::UnaryOperatorClass: {
1123 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1124
1125 // C99 6.6p9
1126 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001127 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001128
Steve Naroff6594a702008-10-27 11:34:16 +00001129 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001130 return true;
1131 }
1132 }
1133}
1134
1135bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1136 switch (Init->getStmtClass()) {
1137 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001138 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001139 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001140 case Expr::ParenExprClass:
1141 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001142 case Expr::StringLiteralClass:
1143 case Expr::ObjCStringLiteralClass:
1144 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001145 case Expr::CallExprClass:
1146 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1147 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1148 Builtin::BI__builtin___CFStringMakeConstantString)
1149 return false;
1150
Steve Naroff6594a702008-10-27 11:34:16 +00001151 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001152 return true;
1153
Eli Friedmanc594b322008-05-20 13:48:25 +00001154 case Expr::UnaryOperatorClass: {
1155 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1156
1157 // C99 6.6p9
1158 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1159 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1160
1161 if (Exp->getOpcode() == UnaryOperator::Extension)
1162 return CheckAddressConstantExpression(Exp->getSubExpr());
1163
Steve Naroff6594a702008-10-27 11:34:16 +00001164 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001165 return true;
1166 }
1167 case Expr::BinaryOperatorClass: {
1168 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1169 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1170
1171 Expr *PExp = Exp->getLHS();
1172 Expr *IExp = Exp->getRHS();
1173 if (IExp->getType()->isPointerType())
1174 std::swap(PExp, IExp);
1175
1176 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1177 return CheckAddressConstantExpression(PExp) ||
1178 CheckArithmeticConstantExpression(IExp);
1179 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001180 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001181 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001182 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001183 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1184 // Check for implicit promotion
1185 if (SubExpr->getType()->isFunctionType() ||
1186 SubExpr->getType()->isArrayType())
1187 return CheckAddressConstantExpressionLValue(SubExpr);
1188 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001189
1190 // Check for pointer->pointer cast
1191 if (SubExpr->getType()->isPointerType())
1192 return CheckAddressConstantExpression(SubExpr);
1193
Eli Friedmanc3f07642008-08-25 20:46:57 +00001194 if (SubExpr->getType()->isIntegralType()) {
1195 // Check for the special-case of a pointer->int->pointer cast;
1196 // this isn't standard, but some code requires it. See
1197 // PR2720 for an example.
1198 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1199 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1200 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1201 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1202 if (IntWidth >= PointerWidth) {
1203 return CheckAddressConstantExpression(SubCast->getSubExpr());
1204 }
1205 }
1206 }
1207 }
1208 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001209 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001210 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001211
Steve Naroff6594a702008-10-27 11:34:16 +00001212 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001213 return true;
1214 }
1215 case Expr::ConditionalOperatorClass: {
1216 // FIXME: Should we pedwarn here?
1217 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1218 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001219 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001220 return true;
1221 }
1222 if (CheckArithmeticConstantExpression(Exp->getCond()))
1223 return true;
1224 if (Exp->getLHS() &&
1225 CheckAddressConstantExpression(Exp->getLHS()))
1226 return true;
1227 return CheckAddressConstantExpression(Exp->getRHS());
1228 }
1229 case Expr::AddrLabelExprClass:
1230 return false;
1231 }
1232}
1233
Eli Friedman4caf0552008-06-09 05:05:07 +00001234static const Expr* FindExpressionBaseAddress(const Expr* E);
1235
1236static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1237 switch (E->getStmtClass()) {
1238 default:
1239 return E;
1240 case Expr::ParenExprClass: {
1241 const ParenExpr* PE = cast<ParenExpr>(E);
1242 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1243 }
1244 case Expr::MemberExprClass: {
1245 const MemberExpr *M = cast<MemberExpr>(E);
1246 if (M->isArrow())
1247 return FindExpressionBaseAddress(M->getBase());
1248 return FindExpressionBaseAddressLValue(M->getBase());
1249 }
1250 case Expr::ArraySubscriptExprClass: {
1251 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1252 return FindExpressionBaseAddress(ASE->getBase());
1253 }
1254 case Expr::UnaryOperatorClass: {
1255 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1256
1257 if (Exp->getOpcode() == UnaryOperator::Deref)
1258 return FindExpressionBaseAddress(Exp->getSubExpr());
1259
1260 return E;
1261 }
1262 }
1263}
1264
1265static const Expr* FindExpressionBaseAddress(const Expr* E) {
1266 switch (E->getStmtClass()) {
1267 default:
1268 return E;
1269 case Expr::ParenExprClass: {
1270 const ParenExpr* PE = cast<ParenExpr>(E);
1271 return FindExpressionBaseAddress(PE->getSubExpr());
1272 }
1273 case Expr::UnaryOperatorClass: {
1274 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1275
1276 // C99 6.6p9
1277 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1278 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1279
1280 if (Exp->getOpcode() == UnaryOperator::Extension)
1281 return FindExpressionBaseAddress(Exp->getSubExpr());
1282
1283 return E;
1284 }
1285 case Expr::BinaryOperatorClass: {
1286 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1287
1288 Expr *PExp = Exp->getLHS();
1289 Expr *IExp = Exp->getRHS();
1290 if (IExp->getType()->isPointerType())
1291 std::swap(PExp, IExp);
1292
1293 return FindExpressionBaseAddress(PExp);
1294 }
1295 case Expr::ImplicitCastExprClass: {
1296 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1297
1298 // Check for implicit promotion
1299 if (SubExpr->getType()->isFunctionType() ||
1300 SubExpr->getType()->isArrayType())
1301 return FindExpressionBaseAddressLValue(SubExpr);
1302
1303 // Check for pointer->pointer cast
1304 if (SubExpr->getType()->isPointerType())
1305 return FindExpressionBaseAddress(SubExpr);
1306
1307 // We assume that we have an arithmetic expression here;
1308 // if we don't, we'll figure it out later
1309 return 0;
1310 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001311 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001312 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1313
1314 // Check for pointer->pointer cast
1315 if (SubExpr->getType()->isPointerType())
1316 return FindExpressionBaseAddress(SubExpr);
1317
1318 // We assume that we have an arithmetic expression here;
1319 // if we don't, we'll figure it out later
1320 return 0;
1321 }
1322 }
1323}
1324
Eli Friedmanc594b322008-05-20 13:48:25 +00001325bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1326 switch (Init->getStmtClass()) {
1327 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001328 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001329 return true;
1330 case Expr::ParenExprClass: {
1331 const ParenExpr* PE = cast<ParenExpr>(Init);
1332 return CheckArithmeticConstantExpression(PE->getSubExpr());
1333 }
1334 case Expr::FloatingLiteralClass:
1335 case Expr::IntegerLiteralClass:
1336 case Expr::CharacterLiteralClass:
1337 case Expr::ImaginaryLiteralClass:
1338 case Expr::TypesCompatibleExprClass:
1339 case Expr::CXXBoolLiteralExprClass:
1340 return false;
1341 case Expr::CallExprClass: {
1342 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001343
1344 // Allow any constant foldable calls to builtins.
1345 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001346 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001347
Steve Naroff6594a702008-10-27 11:34:16 +00001348 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001349 return true;
1350 }
1351 case Expr::DeclRefExprClass: {
1352 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1353 if (isa<EnumConstantDecl>(D))
1354 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001355 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001356 return true;
1357 }
1358 case Expr::CompoundLiteralExprClass:
1359 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1360 // but vectors are allowed to be magic.
1361 if (Init->getType()->isVectorType())
1362 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001363 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001364 return true;
1365 case Expr::UnaryOperatorClass: {
1366 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1367
1368 switch (Exp->getOpcode()) {
1369 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1370 // See C99 6.6p3.
1371 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001372 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001373 return true;
1374 case UnaryOperator::SizeOf:
1375 case UnaryOperator::AlignOf:
1376 case UnaryOperator::OffsetOf:
1377 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1378 // See C99 6.5.3.4p2 and 6.6p3.
1379 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1380 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001381 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001382 return true;
1383 case UnaryOperator::Extension:
1384 case UnaryOperator::LNot:
1385 case UnaryOperator::Plus:
1386 case UnaryOperator::Minus:
1387 case UnaryOperator::Not:
1388 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1389 }
1390 }
1391 case Expr::SizeOfAlignOfTypeExprClass: {
1392 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1393 // Special check for void types, which are allowed as an extension
1394 if (Exp->getArgumentType()->isVoidType())
1395 return false;
1396 // alignof always evaluates to a constant.
1397 // FIXME: is sizeof(int[3.0]) a constant expression?
1398 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001399 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001400 return true;
1401 }
1402 return false;
1403 }
1404 case Expr::BinaryOperatorClass: {
1405 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1406
1407 if (Exp->getLHS()->getType()->isArithmeticType() &&
1408 Exp->getRHS()->getType()->isArithmeticType()) {
1409 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1410 CheckArithmeticConstantExpression(Exp->getRHS());
1411 }
1412
Eli Friedman4caf0552008-06-09 05:05:07 +00001413 if (Exp->getLHS()->getType()->isPointerType() &&
1414 Exp->getRHS()->getType()->isPointerType()) {
1415 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1416 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1417
1418 // Only allow a null (constant integer) base; we could
1419 // allow some additional cases if necessary, but this
1420 // is sufficient to cover offsetof-like constructs.
1421 if (!LHSBase && !RHSBase) {
1422 return CheckAddressConstantExpression(Exp->getLHS()) ||
1423 CheckAddressConstantExpression(Exp->getRHS());
1424 }
1425 }
1426
Steve Naroff6594a702008-10-27 11:34:16 +00001427 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001428 return true;
1429 }
1430 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001431 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001432 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001433 if (SubExpr->getType()->isArithmeticType())
1434 return CheckArithmeticConstantExpression(SubExpr);
1435
Eli Friedmanb529d832008-09-02 09:37:00 +00001436 if (SubExpr->getType()->isPointerType()) {
1437 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1438 // If the pointer has a null base, this is an offsetof-like construct
1439 if (!Base)
1440 return CheckAddressConstantExpression(SubExpr);
1441 }
1442
Steve Naroff6594a702008-10-27 11:34:16 +00001443 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001444 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001445 }
1446 case Expr::ConditionalOperatorClass: {
1447 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001448
1449 // If GNU extensions are disabled, we require all operands to be arithmetic
1450 // constant expressions.
1451 if (getLangOptions().NoExtensions) {
1452 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1453 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1454 CheckArithmeticConstantExpression(Exp->getRHS());
1455 }
1456
1457 // Otherwise, we have to emulate some of the behavior of fold here.
1458 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1459 // because it can constant fold things away. To retain compatibility with
1460 // GCC code, we see if we can fold the condition to a constant (which we
1461 // should always be able to do in theory). If so, we only require the
1462 // specified arm of the conditional to be a constant. This is a horrible
1463 // hack, but is require by real world code that uses __builtin_constant_p.
1464 APValue Val;
1465 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1466 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1467 // won't be able to either. Use it to emit the diagnostic though.
1468 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1469 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1470 return Res;
1471 }
1472
1473 // Verify that the side following the condition is also a constant.
1474 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1475 if (Val.getInt() == 0)
1476 std::swap(TrueSide, FalseSide);
1477
1478 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001479 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001480
1481 // Okay, the evaluated side evaluates to a constant, so we accept this.
1482 // Check to see if the other side is obviously not a constant. If so,
1483 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001484 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001485 Diag(Init->getExprLoc(),
1486 diag::ext_typecheck_expression_not_constant_but_accepted,
1487 FalseSide->getSourceRange());
1488 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001489 }
1490 }
1491}
1492
1493bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001494 Init = Init->IgnoreParens();
1495
Eli Friedmanc594b322008-05-20 13:48:25 +00001496 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1497 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1498 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1499
Nuno Lopes9a979c32008-07-07 16:46:50 +00001500 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1501 return CheckForConstantInitializer(e->getInitializer(), DclT);
1502
Eli Friedmanc594b322008-05-20 13:48:25 +00001503 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1504 unsigned numInits = Exp->getNumInits();
1505 for (unsigned i = 0; i < numInits; i++) {
1506 // FIXME: Need to get the type of the declaration for C++,
1507 // because it could be a reference?
1508 if (CheckForConstantInitializer(Exp->getInit(i),
1509 Exp->getInit(i)->getType()))
1510 return true;
1511 }
1512 return false;
1513 }
1514
1515 if (Init->isNullPointerConstant(Context))
1516 return false;
1517 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001518 QualType InitTy = Context.getCanonicalType(Init->getType())
1519 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001520 if (InitTy == Context.BoolTy) {
1521 // Special handling for pointers implicitly cast to bool;
1522 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1523 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1524 Expr* SubE = ICE->getSubExpr();
1525 if (SubE->getType()->isPointerType() ||
1526 SubE->getType()->isArrayType() ||
1527 SubE->getType()->isFunctionType()) {
1528 return CheckAddressConstantExpression(Init);
1529 }
1530 }
1531 } else if (InitTy->isIntegralType()) {
1532 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001533 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001534 SubE = CE->getSubExpr();
1535 // Special check for pointer cast to int; we allow as an extension
1536 // an address constant cast to an integer if the integer
1537 // is of an appropriate width (this sort of code is apparently used
1538 // in some places).
1539 // FIXME: Add pedwarn?
1540 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1541 if (SubE && (SubE->getType()->isPointerType() ||
1542 SubE->getType()->isArrayType() ||
1543 SubE->getType()->isFunctionType())) {
1544 unsigned IntWidth = Context.getTypeSize(Init->getType());
1545 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1546 if (IntWidth >= PointerWidth)
1547 return CheckAddressConstantExpression(Init);
1548 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001549 }
1550
1551 return CheckArithmeticConstantExpression(Init);
1552 }
1553
1554 if (Init->getType()->isPointerType())
1555 return CheckAddressConstantExpression(Init);
1556
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001557 // An array type at the top level that isn't an init-list must
1558 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001559 if (Init->getType()->isArrayType())
1560 return false;
1561
Nuno Lopes73419bf2008-09-01 18:42:41 +00001562 if (Init->getType()->isFunctionType())
1563 return false;
1564
Steve Naroff8af6a452008-10-02 17:12:56 +00001565 // Allow block exprs at top level.
1566 if (Init->getType()->isBlockPointerType())
1567 return false;
1568
Steve Naroff6594a702008-10-27 11:34:16 +00001569 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001570 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001571}
1572
Steve Naroffbb204692007-09-12 14:07:44 +00001573void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001574 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001575 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001576 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001577
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001578 // If there is no declaration, there was an error parsing it. Just ignore
1579 // the initializer.
1580 if (RealDecl == 0) {
1581 delete Init;
1582 return;
1583 }
Steve Naroffbb204692007-09-12 14:07:44 +00001584
Steve Naroff410e3e22007-09-12 20:13:48 +00001585 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1586 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001587 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1588 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001589 RealDecl->setInvalidDecl();
1590 return;
1591 }
Steve Naroffbb204692007-09-12 14:07:44 +00001592 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001593 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001594 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001595 if (VDecl->isBlockVarDecl()) {
1596 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001597 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001598 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001599 VDecl->setInvalidDecl();
1600 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001601 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1602 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001603 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001604
1605 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1606 if (!getLangOptions().CPlusPlus) {
1607 if (SC == VarDecl::Static) // C99 6.7.8p4.
1608 CheckForConstantInitializer(Init, DclT);
1609 }
Steve Naroffbb204692007-09-12 14:07:44 +00001610 }
Steve Naroff248a7532008-04-15 22:42:06 +00001611 } else if (VDecl->isFileVarDecl()) {
1612 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001613 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001614 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001615 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1616 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001617 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001618
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001619 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1620 if (!getLangOptions().CPlusPlus) {
1621 // C99 6.7.8p4. All file scoped initializers need to be constant.
1622 CheckForConstantInitializer(Init, DclT);
1623 }
Steve Naroffbb204692007-09-12 14:07:44 +00001624 }
1625 // If the type changed, it means we had an incomplete type that was
1626 // completed by the initializer. For example:
1627 // int ary[] = { 1, 3, 5 };
1628 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001629 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001630 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001631 Init->setType(DclT);
1632 }
Steve Naroffbb204692007-09-12 14:07:44 +00001633
1634 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001635 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001636 return;
1637}
1638
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001639void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1640 Decl *RealDecl = static_cast<Decl *>(dcl);
1641
1642 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1643 QualType Type = Var->getType();
1644 // C++ [dcl.init.ref]p3:
1645 // The initializer can be omitted for a reference only in a
1646 // parameter declaration (8.3.5), in the declaration of a
1647 // function return type, in the declaration of a class member
1648 // within its class declaration (9.2), and where the extern
1649 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001650 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001651 Diag(Var->getLocation(),
1652 diag::err_reference_var_requires_init,
1653 Var->getName(),
1654 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor18fe5682008-11-03 20:45:27 +00001655 Var->setInvalidDecl();
1656 return;
1657 }
1658
1659 // C++ [dcl.init]p9:
1660 //
1661 // If no initializer is specified for an object, and the object
1662 // is of (possibly cv-qualified) non-POD class type (or array
1663 // thereof), the object shall be default-initialized; if the
1664 // object is of const-qualified type, the underlying class type
1665 // shall have a user-declared default constructor.
1666 if (getLangOptions().CPlusPlus) {
1667 QualType InitType = Type;
1668 if (const ArrayType *Array = Context.getAsArrayType(Type))
1669 InitType = Array->getElementType();
1670 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001671 const CXXConstructorDecl *Constructor
1672 = PerformInitializationByConstructor(InitType, 0, 0,
1673 Var->getLocation(),
1674 SourceRange(Var->getLocation(),
1675 Var->getLocation()),
1676 Var->getName(),
1677 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001678 if (!Constructor)
1679 Var->setInvalidDecl();
1680 }
1681 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001682
Douglas Gregor818ce482008-10-29 13:50:18 +00001683#if 0
1684 // FIXME: Temporarily disabled because we are not properly parsing
1685 // linkage specifications on declarations, e.g.,
1686 //
1687 // extern "C" const CGPoint CGPointerZero;
1688 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001689 // C++ [dcl.init]p9:
1690 //
1691 // If no initializer is specified for an object, and the
1692 // object is of (possibly cv-qualified) non-POD class type (or
1693 // array thereof), the object shall be default-initialized; if
1694 // the object is of const-qualified type, the underlying class
1695 // type shall have a user-declared default
1696 // constructor. Otherwise, if no initializer is specified for
1697 // an object, the object and its subobjects, if any, have an
1698 // indeterminate initial value; if the object or any of its
1699 // subobjects are of const-qualified type, the program is
1700 // ill-formed.
1701 //
1702 // This isn't technically an error in C, so we don't diagnose it.
1703 //
1704 // FIXME: Actually perform the POD/user-defined default
1705 // constructor check.
1706 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001707 Context.getCanonicalType(Type).isConstQualified() &&
1708 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001709 Diag(Var->getLocation(),
1710 diag::err_const_var_requires_init,
1711 Var->getName(),
1712 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor818ce482008-10-29 13:50:18 +00001713#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001714 }
1715}
1716
Reid Spencer5f016e22007-07-11 17:01:13 +00001717/// The declarators are chained together backwards, reverse the list.
1718Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1719 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001720 Decl *GroupDecl = static_cast<Decl*>(group);
1721 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001722 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001723
1724 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1725 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001726 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001728 else { // reverse the list.
1729 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001730 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001731 Group->setNextDeclarator(NewGroup);
1732 NewGroup = Group;
1733 Group = Next;
1734 }
1735 }
1736 // Perform semantic analysis that depends on having fully processed both
1737 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001738 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001739 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1740 if (!IDecl)
1741 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001742 QualType T = IDecl->getType();
1743
1744 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1745 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001746 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1747 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001748 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001749 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1750 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001751 }
1752 }
1753 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1754 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001755 if (IDecl->isBlockVarDecl() &&
1756 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001757 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001758 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1759 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001760 IDecl->setInvalidDecl();
1761 }
1762 }
1763 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1764 // object that has file scope without an initializer, and without a
1765 // storage-class specifier or with the storage-class specifier "static",
1766 // constitutes a tentative definition. Note: A tentative definition with
1767 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001768 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001769 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001770 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1771 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001772 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001773 // C99 6.9.2p3: If the declaration of an identifier for an object is
1774 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1775 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001776 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1777 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001778 IDecl->setInvalidDecl();
1779 }
1780 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001781 if (IDecl->isFileVarDecl())
1782 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001783 }
1784 return NewGroup;
1785}
Steve Naroffe1223f72007-08-28 03:03:08 +00001786
Chris Lattner04421082008-04-08 04:40:51 +00001787/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1788/// to introduce parameters into function prototype scope.
1789Sema::DeclTy *
1790Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001791 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001792
1793 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001794 VarDecl::StorageClass StorageClass = VarDecl::None;
1795 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1796 StorageClass = VarDecl::Register;
1797 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001798 Diag(DS.getStorageClassSpecLoc(),
1799 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001800 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001801 }
1802 if (DS.isThreadSpecified()) {
1803 Diag(DS.getThreadSpecLoc(),
1804 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001805 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001806 }
1807
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001808 // Check that there are no default arguments inside the type of this
1809 // parameter (C++ only).
1810 if (getLangOptions().CPlusPlus)
1811 CheckExtraCXXDefaultArguments(D);
1812
Chris Lattner04421082008-04-08 04:40:51 +00001813 // In this context, we *do not* check D.getInvalidType(). If the declarator
1814 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1815 // though it will not reflect the user specified type.
1816 QualType parmDeclType = GetTypeForDeclarator(D, S);
1817
1818 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1819
Reid Spencer5f016e22007-07-11 17:01:13 +00001820 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1821 // Can this happen for params? We already checked that they don't conflict
1822 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001823 IdentifierInfo *II = D.getIdentifier();
1824 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1825 if (S->isDeclScope(PrevDecl)) {
1826 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1827 dyn_cast<NamedDecl>(PrevDecl)->getName());
1828
1829 // Recover by removing the name
1830 II = 0;
1831 D.SetIdentifier(0, D.getIdentifierLoc());
1832 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001833 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001834
1835 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1836 // Doing the promotion here has a win and a loss. The win is the type for
1837 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1838 // code generator). The loss is the orginal type isn't preserved. For example:
1839 //
1840 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1841 // int blockvardecl[5];
1842 // sizeof(parmvardecl); // size == 4
1843 // sizeof(blockvardecl); // size == 20
1844 // }
1845 //
1846 // For expressions, all implicit conversions are captured using the
1847 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1848 //
1849 // FIXME: If a source translation tool needs to see the original type, then
1850 // we need to consider storing both types (in ParmVarDecl)...
1851 //
Chris Lattnere6327742008-04-02 05:18:44 +00001852 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001853 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001854 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001855 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001856 parmDeclType = Context.getPointerType(parmDeclType);
1857
Chris Lattner04421082008-04-08 04:40:51 +00001858 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1859 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001860 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001861 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001862
Chris Lattner04421082008-04-08 04:40:51 +00001863 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001864 New->setInvalidDecl();
1865
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001866 if (II)
1867 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001868
Chris Lattner3ff30c82008-06-29 00:02:00 +00001869 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001870 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001871
Reid Spencer5f016e22007-07-11 17:01:13 +00001872}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001873
Chris Lattnerb652cea2007-10-09 17:14:05 +00001874Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001875 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001876 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1877 "Not a function declarator!");
1878 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001879
Reid Spencer5f016e22007-07-11 17:01:13 +00001880 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1881 // for a K&R function.
1882 if (!FTI.hasPrototype) {
1883 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001884 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1886 FTI.ArgInfo[i].Ident->getName());
1887 // Implicitly declare the argument as type 'int' for lack of a better
1888 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001889 DeclSpec DS;
1890 const char* PrevSpec; // unused
1891 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1892 PrevSpec);
1893 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1894 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1895 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001896 }
1897 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001898 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001899 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001900 }
1901
1902 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001903
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001904 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001905 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001906}
1907
1908Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1909 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001910 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00001911
1912 // See if this is a redefinition.
1913 const FunctionDecl *Definition;
1914 if (FD->getBody(Definition)) {
1915 Diag(FD->getLocation(), diag::err_redefinition,
1916 FD->getName());
1917 Diag(Definition->getLocation(), diag::err_previous_definition);
1918 }
1919
Chris Lattnerb048c982008-04-06 04:47:34 +00001920 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001921
1922 // Check the validity of our function parameters
1923 CheckParmsForFunctionDef(FD);
1924
1925 // Introduce our parameters into the function scope
1926 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1927 ParmVarDecl *Param = FD->getParamDecl(p);
1928 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001929 if (Param->getIdentifier())
1930 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001931 }
Chris Lattner04421082008-04-08 04:40:51 +00001932
Reid Spencer5f016e22007-07-11 17:01:13 +00001933 return FD;
1934}
1935
Steve Naroffd6d054d2007-11-11 23:20:51 +00001936Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1937 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001938 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001939 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001940 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001941 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001942 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001943 } else
1944 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001945 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001946 // Verify and clean out per-function state.
1947
1948 // Check goto/label use.
1949 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1950 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1951 // Verify that we have no forward references left. If so, there was a goto
1952 // or address of a label taken, but no definition of it. Label fwd
1953 // definitions are indicated with a null substmt.
1954 if (I->second->getSubStmt() == 0) {
1955 LabelStmt *L = I->second;
1956 // Emit error.
1957 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1958
1959 // At this point, we have gotos that use the bogus label. Stitch it into
1960 // the function body so that they aren't leaked and that the AST is well
1961 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001962 if (Body) {
1963 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1964 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1965 } else {
1966 // The whole function wasn't parsed correctly, just delete this.
1967 delete L;
1968 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001969 }
1970 }
1971 LabelMap.clear();
1972
Steve Naroffd6d054d2007-11-11 23:20:51 +00001973 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001974}
1975
Reid Spencer5f016e22007-07-11 17:01:13 +00001976/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1977/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001978ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1979 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001980 // Extension in C99. Legal in C90, but warn about it.
1981 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001982 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001983 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001984 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1985
1986 // FIXME: handle stuff like:
1987 // void foo() { extern float X(); }
1988 // void bar() { X(); } <-- implicit decl for X in another scope.
1989
1990 // Set a Declarator for the implicit definition: int foo();
1991 const char *Dummy;
1992 DeclSpec DS;
1993 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1994 Error = Error; // Silence warning.
1995 assert(!Error && "Error setting up implicit decl!");
1996 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00001997 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00001998 D.SetIdentifier(&II, Loc);
1999
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002000 // Insert this function into translation-unit scope.
2001
2002 DeclContext *PrevDC = CurContext;
2003 CurContext = Context.getTranslationUnitDecl();
2004
Steve Naroffe2ef8152008-04-04 14:32:09 +00002005 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002006 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002007 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002008
2009 CurContext = PrevDC;
2010
Steve Naroffe2ef8152008-04-04 14:32:09 +00002011 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002012}
2013
2014
Chris Lattner41af0932007-11-14 06:34:38 +00002015TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002016 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002017 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002018 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002019
2020 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002021 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2022 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002023 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002024 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002025 if (D.getInvalidType())
2026 NewTD->setInvalidDecl();
2027 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002028}
2029
Steve Naroff08d92e42007-09-15 18:49:24 +00002030/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002031/// former case, Name will be non-null. In the later case, Name will be null.
2032/// TagType indicates what kind of tag this is. TK indicates whether this is a
2033/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002034Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 SourceLocation KWLoc, IdentifierInfo *Name,
2036 SourceLocation NameLoc, AttributeList *Attr) {
2037 // If this is a use of an existing tag, it must have a name.
2038 assert((Name != 0 || TK == TK_Definition) &&
2039 "Nameless record must be a definition!");
2040
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002041 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002042 switch (TagType) {
2043 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002044 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2045 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2046 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2047 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002048 }
2049
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002050 // Two code paths: a new one for structs/unions/classes where we create
2051 // separate decls for forward declarations, and an old (eventually to
2052 // be removed) code path for enums.
2053 if (Kind != TagDecl::TK_enum)
2054 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
2055
Reid Spencer5f016e22007-07-11 17:01:13 +00002056 // If this is a named struct, check to see if there was a previous forward
2057 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002058 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002059 ScopedDecl *PrevDecl =
2060 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
2061
2062 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002063 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2064 "unexpected Decl type");
2065 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002066 // If this is a use of a previous tag, or if the tag is already declared
2067 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002068 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002069 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002070 // Make sure that this wasn't declared as an enum and now used as a
2071 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002072 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002073 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2074 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002075 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002076 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002077 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002078 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002079 // If this is a use or a forward declaration, we're good.
2080 if (TK != TK_Definition)
2081 return PrevDecl;
2082
2083 // Diagnose attempts to redefine a tag.
2084 if (PrevTagDecl->isDefinition()) {
2085 Diag(NameLoc, diag::err_redefinition, Name->getName());
2086 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2087 // If this is a redefinition, recover by making this struct be
2088 // anonymous, which will make any later references get the previous
2089 // definition.
2090 Name = 0;
2091 } else {
2092 // Okay, this is definition of a previously declared or referenced
2093 // tag. Move the location of the decl to be the definition site.
2094 PrevDecl->setLocation(NameLoc);
2095 return PrevDecl;
2096 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002097 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002099 // If we get here, this is a definition of a new struct type in a nested
2100 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2101 // type.
2102 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002103 // PrevDecl is a namespace.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002104 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002105 // The tag name clashes with a namespace name, issue an error and
2106 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002107 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2108 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2109 Name = 0;
2110 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002111 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002112 }
2113
2114 // If there is an identifier, use the location of the identifier as the
2115 // location of the decl, otherwise use the location of the struct/union
2116 // keyword.
2117 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2118
2119 // Otherwise, if this is the first time we've seen this tag, create the decl.
2120 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002121 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002122 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2123 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002124 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002125 // If this is an undefined enum, warn.
2126 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002127 } else {
2128 // struct/union/class
2129
Reid Spencer5f016e22007-07-11 17:01:13 +00002130 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2131 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002132 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002133 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenekdf042e62008-09-05 01:34:33 +00002134 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002135 else
Ted Kremenekdf042e62008-09-05 01:34:33 +00002136 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002137 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002138
2139 // If this has an identifier, add it to the scope stack.
2140 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002141 // The scope passed in may not be a decl scope. Zip up the scope tree until
2142 // we find one that is.
2143 while ((S->getFlags() & Scope::DeclScope) == 0)
2144 S = S->getParent();
2145
2146 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002147 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002148 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002149
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002150 if (Attr)
2151 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002152 return New;
2153}
2154
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002155/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2156/// the logic for enums, we create separate decls for forward declarations.
2157/// This is called by ActOnTag, but eventually will replace its logic.
2158Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
2159 SourceLocation KWLoc, IdentifierInfo *Name,
2160 SourceLocation NameLoc, AttributeList *Attr) {
2161
2162 // If this is a named struct, check to see if there was a previous forward
2163 // declaration or definition.
2164 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2165 ScopedDecl *PrevDecl =
2166 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
2167
2168 if (PrevDecl) {
2169 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2170 "unexpected Decl type");
2171
2172 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2173 // If this is a use of a previous tag, or if the tag is already declared
2174 // in the same scope (so that the definition/declaration completes or
2175 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002176 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002177 // Make sure that this wasn't declared as an enum and now used as a
2178 // struct or something similar.
2179 if (PrevTagDecl->getTagKind() != Kind) {
2180 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2181 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2182 // Recover by making this an anonymous redefinition.
2183 Name = 0;
2184 PrevDecl = 0;
2185 } else {
2186 // If this is a use, return the original decl.
2187
2188 // FIXME: In the future, return a variant or some other clue
2189 // for the consumer of this Decl to know it doesn't own it.
2190 // For our current ASTs this shouldn't be a problem, but will
2191 // need to be changed with DeclGroups.
2192 if (TK == TK_Reference)
2193 return PrevDecl;
2194
2195 // The new decl is a definition?
2196 if (TK == TK_Definition) {
2197 // Diagnose attempts to redefine a tag.
2198 if (RecordDecl* DefRecord =
2199 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2200 Diag(NameLoc, diag::err_redefinition, Name->getName());
2201 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2202 // If this is a redefinition, recover by making this struct be
2203 // anonymous, which will make any later references get the previous
2204 // definition.
2205 Name = 0;
2206 PrevDecl = 0;
2207 }
2208 // Okay, this is definition of a previously declared or referenced
2209 // tag. We're going to create a new Decl.
2210 }
2211 }
2212 // If we get here we have (another) forward declaration. Just create
2213 // a new decl.
2214 }
2215 else {
2216 // If we get here, this is a definition of a new struct type in a nested
2217 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2218 // new decl/type. We set PrevDecl to NULL so that the Records
2219 // have distinct types.
2220 PrevDecl = 0;
2221 }
2222 } else {
2223 // PrevDecl is a namespace.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002224 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002225 // The tag name clashes with a namespace name, issue an error and
2226 // recover by making this tag be anonymous.
2227 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2228 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2229 Name = 0;
2230 }
2231 }
2232 }
2233
2234 // If there is an identifier, use the location of the identifier as the
2235 // location of the decl, otherwise use the location of the struct/union
2236 // keyword.
2237 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2238
2239 // Otherwise, if this is the first time we've seen this tag, create the decl.
2240 TagDecl *New;
2241
2242 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2243 // struct X { int A; } D; D should chain to X.
2244 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002245 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002246 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2247 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2248 else
2249 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2250 dyn_cast_or_null<RecordDecl>(PrevDecl));
2251
2252 // If this has an identifier, add it to the scope stack.
2253 if ((TK == TK_Definition || !PrevDecl) && Name) {
2254 // The scope passed in may not be a decl scope. Zip up the scope tree until
2255 // we find one that is.
2256 while ((S->getFlags() & Scope::DeclScope) == 0)
2257 S = S->getParent();
2258
2259 // Add it to the decl chain.
2260 PushOnScopeChains(New, S);
2261 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002262
2263 // Handle #pragma pack: if the #pragma pack stack has non-default
2264 // alignment, make up a packed attribute for this decl. These
2265 // attributes are checked when the ASTContext lays out the
2266 // structure.
2267 //
2268 // It is important for implementing the correct semantics that this
2269 // happen here (in act on tag decl). The #pragma pack stack is
2270 // maintained as a result of parser callbacks which can occur at
2271 // many points during the parsing of a struct declaration (because
2272 // the #pragma tokens are effectively skipped over during the
2273 // parsing of the struct).
2274 if (unsigned Alignment = PackContext.getAlignment())
2275 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002276
2277 if (Attr)
2278 ProcessDeclAttributeList(New, Attr);
2279
2280 return New;
2281}
2282
2283
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002284/// Collect the instance variables declared in an Objective-C object. Used in
2285/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002286static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002287 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002288 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002289 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2290
2291 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002292 for (ObjCInterfaceDecl::ivar_iterator
2293 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2294
Ted Kremenek01e67792008-08-20 03:26:33 +00002295 ObjCIvarDecl* ID = *I;
2296 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2297 ID->getIdentifier(),
2298 ID->getType(),
2299 ID->getBitWidth()));
2300 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002301}
2302
2303/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2304/// instance variables of ClassName into Decls.
2305void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2306 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002307 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002308 // Check that ClassName is a valid class
2309 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2310 if (!Class) {
2311 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2312 return;
2313 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002314 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002315 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002316}
2317
Eli Friedman1b76ada2008-06-03 21:01:11 +00002318QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
2319 // This method tries to turn a variable array into a constant
2320 // array even when the size isn't an ICE. This is necessary
2321 // for compatibility with code that depends on gcc's buggy
2322 // constant expression folding, like struct {char x[(int)(char*)2];}
2323 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00002324 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002325 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00002326 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2327 llvm::APSInt &Res = Result.getInt();
2328 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2329 return Context.getConstantArrayType(VLATy->getElementType(),
2330 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002331 }
2332 }
2333 return QualType();
2334}
2335
Steve Naroff08d92e42007-09-15 18:49:24 +00002336/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002337/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002338Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002339 SourceLocation DeclStart,
2340 Declarator &D, ExprTy *BitfieldWidth) {
2341 IdentifierInfo *II = D.getIdentifier();
2342 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002343 SourceLocation Loc = DeclStart;
2344 if (II) Loc = D.getIdentifierLoc();
2345
2346 // FIXME: Unnamed fields can be handled in various different ways, for
2347 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002348
Reid Spencer5f016e22007-07-11 17:01:13 +00002349 if (BitWidth) {
2350 // TODO: Validate.
2351 //printf("WARNING: BITFIELDS IGNORED!\n");
2352
2353 // 6.7.2.1p3
2354 // 6.7.2.1p4
2355
2356 } else {
2357 // Not a bitfield.
2358
2359 // validate II.
2360
2361 }
2362
2363 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002364 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2365 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002366
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2368 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002369 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002370 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2371 if (!FixedTy.isNull()) {
2372 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2373 T = FixedTy;
2374 } else {
2375 // FIXME: This diagnostic needs work
2376 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2377 InvalidDecl = true;
2378 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002379 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002381 FieldDecl *NewFD;
2382
2383 if (getLangOptions().CPlusPlus) {
2384 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2385 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2386 Loc, II, T, BitWidth);
2387 if (II)
2388 PushOnScopeChains(NewFD, S);
2389 }
2390 else
2391 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002392
Chris Lattner3ff30c82008-06-29 00:02:00 +00002393 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002394
Steve Naroff5912a352007-08-28 20:14:24 +00002395 if (D.getInvalidType() || InvalidDecl)
2396 NewFD->setInvalidDecl();
2397 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002398}
2399
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002400/// TranslateIvarVisibility - Translate visibility from a token ID to an
2401/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002402static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002403TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002404 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002405 default: assert(0 && "Unknown visitibility kind");
2406 case tok::objc_private: return ObjCIvarDecl::Private;
2407 case tok::objc_public: return ObjCIvarDecl::Public;
2408 case tok::objc_protected: return ObjCIvarDecl::Protected;
2409 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002410 }
2411}
2412
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002413/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2414/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002415Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002416 SourceLocation DeclStart,
2417 Declarator &D, ExprTy *BitfieldWidth,
2418 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002419 IdentifierInfo *II = D.getIdentifier();
2420 Expr *BitWidth = (Expr*)BitfieldWidth;
2421 SourceLocation Loc = DeclStart;
2422 if (II) Loc = D.getIdentifierLoc();
2423
2424 // FIXME: Unnamed fields can be handled in various different ways, for
2425 // example, unnamed unions inject all members into the struct namespace!
2426
2427
2428 if (BitWidth) {
2429 // TODO: Validate.
2430 //printf("WARNING: BITFIELDS IGNORED!\n");
2431
2432 // 6.7.2.1p3
2433 // 6.7.2.1p4
2434
2435 } else {
2436 // Not a bitfield.
2437
2438 // validate II.
2439
2440 }
2441
2442 QualType T = GetTypeForDeclarator(D, S);
2443 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2444 bool InvalidDecl = false;
2445
2446 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2447 // than a variably modified type.
2448 if (T->isVariablyModifiedType()) {
2449 // FIXME: This diagnostic needs work
2450 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2451 InvalidDecl = true;
2452 }
2453
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002454 // Get the visibility (access control) for this ivar.
2455 ObjCIvarDecl::AccessControl ac =
2456 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2457 : ObjCIvarDecl::None;
2458
2459 // Construct the decl.
2460 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002461 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002462
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002463 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002464 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002465
2466 if (D.getInvalidType() || InvalidDecl)
2467 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002468
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002469 return NewID;
2470}
2471
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002472void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002473 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002474 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002475 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002476 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002477 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2478 assert(EnclosingDecl && "missing record or interface decl");
2479 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2480
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002481 if (Record)
2482 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2483 // Diagnose code like:
2484 // struct S { struct S {} X; };
2485 // We discover this when we complete the outer S. Reject and ignore the
2486 // outer S.
2487 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2488 DefRecord->getKindName());
2489 Diag(RecLoc, diag::err_previous_definition);
2490 Record->setInvalidDecl();
2491 return;
2492 }
2493
Reid Spencer5f016e22007-07-11 17:01:13 +00002494 // Verify that all the fields are okay.
2495 unsigned NumNamedMembers = 0;
2496 llvm::SmallVector<FieldDecl*, 32> RecFields;
2497 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002498
Reid Spencer5f016e22007-07-11 17:01:13 +00002499 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002500
Steve Naroff74216642007-09-14 22:20:54 +00002501 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2502 assert(FD && "missing field decl");
2503
2504 // Remember all fields.
2505 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002506
2507 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002508 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002509
Reid Spencer5f016e22007-07-11 17:01:13 +00002510 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002511 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002512 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002513 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002514 FD->setInvalidDecl();
2515 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002516 continue;
2517 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002518 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2519 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002520 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002521 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002522 FD->setInvalidDecl();
2523 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002524 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002525 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002526 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002527 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002528 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002529 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002530 FD->setInvalidDecl();
2531 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002532 continue;
2533 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002534 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002535 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2536 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002537 FD->setInvalidDecl();
2538 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002539 continue;
2540 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002541 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002542 if (Record)
2543 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002544 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002545 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2546 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002547 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002548 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2549 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002550 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002551 Record->setHasFlexibleArrayMember(true);
2552 } else {
2553 // If this is a struct/class and this is not the last element, reject
2554 // it. Note that GCC supports variable sized arrays in the middle of
2555 // structures.
2556 if (i != NumFields-1) {
2557 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2558 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002559 FD->setInvalidDecl();
2560 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 continue;
2562 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002563 // We support flexible arrays at the end of structs in other structs
2564 // as an extension.
2565 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2566 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002567 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002568 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 }
2570 }
2571 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002572 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002573 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002574 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2575 FD->getName());
2576 FD->setInvalidDecl();
2577 EnclosingDecl->setInvalidDecl();
2578 continue;
2579 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002580 // Keep track of the number of named members.
2581 if (IdentifierInfo *II = FD->getIdentifier()) {
2582 // Detect duplicate member names.
2583 if (!FieldIDs.insert(II)) {
2584 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2585 // Find the previous decl.
2586 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002587 for (unsigned i = 0; ; ++i) {
2588 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002589 if (RecFields[i]->getIdentifier() == II) {
2590 PrevLoc = RecFields[i]->getLocation();
2591 break;
2592 }
2593 }
2594 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002595 FD->setInvalidDecl();
2596 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002597 continue;
2598 }
2599 ++NumNamedMembers;
2600 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002601 }
2602
Reid Spencer5f016e22007-07-11 17:01:13 +00002603 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002604 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002605 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002606 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2607 // Sema::ActOnFinishCXXClassDef.
2608 if (!isa<CXXRecordDecl>(Record))
2609 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002610 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002611 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2612 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2613 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2614 else if (ObjCImplementationDecl *IMPDecl =
2615 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002616 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2617 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002618 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002619 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002620 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002621
2622 if (Attr)
2623 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002624}
2625
Steve Naroff08d92e42007-09-15 18:49:24 +00002626Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002627 DeclTy *lastEnumConst,
2628 SourceLocation IdLoc, IdentifierInfo *Id,
2629 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002630 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002631 EnumConstantDecl *LastEnumConst =
2632 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2633 Expr *Val = static_cast<Expr*>(val);
2634
Chris Lattner31e05722007-08-26 06:24:45 +00002635 // The scope passed in may not be a decl scope. Zip up the scope tree until
2636 // we find one that is.
2637 while ((S->getFlags() & Scope::DeclScope) == 0)
2638 S = S->getParent();
2639
Reid Spencer5f016e22007-07-11 17:01:13 +00002640 // Verify that there isn't already something declared with this name in this
2641 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002642 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002643 // When in C++, we may get a TagDecl with the same name; in this case the
2644 // enum constant will 'hide' the tag.
2645 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2646 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002647 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 if (isa<EnumConstantDecl>(PrevDecl))
2649 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2650 else
2651 Diag(IdLoc, diag::err_redefinition, Id->getName());
2652 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002653 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 return 0;
2655 }
2656 }
2657
2658 llvm::APSInt EnumVal(32);
2659 QualType EltTy;
2660 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002661 // Make sure to promote the operand type to int.
2662 UsualUnaryConversions(Val);
2663
Reid Spencer5f016e22007-07-11 17:01:13 +00002664 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2665 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002666 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002667 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2668 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002669 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002670 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002671 } else {
2672 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002673 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002674 }
2675
2676 if (!Val) {
2677 if (LastEnumConst) {
2678 // Assign the last value + 1.
2679 EnumVal = LastEnumConst->getInitVal();
2680 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002681
2682 // Check for overflow on increment.
2683 if (EnumVal < LastEnumConst->getInitVal())
2684 Diag(IdLoc, diag::warn_enum_value_overflow);
2685
Chris Lattnerb7416f92007-08-27 17:37:24 +00002686 EltTy = LastEnumConst->getType();
2687 } else {
2688 // First value, set to zero.
2689 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002690 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002691 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002692 }
2693
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002694 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002695 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2696 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002697 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002698
2699 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002700 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 return New;
2702}
2703
Steve Naroff02408c62008-08-07 14:08:16 +00002704// FIXME: For consistency with ActOnFields(), we should have the parser
2705// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002706void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002707 DeclTy **Elements, unsigned NumElements) {
2708 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002709
Steve Naroff02408c62008-08-07 14:08:16 +00002710 if (Enum && Enum->isDefinition()) {
2711 // Diagnose code like:
2712 // enum e0 {
2713 // E0 = sizeof(enum e0 { E1 })
2714 // };
2715 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2716 Enum->getName());
2717 Diag(EnumLoc, diag::err_previous_definition);
2718 Enum->setInvalidDecl();
2719 return;
2720 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002721 // TODO: If the result value doesn't fit in an int, it must be a long or long
2722 // long value. ISO C does not support this, but GCC does as an extension,
2723 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002724 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002725
Chris Lattnerac609682007-08-28 06:15:15 +00002726 // Verify that all the values are okay, compute the size of the values, and
2727 // reverse the list.
2728 unsigned NumNegativeBits = 0;
2729 unsigned NumPositiveBits = 0;
2730
2731 // Keep track of whether all elements have type int.
2732 bool AllElementsInt = true;
2733
Reid Spencer5f016e22007-07-11 17:01:13 +00002734 EnumConstantDecl *EltList = 0;
2735 for (unsigned i = 0; i != NumElements; ++i) {
2736 EnumConstantDecl *ECD =
2737 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2738 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002739
2740 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002741 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002742 assert(InitVal.getBitWidth() >= IntWidth &&
2743 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002744 if (InitVal.getBitWidth() > IntWidth) {
2745 llvm::APSInt V(InitVal);
2746 V.trunc(IntWidth);
2747 V.extend(InitVal.getBitWidth());
2748 if (V != InitVal)
2749 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002750 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002751 }
Chris Lattnerac609682007-08-28 06:15:15 +00002752
2753 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002754 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002755 NumPositiveBits = std::max(NumPositiveBits,
2756 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002757 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002758 NumNegativeBits = std::max(NumNegativeBits,
2759 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002760
Chris Lattnerac609682007-08-28 06:15:15 +00002761 // Keep track of whether every enum element has type int (very commmon).
2762 if (AllElementsInt)
2763 AllElementsInt = ECD->getType() == Context.IntTy;
2764
Reid Spencer5f016e22007-07-11 17:01:13 +00002765 ECD->setNextDeclarator(EltList);
2766 EltList = ECD;
2767 }
2768
Chris Lattnerac609682007-08-28 06:15:15 +00002769 // Figure out the type that should be used for this enum.
2770 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2771 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002772 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002773
2774 if (NumNegativeBits) {
2775 // If there is a negative value, figure out the smallest integer type (of
2776 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002777 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002778 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002779 BestWidth = IntWidth;
2780 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002781 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002782
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002783 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002784 BestType = Context.LongTy;
2785 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002786 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002787
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002788 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002789 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2790 BestType = Context.LongLongTy;
2791 }
2792 }
2793 } else {
2794 // If there is no negative value, figure out which of uint, ulong, ulonglong
2795 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002796 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002797 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002798 BestWidth = IntWidth;
2799 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002800 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002801 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002802 } else {
2803 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002804 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002805 "How could an initializer get larger than ULL?");
2806 BestType = Context.UnsignedLongLongTy;
2807 }
2808 }
2809
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002810 // Loop over all of the enumerator constants, changing their types to match
2811 // the type of the enum if needed.
2812 for (unsigned i = 0; i != NumElements; ++i) {
2813 EnumConstantDecl *ECD =
2814 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2815 if (!ECD) continue; // Already issued a diagnostic.
2816
2817 // Standard C says the enumerators have int type, but we allow, as an
2818 // extension, the enumerators to be larger than int size. If each
2819 // enumerator value fits in an int, type it as an int, otherwise type it the
2820 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2821 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002822 if (ECD->getType() == Context.IntTy) {
2823 // Make sure the init value is signed.
2824 llvm::APSInt IV = ECD->getInitVal();
2825 IV.setIsSigned(true);
2826 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002827 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002828 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002829
2830 // Determine whether the value fits into an int.
2831 llvm::APSInt InitVal = ECD->getInitVal();
2832 bool FitsInInt;
2833 if (InitVal.isUnsigned() || !InitVal.isNegative())
2834 FitsInInt = InitVal.getActiveBits() < IntWidth;
2835 else
2836 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2837
2838 // If it fits into an integer type, force it. Otherwise force it to match
2839 // the enum decl type.
2840 QualType NewTy;
2841 unsigned NewWidth;
2842 bool NewSign;
2843 if (FitsInInt) {
2844 NewTy = Context.IntTy;
2845 NewWidth = IntWidth;
2846 NewSign = true;
2847 } else if (ECD->getType() == BestType) {
2848 // Already the right type!
2849 continue;
2850 } else {
2851 NewTy = BestType;
2852 NewWidth = BestWidth;
2853 NewSign = BestType->isSignedIntegerType();
2854 }
2855
2856 // Adjust the APSInt value.
2857 InitVal.extOrTrunc(NewWidth);
2858 InitVal.setIsSigned(NewSign);
2859 ECD->setInitVal(InitVal);
2860
2861 // Adjust the Expr initializer and type.
2862 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2863 ECD->setType(NewTy);
2864 }
Chris Lattnerac609682007-08-28 06:15:15 +00002865
Chris Lattnere00b18c2007-08-28 18:24:31 +00002866 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002867 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002868}
2869
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002870Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2871 ExprTy *expr) {
2872 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2873
Chris Lattner8e25d862008-03-16 00:16:02 +00002874 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002875}
2876
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002877Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002878 SourceLocation LBrace,
2879 SourceLocation RBrace,
2880 const char *Lang,
2881 unsigned StrSize,
2882 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002883 LinkageSpecDecl::LanguageIDs Language;
2884 Decl *dcl = static_cast<Decl *>(D);
2885 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2886 Language = LinkageSpecDecl::lang_c;
2887 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2888 Language = LinkageSpecDecl::lang_cxx;
2889 else {
2890 Diag(Loc, diag::err_bad_language);
2891 return 0;
2892 }
2893
2894 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002895 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002896}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00002897
2898void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
2899 ExprTy *alignment, SourceLocation PragmaLoc,
2900 SourceLocation LParenLoc, SourceLocation RParenLoc) {
2901 Expr *Alignment = static_cast<Expr *>(alignment);
2902
2903 // If specified then alignment must be a "small" power of two.
2904 unsigned AlignmentVal = 0;
2905 if (Alignment) {
2906 llvm::APSInt Val;
2907 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
2908 !Val.isPowerOf2() ||
2909 Val.getZExtValue() > 16) {
2910 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
2911 delete Alignment;
2912 return; // Ignore
2913 }
2914
2915 AlignmentVal = (unsigned) Val.getZExtValue();
2916 }
2917
2918 switch (Kind) {
2919 case Action::PPK_Default: // pack([n])
2920 PackContext.setAlignment(AlignmentVal);
2921 break;
2922
2923 case Action::PPK_Show: // pack(show)
2924 // Show the current alignment, making sure to show the right value
2925 // for the default.
2926 AlignmentVal = PackContext.getAlignment();
2927 // FIXME: This should come from the target.
2928 if (AlignmentVal == 0)
2929 AlignmentVal = 8;
2930 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
2931 break;
2932
2933 case Action::PPK_Push: // pack(push [, id] [, [n])
2934 PackContext.push(Name);
2935 // Set the new alignment if specified.
2936 if (Alignment)
2937 PackContext.setAlignment(AlignmentVal);
2938 break;
2939
2940 case Action::PPK_Pop: // pack(pop [, id] [, n])
2941 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
2942 // "#pragma pack(pop, identifier, n) is undefined"
2943 if (Alignment && Name)
2944 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
2945
2946 // Do the pop.
2947 if (!PackContext.pop(Name)) {
2948 // If a name was specified then failure indicates the name
2949 // wasn't found. Otherwise failure indicates the stack was
2950 // empty.
2951 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
2952 Name ? "no record matching name" : "stack empty");
2953
2954 // FIXME: Warn about popping named records as MSVC does.
2955 } else {
2956 // Pop succeeded, set the new alignment if specified.
2957 if (Alignment)
2958 PackContext.setAlignment(AlignmentVal);
2959 }
2960 break;
2961
2962 default:
2963 assert(0 && "Invalid #pragma pack kind.");
2964 }
2965}
2966
2967bool PragmaPackStack::pop(IdentifierInfo *Name) {
2968 if (Stack.empty())
2969 return false;
2970
2971 // If name is empty just pop top.
2972 if (!Name) {
2973 Alignment = Stack.back().first;
2974 Stack.pop_back();
2975 return true;
2976 }
2977
2978 // Otherwise, find the named record.
2979 for (unsigned i = Stack.size(); i != 0; ) {
2980 --i;
2981 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
2982 // Found it, pop up to and including this record.
2983 Alignment = Stack[i].first;
2984 Stack.erase(Stack.begin() + i, Stack.end());
2985 return true;
2986 }
2987 }
2988
2989 return false;
2990}