blob: 1befc2e2e9a05125a35011c8a71af735d0bb3b63 [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 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +000098 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
99 // We are pushing the name of a function, which might be an
100 // overloaded name.
101 IdentifierResolver::iterator
102 I = IdResolver.begin(FD->getIdentifier(),
103 FD->getDeclContext(), false/*LookInParentCtx*/);
104 if (I != IdResolver.end() &&
105 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
106 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
107 // There is already a declaration with the same name in the same
108 // scope. It must be a function or an overloaded function.
109 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
110 if (!Ovl) {
111 // We haven't yet overloaded this function. Take the existing
112 // FunctionDecl and put it into an OverloadedFunctionDecl.
113 Ovl = OverloadedFunctionDecl::Create(Context,
114 FD->getDeclContext(),
115 FD->getIdentifier());
116 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
117
118 // Remove the name binding to the existing FunctionDecl...
119 IdResolver.RemoveDecl(*I);
120
121 // ... and put the OverloadedFunctionDecl in its place.
122 IdResolver.AddDecl(Ovl);
123 }
124
125 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
126 // to its list of overloads.
127 Ovl->addOverload(FD);
128
129 return;
130 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000131 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000132
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000133 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000134}
135
Steve Naroffb216c882007-10-09 22:01:59 +0000136void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000137 if (S->decl_empty()) return;
138 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000139
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
141 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000142 Decl *TmpD = static_cast<Decl*>(*I);
143 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000144
145 if (isa<CXXFieldDecl>(TmpD)) continue;
146
147 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
148 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000149
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 IdentifierInfo *II = D->getIdentifier();
151 if (!II) continue;
152
Ted Kremeneka89d1972008-09-03 18:03:35 +0000153 // We only want to remove the decls from the identifier decl chains for
154 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000155 if (S->getFnParent() != 0)
156 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000157
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000158 // Chain this decl to the containing DeclContext.
159 D->setNext(CurContext->getDeclChain());
160 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000161 }
162}
163
Steve Naroffe8043c32008-04-01 23:04:06 +0000164/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
165/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000166ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000167 // The third "scope" argument is 0 since we aren't enabling lazy built-in
168 // creation from this context.
169 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000170
Steve Naroffb327ce02008-04-02 14:35:35 +0000171 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000172}
173
Steve Naroffe8043c32008-04-01 23:04:06 +0000174/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000175/// namespace.
Steve Naroffb327ce02008-04-02 14:35:35 +0000176Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
177 Scope *S, bool enableLazyBuiltinCreation) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000178 if (II == 0) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000179 unsigned NS = NSI;
180 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
181 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 // Scan up the scope chain looking for a decl that matches this identifier
184 // that is in the appropriate namespace. This search should not take long, as
185 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000186 for (IdentifierResolver::iterator
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000187 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000188 if ((*I)->getIdentifierNamespace() & NS)
189 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000190
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 // If we didn't find a use of this identifier, and if the identifier
192 // corresponds to a compiler builtin, create the decl object for the builtin
193 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000194 if (NS & Decl::IDNS_Ordinary) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000195 if (enableLazyBuiltinCreation) {
196 // If this is a builtin on this (or all) targets, create the decl.
197 if (unsigned BuiltinID = II->getBuiltinID())
198 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
199 }
Steve Naroffe8043c32008-04-01 23:04:06 +0000200 if (getLangOptions().ObjC1) {
201 // @interface and @compatibility_alias introduce typedef-like names.
202 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000203 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000204 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000205 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
206 if (IDI != ObjCInterfaceDecls.end())
207 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000208 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
209 if (I != ObjCAliasDecls.end())
210 return I->second->getClassInterface();
211 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 }
213 return 0;
214}
215
Chris Lattner95e2c712008-05-05 22:18:14 +0000216void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000217 if (!Context.getBuiltinVaListType().isNull())
218 return;
219
220 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000221 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000222 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000223 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
224}
225
Reid Spencer5f016e22007-07-11 17:01:13 +0000226/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
227/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000228ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
229 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 Builtin::ID BID = (Builtin::ID)bid;
231
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000232 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000233 InitBuiltinVaListType();
234
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000235 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000236 FunctionDecl *New = FunctionDecl::Create(Context,
237 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000238 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000239 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000240
Chris Lattner95e2c712008-05-05 22:18:14 +0000241 // Create Decl objects for each parameter, adding them to the
242 // FunctionDecl.
243 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
244 llvm::SmallVector<ParmVarDecl*, 16> Params;
245 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
246 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
247 FT->getArgType(i), VarDecl::None, 0,
248 0));
249 New->setParams(&Params[0], Params.size());
250 }
251
252
253
Chris Lattner7f925cc2008-04-11 07:00:53 +0000254 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000255 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000256 return New;
257}
258
259/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
260/// and scope as a previous declaration 'Old'. Figure out how to resolve this
261/// situation, merging decls or emitting diagnostics as appropriate.
262///
Steve Naroffe8043c32008-04-01 23:04:06 +0000263TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000264 // Allow multiple definitions for ObjC built-in typedefs.
265 // FIXME: Verify the underlying types are equivalent!
266 if (getLangOptions().ObjC1) {
267 const IdentifierInfo *typeIdent = New->getIdentifier();
268 if (typeIdent == Ident_id) {
269 Context.setObjCIdType(New);
270 return New;
271 } else if (typeIdent == Ident_Class) {
272 Context.setObjCClassType(New);
273 return New;
274 } else if (typeIdent == Ident_SEL) {
275 Context.setObjCSelType(New);
276 return New;
277 } else if (typeIdent == Ident_Protocol) {
278 Context.setObjCProtoType(New->getUnderlyingType());
279 return New;
280 }
281 // Fall through - the typedef name was not a builtin type.
282 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000283 // Verify the old decl was also a typedef.
284 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
285 if (!Old) {
286 Diag(New->getLocation(), diag::err_redefinition_different_kind,
287 New->getName());
288 Diag(OldD->getLocation(), diag::err_previous_definition);
289 return New;
290 }
291
Chris Lattner99cb9972008-07-25 18:44:27 +0000292 // If the typedef types are not identical, reject them in all languages and
293 // with any extensions enabled.
294 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
295 Context.getCanonicalType(Old->getUnderlyingType()) !=
296 Context.getCanonicalType(New->getUnderlyingType())) {
297 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
298 New->getUnderlyingType().getAsString(),
299 Old->getUnderlyingType().getAsString());
300 Diag(Old->getLocation(), diag::err_previous_definition);
301 return Old;
302 }
303
Eli Friedman54ecfce2008-06-11 06:20:39 +0000304 if (getLangOptions().Microsoft) return New;
305
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000306 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
307 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
308 // *either* declaration is in a system header. The code below implements
309 // this adhoc compatibility rule. FIXME: The following code will not
310 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000311 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
312 SourceManager &SrcMgr = Context.getSourceManager();
313 if (SrcMgr.isInSystemHeader(Old->getLocation()))
314 return New;
315 if (SrcMgr.isInSystemHeader(New->getLocation()))
316 return New;
317 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000318
Ted Kremenek2d05c082008-05-23 21:28:18 +0000319 Diag(New->getLocation(), diag::err_redefinition, New->getName());
320 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000321 return New;
322}
323
Chris Lattner6b6b5372008-06-26 18:38:35 +0000324/// DeclhasAttr - returns true if decl Declaration already has the target
325/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000326static bool DeclHasAttr(const Decl *decl, const Attr *target) {
327 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
328 if (attr->getKind() == target->getKind())
329 return true;
330
331 return false;
332}
333
334/// MergeAttributes - append attributes from the Old decl to the New one.
335static void MergeAttributes(Decl *New, Decl *Old) {
336 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
337
Chris Lattnerddee4232008-03-03 03:28:21 +0000338 while (attr) {
339 tmp = attr;
340 attr = attr->getNext();
341
342 if (!DeclHasAttr(New, tmp)) {
343 New->addAttr(tmp);
344 } else {
345 tmp->setNext(0);
346 delete(tmp);
347 }
348 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000349
350 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000351}
352
Chris Lattner04421082008-04-08 04:40:51 +0000353/// MergeFunctionDecl - We just parsed a function 'New' from
354/// declarator D which has the same name and scope as a previous
355/// declaration 'Old'. Figure out how to resolve this situation,
356/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000357/// Redeclaration will be set true if this New is a redeclaration OldD.
358///
359/// In C++, New and Old must be declarations that are not
360/// overloaded. Use IsOverload to determine whether New and Old are
361/// overloaded, and to select the Old declaration that New should be
362/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000363FunctionDecl *
364Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000365 assert(!isa<OverloadedFunctionDecl>(OldD) &&
366 "Cannot merge with an overloaded function declaration");
367
Douglas Gregorf0097952008-04-21 02:02:58 +0000368 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000369 // Verify the old decl was also a function.
370 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
371 if (!Old) {
372 Diag(New->getLocation(), diag::err_redefinition_different_kind,
373 New->getName());
374 Diag(OldD->getLocation(), diag::err_previous_definition);
375 return New;
376 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000377
378 // Determine whether the previous declaration was a definition,
379 // implicit declaration, or a declaration.
380 diag::kind PrevDiag;
381 if (Old->isThisDeclarationADefinition())
382 PrevDiag = diag::err_previous_definition;
383 else if (Old->isImplicit())
384 PrevDiag = diag::err_previous_implicit_declaration;
385 else
386 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000387
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000388 QualType OldQType = Context.getCanonicalType(Old->getType());
389 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000390
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000391 if (getLangOptions().CPlusPlus) {
392 // (C++98 13.1p2):
393 // Certain function declarations cannot be overloaded:
394 // -- Function declarations that differ only in the return type
395 // cannot be overloaded.
396 QualType OldReturnType
397 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
398 QualType NewReturnType
399 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
400 if (OldReturnType != NewReturnType) {
401 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
402 Diag(Old->getLocation(), PrevDiag);
403 return New;
404 }
405
406 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
407 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
408 if (OldMethod && NewMethod) {
409 // -- Member function declarations with the same name and the
410 // same parameter types cannot be overloaded if any of them
411 // is a static member function declaration.
412 if (OldMethod->isStatic() || NewMethod->isStatic()) {
413 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
414 Diag(Old->getLocation(), PrevDiag);
415 return New;
416 }
417 }
418
419 // (C++98 8.3.5p3):
420 // All declarations for a function shall agree exactly in both the
421 // return type and the parameter-type-list.
422 if (OldQType == NewQType) {
423 // We have a redeclaration.
424 MergeAttributes(New, Old);
425 Redeclaration = true;
426 return MergeCXXFunctionDecl(New, Old);
427 }
428
429 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000430 }
Chris Lattner04421082008-04-08 04:40:51 +0000431
432 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000433 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000434 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000435 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000436 MergeAttributes(New, Old);
437 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000438 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000439 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000440
Steve Naroff837618c2008-01-16 15:01:34 +0000441 // A function that has already been declared has been redeclared or defined
442 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000443
Reid Spencer5f016e22007-07-11 17:01:13 +0000444 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
445 // TODO: This is totally simplistic. It should handle merging functions
446 // together etc, merging extern int X; int X; ...
Steve Naroff837618c2008-01-16 15:01:34 +0000447 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
448 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 return New;
450}
451
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000452/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000453static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000454 if (VD->isFileVarDecl())
455 return (!VD->getInit() &&
456 (VD->getStorageClass() == VarDecl::None ||
457 VD->getStorageClass() == VarDecl::Static));
458 return false;
459}
460
461/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
462/// when dealing with C "tentative" external object definitions (C99 6.9.2).
463void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
464 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000465 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000466
467 for (IdentifierResolver::iterator
468 I = IdResolver.begin(VD->getIdentifier(),
469 VD->getDeclContext(), false/*LookInParentCtx*/),
470 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000471 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000472 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
473
Steve Narofff855e6f2008-08-10 15:20:13 +0000474 // Handle the following case:
475 // int a[10];
476 // int a[]; - the code below makes sure we set the correct type.
477 // int a[11]; - this is an error, size isn't 10.
478 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
479 OldDecl->getType()->isConstantArrayType())
480 VD->setType(OldDecl->getType());
481
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000482 // Check for "tentative" definitions. We can't accomplish this in
483 // MergeVarDecl since the initializer hasn't been attached.
484 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
485 continue;
486
487 // Handle __private_extern__ just like extern.
488 if (OldDecl->getStorageClass() != VarDecl::Extern &&
489 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
490 VD->getStorageClass() != VarDecl::Extern &&
491 VD->getStorageClass() != VarDecl::PrivateExtern) {
492 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
493 Diag(OldDecl->getLocation(), diag::err_previous_definition);
494 }
495 }
496 }
497}
498
Reid Spencer5f016e22007-07-11 17:01:13 +0000499/// MergeVarDecl - We just parsed a variable 'New' which has the same name
500/// and scope as a previous declaration 'Old'. Figure out how to resolve this
501/// situation, merging decls or emitting diagnostics as appropriate.
502///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000503/// Tentative definition rules (C99 6.9.2p2) are checked by
504/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
505/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000506///
Steve Naroffe8043c32008-04-01 23:04:06 +0000507VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 // Verify the old decl was also a variable.
509 VarDecl *Old = dyn_cast<VarDecl>(OldD);
510 if (!Old) {
511 Diag(New->getLocation(), diag::err_redefinition_different_kind,
512 New->getName());
513 Diag(OldD->getLocation(), diag::err_previous_definition);
514 return New;
515 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000516
517 MergeAttributes(New, Old);
518
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000520 QualType OldCType = Context.getCanonicalType(Old->getType());
521 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000522 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 Diag(New->getLocation(), diag::err_redefinition, New->getName());
524 Diag(Old->getLocation(), diag::err_previous_definition);
525 return New;
526 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000527 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
528 if (New->getStorageClass() == VarDecl::Static &&
529 (Old->getStorageClass() == VarDecl::None ||
530 Old->getStorageClass() == VarDecl::Extern)) {
531 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
532 Diag(Old->getLocation(), diag::err_previous_definition);
533 return New;
534 }
535 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
536 if (New->getStorageClass() != VarDecl::Static &&
537 Old->getStorageClass() == VarDecl::Static) {
538 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
539 Diag(Old->getLocation(), diag::err_previous_definition);
540 return New;
541 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000542 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
543 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000544 Diag(New->getLocation(), diag::err_redefinition, New->getName());
545 Diag(Old->getLocation(), diag::err_previous_definition);
546 }
547 return New;
548}
549
Chris Lattner04421082008-04-08 04:40:51 +0000550/// CheckParmsForFunctionDef - Check that the parameters of the given
551/// function are appropriate for the definition of a function. This
552/// takes care of any checks that cannot be performed on the
553/// declaration itself, e.g., that the types of each of the function
554/// parameters are complete.
555bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
556 bool HasInvalidParm = false;
557 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
558 ParmVarDecl *Param = FD->getParamDecl(p);
559
560 // C99 6.7.5.3p4: the parameters in a parameter type list in a
561 // function declarator that is part of a function definition of
562 // that function shall not have incomplete type.
563 if (Param->getType()->isIncompleteType() &&
564 !Param->isInvalidDecl()) {
565 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
566 Param->getType().getAsString());
567 Param->setInvalidDecl();
568 HasInvalidParm = true;
569 }
570 }
571
572 return HasInvalidParm;
573}
574
Reid Spencer5f016e22007-07-11 17:01:13 +0000575/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
576/// no declarator (e.g. "struct foo;") is parsed.
577Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
578 // TODO: emit error on 'int;' or 'const enum foo;'.
579 // TODO: emit error on 'typedef int;'
580 // if (!DS.isMissingDeclaratorOk()) Diag(...);
581
Steve Naroff92199282007-11-17 21:37:36 +0000582 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000583}
584
Steve Naroffd0091aa2008-01-10 22:15:12 +0000585bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000586 // Get the type before calling CheckSingleAssignmentConstraints(), since
587 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000588 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000589
Chris Lattner5cf216b2008-01-04 18:04:52 +0000590 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
591 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
592 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000593}
594
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000595bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000596 const ArrayType *AT = Context.getAsArrayType(DeclT);
597
598 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000599 // C99 6.7.8p14. We have an array of character type with unknown size
600 // being initialized to a string literal.
601 llvm::APSInt ConstVal(32);
602 ConstVal = strLiteral->getByteLength() + 1;
603 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000604 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000605 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000606 } else {
607 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000608 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000609 // FIXME: Avoid truncation for 64-bit length strings.
610 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000611 Diag(strLiteral->getSourceRange().getBegin(),
612 diag::warn_initializer_string_for_char_array_too_long,
613 strLiteral->getSourceRange());
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000614 }
615 // Set type from "char *" to "constant array of char".
616 strLiteral->setType(DeclT);
617 // For now, we always return false (meaning success).
618 return false;
619}
620
621StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000622 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000623 if (AT && AT->getElementType()->isCharType()) {
624 return dyn_cast<StringLiteral>(Init);
625 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000626 return 0;
627}
628
Steve Naroffa9960332008-01-25 00:51:06 +0000629bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType) {
Steve Naroffca107302008-01-21 23:53:58 +0000630 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
631 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000632 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Steve Naroffca107302008-01-21 23:53:58 +0000633 return Diag(VAT->getSizeExpr()->getLocStart(),
634 diag::err_variable_object_no_init,
635 VAT->getSizeExpr()->getSourceRange());
636
Steve Naroff2fdc3742007-12-10 22:44:33 +0000637 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
638 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000639 // FIXME: Handle wide strings
640 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
641 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000642
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000643 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000644 if (DeclType->isArrayType())
645 return Diag(Init->getLocStart(),
646 diag::err_array_init_list_required,
647 Init->getSourceRange());
648
Steve Naroffd0091aa2008-01-10 22:15:12 +0000649 return CheckSingleInitializer(Init, DeclType);
Steve Naroff2fdc3742007-12-10 22:44:33 +0000650 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000651
Steve Naroff0cca7492008-05-01 22:18:59 +0000652 InitListChecker CheckInitList(this, InitList, DeclType);
653 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000654}
655
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000656Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000657Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000658 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +0000659 IdentifierInfo *II = D.getIdentifier();
660
Chris Lattnere80a59c2007-07-25 00:24:17 +0000661 // All of these full declarators require an identifier. If it doesn't have
662 // one, the ParsedFreeStandingDeclSpec action should be used.
663 if (II == 0) {
Chris Lattner311ff022007-10-16 22:36:42 +0000664 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner98e08632007-08-28 06:17:15 +0000665 diag::err_declarator_need_ident,
Chris Lattnere80a59c2007-07-25 00:24:17 +0000666 D.getDeclSpec().getSourceRange(), D.getSourceRange());
667 return 0;
668 }
669
Chris Lattner31e05722007-08-26 06:24:45 +0000670 // The scope passed in may not be a decl scope. Zip up the scope tree until
671 // we find one that is.
672 while ((S->getFlags() & Scope::DeclScope) == 0)
673 S = S->getParent();
674
Reid Spencer5f016e22007-07-11 17:01:13 +0000675 // See if this is a redefinition of a variable in the same scope.
Steve Naroffb327ce02008-04-02 14:35:35 +0000676 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffc752d042007-09-13 18:10:37 +0000677 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000678 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000679
680 // In C++, the previous declaration we find might be a tag type
681 // (class or enum). In this case, the new declaration will hide the
682 // tag type.
683 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
684 PrevDecl = 0;
685
Chris Lattner41af0932007-11-14 06:34:38 +0000686 QualType R = GetTypeForDeclarator(D, S);
687 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
688
Reid Spencer5f016e22007-07-11 17:01:13 +0000689 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000690 // Check that there are no default arguments (C++ only).
691 if (getLangOptions().CPlusPlus)
692 CheckExtraCXXDefaultArguments(D);
693
Chris Lattner41af0932007-11-14 06:34:38 +0000694 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000695 if (!NewTD) return 0;
696
697 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000698 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000699 // Merge the decl with the existing one if appropriate. If the decl is
700 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000701 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000702 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
703 if (NewTD == 0) return 0;
704 }
705 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000706 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000707 // C99 6.7.7p2: If a typedef name specifies a variably modified type
708 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000709 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
710 // FIXME: Diagnostic needs to be fixed.
711 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000712 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000713 }
714 }
Chris Lattner41af0932007-11-14 06:34:38 +0000715 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000716 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000717 switch (D.getDeclSpec().getStorageClassSpec()) {
718 default: assert(0 && "Unknown storage class!");
719 case DeclSpec::SCS_auto:
720 case DeclSpec::SCS_register:
721 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
722 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000723 InvalidDecl = true;
724 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000725 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
726 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
727 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000728 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000729 }
730
Chris Lattnera98e58d2008-03-15 21:24:04 +0000731 bool isInline = D.getDeclSpec().isInlineSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000732 FunctionDecl *NewFD;
733 if (D.getContext() == Declarator::MemberContext) {
734 // This is a C++ method declaration.
735 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
736 D.getIdentifierLoc(), II, R,
737 (SC == FunctionDecl::Static), isInline,
738 LastDeclarator);
739 } else {
740 NewFD = FunctionDecl::Create(Context, CurContext,
741 D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000742 II, R, SC, isInline, LastDeclarator,
743 // FIXME: Move to DeclGroup...
744 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000745 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000746 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000747 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000748
Daniel Dunbara80f8742008-08-05 01:35:17 +0000749 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000750 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000751 // The parser guarantees this is a string.
752 StringLiteral *SE = cast<StringLiteral>(E);
753 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
754 SE->getByteLength())));
755 }
756
Chris Lattner04421082008-04-08 04:40:51 +0000757 // Copy the parameter declarations from the declarator D to
758 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000759 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000760 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
761
762 // Create Decl objects for each parameter, adding them to the
763 // FunctionDecl.
764 llvm::SmallVector<ParmVarDecl*, 16> Params;
765
766 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
767 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +0000768 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000769 // We let through "const void" here because Sema::GetTypeForDeclarator
770 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +0000771 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
772 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +0000773 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
774 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +0000775 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
776
Chris Lattnerdef026a2008-04-10 02:26:16 +0000777 // In C++, the empty parameter-type-list must be spelled "void"; a
778 // typedef of void is not permitted.
779 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +0000780 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +0000781 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
782 }
783
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000784 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +0000785 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
786 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
787 }
788
789 NewFD->setParams(&Params[0], Params.size());
790 }
791
Steve Naroffffce4d52008-01-09 23:34:55 +0000792 // Merge the decl with the existing one if appropriate. Since C functions
793 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000794 if (PrevDecl &&
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000795 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000796 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000797
798 // If C++, determine whether NewFD is an overload of PrevDecl or
799 // a declaration that requires merging. If it's an overload,
800 // there's no more work to do here; we'll just add the new
801 // function to the scope.
802 OverloadedFunctionDecl::function_iterator MatchedDecl;
803 if (!getLangOptions().CPlusPlus ||
804 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
805 Decl *OldDecl = PrevDecl;
806
807 // If PrevDecl was an overloaded function, extract the
808 // FunctionDecl that matched.
809 if (isa<OverloadedFunctionDecl>(PrevDecl))
810 OldDecl = *MatchedDecl;
811
812 // NewFD and PrevDecl represent declarations that need to be
813 // merged.
814 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
815
816 if (NewFD == 0) return 0;
817 if (Redeclaration) {
818 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
819
820 if (OldDecl == PrevDecl) {
821 // Remove the name binding for the previous
822 // declaration. We'll add the binding back later, but then
823 // it will refer to the new declaration (which will
824 // contain more information).
825 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
826 } else {
827 // We need to update the OverloadedFunctionDecl with the
828 // latest declaration of this function, so that name
829 // lookup will always refer to the latest declaration of
830 // this function.
831 *MatchedDecl = NewFD;
832
833 // Add the redeclaration to the current scope, since we'll
834 // be skipping PushOnScopeChains.
835 S->AddDecl(NewFD);
836
837 return NewFD;
838 }
839 }
Douglas Gregorf0097952008-04-21 02:02:58 +0000840 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000841 }
842 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +0000843
844 // In C++, check default arguments now that we have merged decls.
845 if (getLangOptions().CPlusPlus)
846 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000847 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000848 // Check that there are no default arguments (C++ only).
849 if (getLangOptions().CPlusPlus)
850 CheckExtraCXXDefaultArguments(D);
851
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000852 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +0000853 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
854 D.getIdentifier()->getName());
855 InvalidDecl = true;
856 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000857
858 VarDecl *NewVD;
859 VarDecl::StorageClass SC;
860 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +0000861 default: assert(0 && "Unknown storage class!");
862 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
863 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
864 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
865 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
866 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
867 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000868 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000869 if (D.getContext() == Declarator::MemberContext) {
870 assert(SC == VarDecl::Static && "Invalid storage class for member!");
871 // This is a static data member for a C++ class.
872 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
873 D.getIdentifierLoc(), II,
874 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +0000875 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +0000876 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000877 if (S->getFnParent() == 0) {
878 // C99 6.9p2: The storage-class specifiers auto and register shall not
879 // appear in the declaration specifiers in an external declaration.
880 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
881 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
882 R.getAsString());
883 InvalidDecl = true;
884 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000885 }
Daniel Dunbar6f0200e2008-09-08 20:05:47 +0000886 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000887 II, R, SC, LastDeclarator,
888 // FIXME: Move to DeclGroup...
889 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar6f0200e2008-09-08 20:05:47 +0000890 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +0000891 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000892 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000893 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +0000894
Daniel Dunbara735ad82008-08-06 00:03:29 +0000895 // Handle GNU asm-label extension (encoded as an attribute).
896 if (Expr *E = (Expr*) D.getAsmLabel()) {
897 // The parser guarantees this is a string.
898 StringLiteral *SE = cast<StringLiteral>(E);
899 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
900 SE->getByteLength())));
901 }
902
Nate Begemanc8e89a82008-03-14 18:07:10 +0000903 // Emit an error if an address space was applied to decl with local storage.
904 // This includes arrays of objects with address space qualifiers, but not
905 // automatic variables that point to other address spaces.
906 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +0000907 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
908 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
909 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +0000910 }
Steve Naroffffce4d52008-01-09 23:34:55 +0000911 // Merge the decl with the existing one if appropriate. If the decl is
912 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000913 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000914 NewVD = MergeVarDecl(NewVD, PrevDecl);
915 if (NewVD == 0) return 0;
916 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000917 New = NewVD;
918 }
919
920 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000921 if (II)
922 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +0000923 // If any semantic error occurred, mark the decl as invalid.
924 if (D.getInvalidType() || InvalidDecl)
925 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +0000926
927 return New;
928}
929
Eli Friedmanc594b322008-05-20 13:48:25 +0000930bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
931 switch (Init->getStmtClass()) {
932 default:
933 Diag(Init->getExprLoc(),
934 diag::err_init_element_not_constant, Init->getSourceRange());
935 return true;
936 case Expr::ParenExprClass: {
937 const ParenExpr* PE = cast<ParenExpr>(Init);
938 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
939 }
940 case Expr::CompoundLiteralExprClass:
941 return cast<CompoundLiteralExpr>(Init)->isFileScope();
942 case Expr::DeclRefExprClass: {
943 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +0000944 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
945 if (VD->hasGlobalStorage())
946 return false;
947 Diag(Init->getExprLoc(),
948 diag::err_init_element_not_constant, Init->getSourceRange());
949 return true;
950 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000951 if (isa<FunctionDecl>(D))
952 return false;
953 Diag(Init->getExprLoc(),
954 diag::err_init_element_not_constant, Init->getSourceRange());
Steve Naroffd0091aa2008-01-10 22:15:12 +0000955 return true;
956 }
Eli Friedmanc594b322008-05-20 13:48:25 +0000957 case Expr::MemberExprClass: {
958 const MemberExpr *M = cast<MemberExpr>(Init);
959 if (M->isArrow())
960 return CheckAddressConstantExpression(M->getBase());
961 return CheckAddressConstantExpressionLValue(M->getBase());
962 }
963 case Expr::ArraySubscriptExprClass: {
964 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
965 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
966 return CheckAddressConstantExpression(ASE->getBase()) ||
967 CheckArithmeticConstantExpression(ASE->getIdx());
968 }
969 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +0000970 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +0000971 return false;
972 case Expr::UnaryOperatorClass: {
973 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
974
975 // C99 6.6p9
976 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +0000977 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000978
979 Diag(Init->getExprLoc(),
980 diag::err_init_element_not_constant, Init->getSourceRange());
981 return true;
982 }
983 }
984}
985
986bool Sema::CheckAddressConstantExpression(const Expr* Init) {
987 switch (Init->getStmtClass()) {
988 default:
989 Diag(Init->getExprLoc(),
990 diag::err_init_element_not_constant, Init->getSourceRange());
991 return true;
Chris Lattner506ff882008-10-06 07:26:43 +0000992 case Expr::ParenExprClass:
993 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +0000994 case Expr::StringLiteralClass:
995 case Expr::ObjCStringLiteralClass:
996 return false;
Chris Lattner506ff882008-10-06 07:26:43 +0000997 case Expr::CallExprClass:
998 // __builtin___CFStringMakeConstantString is a valid constant l-value.
999 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1000 Builtin::BI__builtin___CFStringMakeConstantString)
1001 return false;
1002
1003 Diag(Init->getExprLoc(),
1004 diag::err_init_element_not_constant, Init->getSourceRange());
1005 return true;
1006
Eli Friedmanc594b322008-05-20 13:48:25 +00001007 case Expr::UnaryOperatorClass: {
1008 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1009
1010 // C99 6.6p9
1011 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1012 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1013
1014 if (Exp->getOpcode() == UnaryOperator::Extension)
1015 return CheckAddressConstantExpression(Exp->getSubExpr());
1016
1017 Diag(Init->getExprLoc(),
1018 diag::err_init_element_not_constant, Init->getSourceRange());
1019 return true;
1020 }
1021 case Expr::BinaryOperatorClass: {
1022 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1023 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1024
1025 Expr *PExp = Exp->getLHS();
1026 Expr *IExp = Exp->getRHS();
1027 if (IExp->getType()->isPointerType())
1028 std::swap(PExp, IExp);
1029
1030 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1031 return CheckAddressConstantExpression(PExp) ||
1032 CheckArithmeticConstantExpression(IExp);
1033 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001034 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001035 case Expr::ExplicitCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001036 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001037 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1038 // Check for implicit promotion
1039 if (SubExpr->getType()->isFunctionType() ||
1040 SubExpr->getType()->isArrayType())
1041 return CheckAddressConstantExpressionLValue(SubExpr);
1042 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001043
1044 // Check for pointer->pointer cast
1045 if (SubExpr->getType()->isPointerType())
1046 return CheckAddressConstantExpression(SubExpr);
1047
Eli Friedmanc3f07642008-08-25 20:46:57 +00001048 if (SubExpr->getType()->isIntegralType()) {
1049 // Check for the special-case of a pointer->int->pointer cast;
1050 // this isn't standard, but some code requires it. See
1051 // PR2720 for an example.
1052 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1053 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1054 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1055 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1056 if (IntWidth >= PointerWidth) {
1057 return CheckAddressConstantExpression(SubCast->getSubExpr());
1058 }
1059 }
1060 }
1061 }
1062 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001063 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001064 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001065
1066 Diag(Init->getExprLoc(),
1067 diag::err_init_element_not_constant, Init->getSourceRange());
1068 return true;
1069 }
1070 case Expr::ConditionalOperatorClass: {
1071 // FIXME: Should we pedwarn here?
1072 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1073 if (!Exp->getCond()->getType()->isArithmeticType()) {
1074 Diag(Init->getExprLoc(),
1075 diag::err_init_element_not_constant, Init->getSourceRange());
1076 return true;
1077 }
1078 if (CheckArithmeticConstantExpression(Exp->getCond()))
1079 return true;
1080 if (Exp->getLHS() &&
1081 CheckAddressConstantExpression(Exp->getLHS()))
1082 return true;
1083 return CheckAddressConstantExpression(Exp->getRHS());
1084 }
1085 case Expr::AddrLabelExprClass:
1086 return false;
1087 }
1088}
1089
Eli Friedman4caf0552008-06-09 05:05:07 +00001090static const Expr* FindExpressionBaseAddress(const Expr* E);
1091
1092static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1093 switch (E->getStmtClass()) {
1094 default:
1095 return E;
1096 case Expr::ParenExprClass: {
1097 const ParenExpr* PE = cast<ParenExpr>(E);
1098 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1099 }
1100 case Expr::MemberExprClass: {
1101 const MemberExpr *M = cast<MemberExpr>(E);
1102 if (M->isArrow())
1103 return FindExpressionBaseAddress(M->getBase());
1104 return FindExpressionBaseAddressLValue(M->getBase());
1105 }
1106 case Expr::ArraySubscriptExprClass: {
1107 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1108 return FindExpressionBaseAddress(ASE->getBase());
1109 }
1110 case Expr::UnaryOperatorClass: {
1111 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1112
1113 if (Exp->getOpcode() == UnaryOperator::Deref)
1114 return FindExpressionBaseAddress(Exp->getSubExpr());
1115
1116 return E;
1117 }
1118 }
1119}
1120
1121static const Expr* FindExpressionBaseAddress(const Expr* E) {
1122 switch (E->getStmtClass()) {
1123 default:
1124 return E;
1125 case Expr::ParenExprClass: {
1126 const ParenExpr* PE = cast<ParenExpr>(E);
1127 return FindExpressionBaseAddress(PE->getSubExpr());
1128 }
1129 case Expr::UnaryOperatorClass: {
1130 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1131
1132 // C99 6.6p9
1133 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1134 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1135
1136 if (Exp->getOpcode() == UnaryOperator::Extension)
1137 return FindExpressionBaseAddress(Exp->getSubExpr());
1138
1139 return E;
1140 }
1141 case Expr::BinaryOperatorClass: {
1142 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1143
1144 Expr *PExp = Exp->getLHS();
1145 Expr *IExp = Exp->getRHS();
1146 if (IExp->getType()->isPointerType())
1147 std::swap(PExp, IExp);
1148
1149 return FindExpressionBaseAddress(PExp);
1150 }
1151 case Expr::ImplicitCastExprClass: {
1152 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1153
1154 // Check for implicit promotion
1155 if (SubExpr->getType()->isFunctionType() ||
1156 SubExpr->getType()->isArrayType())
1157 return FindExpressionBaseAddressLValue(SubExpr);
1158
1159 // Check for pointer->pointer cast
1160 if (SubExpr->getType()->isPointerType())
1161 return FindExpressionBaseAddress(SubExpr);
1162
1163 // We assume that we have an arithmetic expression here;
1164 // if we don't, we'll figure it out later
1165 return 0;
1166 }
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001167 case Expr::ExplicitCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001168 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1169
1170 // Check for pointer->pointer cast
1171 if (SubExpr->getType()->isPointerType())
1172 return FindExpressionBaseAddress(SubExpr);
1173
1174 // We assume that we have an arithmetic expression here;
1175 // if we don't, we'll figure it out later
1176 return 0;
1177 }
1178 }
1179}
1180
Eli Friedmanc594b322008-05-20 13:48:25 +00001181bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1182 switch (Init->getStmtClass()) {
1183 default:
1184 Diag(Init->getExprLoc(),
1185 diag::err_init_element_not_constant, Init->getSourceRange());
1186 return true;
1187 case Expr::ParenExprClass: {
1188 const ParenExpr* PE = cast<ParenExpr>(Init);
1189 return CheckArithmeticConstantExpression(PE->getSubExpr());
1190 }
1191 case Expr::FloatingLiteralClass:
1192 case Expr::IntegerLiteralClass:
1193 case Expr::CharacterLiteralClass:
1194 case Expr::ImaginaryLiteralClass:
1195 case Expr::TypesCompatibleExprClass:
1196 case Expr::CXXBoolLiteralExprClass:
1197 return false;
1198 case Expr::CallExprClass: {
1199 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001200
1201 // Allow any constant foldable calls to builtins.
1202 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001203 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001204
Eli Friedmanc594b322008-05-20 13:48:25 +00001205 Diag(Init->getExprLoc(),
1206 diag::err_init_element_not_constant, Init->getSourceRange());
1207 return true;
1208 }
1209 case Expr::DeclRefExprClass: {
1210 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1211 if (isa<EnumConstantDecl>(D))
1212 return false;
1213 Diag(Init->getExprLoc(),
1214 diag::err_init_element_not_constant, Init->getSourceRange());
1215 return true;
1216 }
1217 case Expr::CompoundLiteralExprClass:
1218 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1219 // but vectors are allowed to be magic.
1220 if (Init->getType()->isVectorType())
1221 return false;
1222 Diag(Init->getExprLoc(),
1223 diag::err_init_element_not_constant, Init->getSourceRange());
1224 return true;
1225 case Expr::UnaryOperatorClass: {
1226 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1227
1228 switch (Exp->getOpcode()) {
1229 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1230 // See C99 6.6p3.
1231 default:
1232 Diag(Init->getExprLoc(),
1233 diag::err_init_element_not_constant, Init->getSourceRange());
1234 return true;
1235 case UnaryOperator::SizeOf:
1236 case UnaryOperator::AlignOf:
1237 case UnaryOperator::OffsetOf:
1238 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1239 // See C99 6.5.3.4p2 and 6.6p3.
1240 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1241 return false;
1242 Diag(Init->getExprLoc(),
1243 diag::err_init_element_not_constant, Init->getSourceRange());
1244 return true;
1245 case UnaryOperator::Extension:
1246 case UnaryOperator::LNot:
1247 case UnaryOperator::Plus:
1248 case UnaryOperator::Minus:
1249 case UnaryOperator::Not:
1250 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1251 }
1252 }
1253 case Expr::SizeOfAlignOfTypeExprClass: {
1254 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1255 // Special check for void types, which are allowed as an extension
1256 if (Exp->getArgumentType()->isVoidType())
1257 return false;
1258 // alignof always evaluates to a constant.
1259 // FIXME: is sizeof(int[3.0]) a constant expression?
1260 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
1261 Diag(Init->getExprLoc(),
1262 diag::err_init_element_not_constant, Init->getSourceRange());
1263 return true;
1264 }
1265 return false;
1266 }
1267 case Expr::BinaryOperatorClass: {
1268 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1269
1270 if (Exp->getLHS()->getType()->isArithmeticType() &&
1271 Exp->getRHS()->getType()->isArithmeticType()) {
1272 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1273 CheckArithmeticConstantExpression(Exp->getRHS());
1274 }
1275
Eli Friedman4caf0552008-06-09 05:05:07 +00001276 if (Exp->getLHS()->getType()->isPointerType() &&
1277 Exp->getRHS()->getType()->isPointerType()) {
1278 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1279 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1280
1281 // Only allow a null (constant integer) base; we could
1282 // allow some additional cases if necessary, but this
1283 // is sufficient to cover offsetof-like constructs.
1284 if (!LHSBase && !RHSBase) {
1285 return CheckAddressConstantExpression(Exp->getLHS()) ||
1286 CheckAddressConstantExpression(Exp->getRHS());
1287 }
1288 }
1289
Eli Friedmanc594b322008-05-20 13:48:25 +00001290 Diag(Init->getExprLoc(),
1291 diag::err_init_element_not_constant, Init->getSourceRange());
1292 return true;
1293 }
1294 case Expr::ImplicitCastExprClass:
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001295 case Expr::ExplicitCastExprClass: {
1296 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001297 if (SubExpr->getType()->isArithmeticType())
1298 return CheckArithmeticConstantExpression(SubExpr);
1299
Eli Friedmanb529d832008-09-02 09:37:00 +00001300 if (SubExpr->getType()->isPointerType()) {
1301 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1302 // If the pointer has a null base, this is an offsetof-like construct
1303 if (!Base)
1304 return CheckAddressConstantExpression(SubExpr);
1305 }
1306
Eli Friedman6d4abe12008-09-01 22:08:17 +00001307 Diag(Init->getExprLoc(),
1308 diag::err_init_element_not_constant, Init->getSourceRange());
1309 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001310 }
1311 case Expr::ConditionalOperatorClass: {
1312 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001313
1314 // If GNU extensions are disabled, we require all operands to be arithmetic
1315 // constant expressions.
1316 if (getLangOptions().NoExtensions) {
1317 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1318 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1319 CheckArithmeticConstantExpression(Exp->getRHS());
1320 }
1321
1322 // Otherwise, we have to emulate some of the behavior of fold here.
1323 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1324 // because it can constant fold things away. To retain compatibility with
1325 // GCC code, we see if we can fold the condition to a constant (which we
1326 // should always be able to do in theory). If so, we only require the
1327 // specified arm of the conditional to be a constant. This is a horrible
1328 // hack, but is require by real world code that uses __builtin_constant_p.
1329 APValue Val;
1330 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1331 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1332 // won't be able to either. Use it to emit the diagnostic though.
1333 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1334 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1335 return Res;
1336 }
1337
1338 // Verify that the side following the condition is also a constant.
1339 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1340 if (Val.getInt() == 0)
1341 std::swap(TrueSide, FalseSide);
1342
1343 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001344 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001345
1346 // Okay, the evaluated side evaluates to a constant, so we accept this.
1347 // Check to see if the other side is obviously not a constant. If so,
1348 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001349 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001350 Diag(Init->getExprLoc(),
1351 diag::ext_typecheck_expression_not_constant_but_accepted,
1352 FalseSide->getSourceRange());
1353 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001354 }
1355 }
1356}
1357
1358bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001359 Init = Init->IgnoreParens();
1360
Eli Friedmanc594b322008-05-20 13:48:25 +00001361 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1362 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1363 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1364
Nuno Lopes9a979c32008-07-07 16:46:50 +00001365 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1366 return CheckForConstantInitializer(e->getInitializer(), DclT);
1367
Eli Friedmanc594b322008-05-20 13:48:25 +00001368 if (Init->getType()->isReferenceType()) {
Chris Lattner46cfefa2008-10-06 05:42:39 +00001369 // FIXME: Work out how the heck references work.
Eli Friedmanc594b322008-05-20 13:48:25 +00001370 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001371 }
1372
1373 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1374 unsigned numInits = Exp->getNumInits();
1375 for (unsigned i = 0; i < numInits; i++) {
1376 // FIXME: Need to get the type of the declaration for C++,
1377 // because it could be a reference?
1378 if (CheckForConstantInitializer(Exp->getInit(i),
1379 Exp->getInit(i)->getType()))
1380 return true;
1381 }
1382 return false;
1383 }
1384
1385 if (Init->isNullPointerConstant(Context))
1386 return false;
1387 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001388 QualType InitTy = Context.getCanonicalType(Init->getType())
1389 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001390 if (InitTy == Context.BoolTy) {
1391 // Special handling for pointers implicitly cast to bool;
1392 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1393 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1394 Expr* SubE = ICE->getSubExpr();
1395 if (SubE->getType()->isPointerType() ||
1396 SubE->getType()->isArrayType() ||
1397 SubE->getType()->isFunctionType()) {
1398 return CheckAddressConstantExpression(Init);
1399 }
1400 }
1401 } else if (InitTy->isIntegralType()) {
1402 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001403 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001404 SubE = CE->getSubExpr();
1405 // Special check for pointer cast to int; we allow as an extension
1406 // an address constant cast to an integer if the integer
1407 // is of an appropriate width (this sort of code is apparently used
1408 // in some places).
1409 // FIXME: Add pedwarn?
1410 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1411 if (SubE && (SubE->getType()->isPointerType() ||
1412 SubE->getType()->isArrayType() ||
1413 SubE->getType()->isFunctionType())) {
1414 unsigned IntWidth = Context.getTypeSize(Init->getType());
1415 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1416 if (IntWidth >= PointerWidth)
1417 return CheckAddressConstantExpression(Init);
1418 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001419 }
1420
1421 return CheckArithmeticConstantExpression(Init);
1422 }
1423
1424 if (Init->getType()->isPointerType())
1425 return CheckAddressConstantExpression(Init);
1426
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001427 // An array type at the top level that isn't an init-list must
1428 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001429 if (Init->getType()->isArrayType())
1430 return false;
1431
Nuno Lopes73419bf2008-09-01 18:42:41 +00001432 if (Init->getType()->isFunctionType())
1433 return false;
1434
Steve Naroff8af6a452008-10-02 17:12:56 +00001435 // Allow block exprs at top level.
1436 if (Init->getType()->isBlockPointerType())
1437 return false;
1438
Eli Friedmanc594b322008-05-20 13:48:25 +00001439 Diag(Init->getExprLoc(), diag::err_init_element_not_constant,
1440 Init->getSourceRange());
1441 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001442}
1443
Steve Naroffbb204692007-09-12 14:07:44 +00001444void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001445 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001446 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001447 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001448
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001449 // If there is no declaration, there was an error parsing it. Just ignore
1450 // the initializer.
1451 if (RealDecl == 0) {
1452 delete Init;
1453 return;
1454 }
Steve Naroffbb204692007-09-12 14:07:44 +00001455
Steve Naroff410e3e22007-09-12 20:13:48 +00001456 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1457 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001458 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1459 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001460 RealDecl->setInvalidDecl();
1461 return;
1462 }
Steve Naroffbb204692007-09-12 14:07:44 +00001463 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001464 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001465 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001466 if (VDecl->isBlockVarDecl()) {
1467 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001468 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001469 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001470 VDecl->setInvalidDecl();
1471 } else if (!VDecl->isInvalidDecl()) {
Steve Naroffa9960332008-01-25 00:51:06 +00001472 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001473 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001474
1475 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1476 if (!getLangOptions().CPlusPlus) {
1477 if (SC == VarDecl::Static) // C99 6.7.8p4.
1478 CheckForConstantInitializer(Init, DclT);
1479 }
Steve Naroffbb204692007-09-12 14:07:44 +00001480 }
Steve Naroff248a7532008-04-15 22:42:06 +00001481 } else if (VDecl->isFileVarDecl()) {
1482 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001483 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001484 if (!VDecl->isInvalidDecl())
Steve Naroffa9960332008-01-25 00:51:06 +00001485 if (CheckInitializerTypes(Init, DclT))
Steve Naroff248a7532008-04-15 22:42:06 +00001486 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001487
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001488 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1489 if (!getLangOptions().CPlusPlus) {
1490 // C99 6.7.8p4. All file scoped initializers need to be constant.
1491 CheckForConstantInitializer(Init, DclT);
1492 }
Steve Naroffbb204692007-09-12 14:07:44 +00001493 }
1494 // If the type changed, it means we had an incomplete type that was
1495 // completed by the initializer. For example:
1496 // int ary[] = { 1, 3, 5 };
1497 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001498 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001499 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001500 Init->setType(DclT);
1501 }
Steve Naroffbb204692007-09-12 14:07:44 +00001502
1503 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001504 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001505 return;
1506}
1507
Reid Spencer5f016e22007-07-11 17:01:13 +00001508/// The declarators are chained together backwards, reverse the list.
1509Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1510 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001511 Decl *GroupDecl = static_cast<Decl*>(group);
1512 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001513 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001514
1515 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1516 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001517 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001518 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001519 else { // reverse the list.
1520 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001521 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001522 Group->setNextDeclarator(NewGroup);
1523 NewGroup = Group;
1524 Group = Next;
1525 }
1526 }
1527 // Perform semantic analysis that depends on having fully processed both
1528 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001529 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001530 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1531 if (!IDecl)
1532 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001533 QualType T = IDecl->getType();
1534
1535 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1536 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001537 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1538 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001539 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001540 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1541 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001542 }
1543 }
1544 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1545 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001546 if (IDecl->isBlockVarDecl() &&
1547 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001548 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001549 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1550 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001551 IDecl->setInvalidDecl();
1552 }
1553 }
1554 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1555 // object that has file scope without an initializer, and without a
1556 // storage-class specifier or with the storage-class specifier "static",
1557 // constitutes a tentative definition. Note: A tentative definition with
1558 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001559 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001560 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001561 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1562 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001563 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001564 // C99 6.9.2p3: If the declaration of an identifier for an object is
1565 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1566 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001567 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1568 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001569 IDecl->setInvalidDecl();
1570 }
1571 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001572 if (IDecl->isFileVarDecl())
1573 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001574 }
1575 return NewGroup;
1576}
Steve Naroffe1223f72007-08-28 03:03:08 +00001577
Chris Lattner04421082008-04-08 04:40:51 +00001578/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1579/// to introduce parameters into function prototype scope.
1580Sema::DeclTy *
1581Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00001582 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001583
1584 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001585 VarDecl::StorageClass StorageClass = VarDecl::None;
1586 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1587 StorageClass = VarDecl::Register;
1588 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001589 Diag(DS.getStorageClassSpecLoc(),
1590 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001591 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001592 }
1593 if (DS.isThreadSpecified()) {
1594 Diag(DS.getThreadSpecLoc(),
1595 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001596 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001597 }
1598
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001599 // Check that there are no default arguments inside the type of this
1600 // parameter (C++ only).
1601 if (getLangOptions().CPlusPlus)
1602 CheckExtraCXXDefaultArguments(D);
1603
Chris Lattner04421082008-04-08 04:40:51 +00001604 // In this context, we *do not* check D.getInvalidType(). If the declarator
1605 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1606 // though it will not reflect the user specified type.
1607 QualType parmDeclType = GetTypeForDeclarator(D, S);
1608
1609 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1610
Reid Spencer5f016e22007-07-11 17:01:13 +00001611 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1612 // Can this happen for params? We already checked that they don't conflict
1613 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001614 IdentifierInfo *II = D.getIdentifier();
1615 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1616 if (S->isDeclScope(PrevDecl)) {
1617 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1618 dyn_cast<NamedDecl>(PrevDecl)->getName());
1619
1620 // Recover by removing the name
1621 II = 0;
1622 D.SetIdentifier(0, D.getIdentifierLoc());
1623 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001624 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001625
1626 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1627 // Doing the promotion here has a win and a loss. The win is the type for
1628 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1629 // code generator). The loss is the orginal type isn't preserved. For example:
1630 //
1631 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1632 // int blockvardecl[5];
1633 // sizeof(parmvardecl); // size == 4
1634 // sizeof(blockvardecl); // size == 20
1635 // }
1636 //
1637 // For expressions, all implicit conversions are captured using the
1638 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1639 //
1640 // FIXME: If a source translation tool needs to see the original type, then
1641 // we need to consider storing both types (in ParmVarDecl)...
1642 //
Chris Lattnere6327742008-04-02 05:18:44 +00001643 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00001644 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00001645 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00001646 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001647 parmDeclType = Context.getPointerType(parmDeclType);
1648
Chris Lattner04421082008-04-08 04:40:51 +00001649 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1650 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001651 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00001652 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00001653
Chris Lattner04421082008-04-08 04:40:51 +00001654 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00001655 New->setInvalidDecl();
1656
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001657 if (II)
1658 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00001659
Chris Lattner3ff30c82008-06-29 00:02:00 +00001660 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00001661 return New;
Chris Lattner04421082008-04-08 04:40:51 +00001662
Reid Spencer5f016e22007-07-11 17:01:13 +00001663}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00001664
Chris Lattnerb652cea2007-10-09 17:14:05 +00001665Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001666 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00001667 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1668 "Not a function declarator!");
1669 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00001670
Reid Spencer5f016e22007-07-11 17:01:13 +00001671 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1672 // for a K&R function.
1673 if (!FTI.hasPrototype) {
1674 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00001675 if (FTI.ArgInfo[i].Param == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001676 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1677 FTI.ArgInfo[i].Ident->getName());
1678 // Implicitly declare the argument as type 'int' for lack of a better
1679 // type.
Chris Lattner04421082008-04-08 04:40:51 +00001680 DeclSpec DS;
1681 const char* PrevSpec; // unused
1682 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1683 PrevSpec);
1684 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1685 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1686 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001687 }
1688 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001689 } else {
Chris Lattner04421082008-04-08 04:40:51 +00001690 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00001691 }
1692
1693 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001694
1695 // See if this is a redefinition.
Steve Naroffe8043c32008-04-01 23:04:06 +00001696 Decl *PrevDcl = LookupDecl(D.getIdentifier(), Decl::IDNS_Ordinary,
Steve Naroffb327ce02008-04-02 14:35:35 +00001697 GlobalScope);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001698 if (PrevDcl && isDeclInScope(PrevDcl, CurContext)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001699 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(PrevDcl)) {
1700 const FunctionDecl *Definition;
1701 if (FD->getBody(Definition)) {
1702 Diag(D.getIdentifierLoc(), diag::err_redefinition,
1703 D.getIdentifier()->getName());
1704 Diag(Definition->getLocation(), diag::err_previous_definition);
1705 }
Steve Naroffadbbd0c2008-01-14 20:51:29 +00001706 }
1707 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001708
1709 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00001710 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001711}
1712
1713Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1714 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00001715 FunctionDecl *FD = cast<FunctionDecl>(decl);
Chris Lattnerb048c982008-04-06 04:47:34 +00001716 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00001717
1718 // Check the validity of our function parameters
1719 CheckParmsForFunctionDef(FD);
1720
1721 // Introduce our parameters into the function scope
1722 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1723 ParmVarDecl *Param = FD->getParamDecl(p);
1724 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001725 if (Param->getIdentifier())
1726 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00001727 }
Chris Lattner04421082008-04-08 04:40:51 +00001728
Reid Spencer5f016e22007-07-11 17:01:13 +00001729 return FD;
1730}
1731
Steve Naroffd6d054d2007-11-11 23:20:51 +00001732Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1733 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00001734 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001735 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00001736 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00001737 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00001738 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00001739 } else
1740 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00001741 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00001742 // Verify and clean out per-function state.
1743
1744 // Check goto/label use.
1745 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1746 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1747 // Verify that we have no forward references left. If so, there was a goto
1748 // or address of a label taken, but no definition of it. Label fwd
1749 // definitions are indicated with a null substmt.
1750 if (I->second->getSubStmt() == 0) {
1751 LabelStmt *L = I->second;
1752 // Emit error.
1753 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1754
1755 // At this point, we have gotos that use the bogus label. Stitch it into
1756 // the function body so that they aren't leaked and that the AST is well
1757 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00001758 if (Body) {
1759 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1760 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1761 } else {
1762 // The whole function wasn't parsed correctly, just delete this.
1763 delete L;
1764 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001765 }
1766 }
1767 LabelMap.clear();
1768
Steve Naroffd6d054d2007-11-11 23:20:51 +00001769 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00001770}
1771
Reid Spencer5f016e22007-07-11 17:01:13 +00001772/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1773/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00001774ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1775 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00001776 // Extension in C99. Legal in C90, but warn about it.
1777 if (getLangOptions().C99)
Reid Spencer5f016e22007-07-11 17:01:13 +00001778 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattner37d10842008-05-05 21:18:06 +00001779 else
Reid Spencer5f016e22007-07-11 17:01:13 +00001780 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1781
1782 // FIXME: handle stuff like:
1783 // void foo() { extern float X(); }
1784 // void bar() { X(); } <-- implicit decl for X in another scope.
1785
1786 // Set a Declarator for the implicit definition: int foo();
1787 const char *Dummy;
1788 DeclSpec DS;
1789 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1790 Error = Error; // Silence warning.
1791 assert(!Error && "Error setting up implicit decl!");
1792 Declarator D(DS, Declarator::BlockContext);
1793 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, Loc));
1794 D.SetIdentifier(&II, Loc);
1795
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001796 // Insert this function into translation-unit scope.
1797
1798 DeclContext *PrevDC = CurContext;
1799 CurContext = Context.getTranslationUnitDecl();
1800
Steve Naroffe2ef8152008-04-04 14:32:09 +00001801 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00001802 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00001803 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00001804
1805 CurContext = PrevDC;
1806
Steve Naroffe2ef8152008-04-04 14:32:09 +00001807 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001808}
1809
1810
Chris Lattner41af0932007-11-14 06:34:38 +00001811TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00001812 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001813 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00001814 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00001815
1816 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001817 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
1818 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00001819 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00001820 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00001821 if (D.getInvalidType())
1822 NewTD->setInvalidDecl();
1823 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00001824}
1825
Steve Naroff08d92e42007-09-15 18:49:24 +00001826/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00001827/// former case, Name will be non-null. In the later case, Name will be null.
1828/// TagType indicates what kind of tag this is. TK indicates whether this is a
1829/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00001830Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Reid Spencer5f016e22007-07-11 17:01:13 +00001831 SourceLocation KWLoc, IdentifierInfo *Name,
1832 SourceLocation NameLoc, AttributeList *Attr) {
1833 // If this is a use of an existing tag, it must have a name.
1834 assert((Name != 0 || TK == TK_Definition) &&
1835 "Nameless record must be a definition!");
1836
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001837 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00001838 switch (TagType) {
1839 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001840 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
1841 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
1842 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
1843 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001844 }
1845
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001846 // Two code paths: a new one for structs/unions/classes where we create
1847 // separate decls for forward declarations, and an old (eventually to
1848 // be removed) code path for enums.
1849 if (Kind != TagDecl::TK_enum)
1850 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
1851
Reid Spencer5f016e22007-07-11 17:01:13 +00001852 // If this is a named struct, check to see if there was a previous forward
1853 // declaration or definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001854 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenek7e8cc572008-09-02 21:26:19 +00001855 ScopedDecl *PrevDecl =
1856 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1857
1858 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001859 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1860 "unexpected Decl type");
1861 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001862 // If this is a use of a previous tag, or if the tag is already declared
1863 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001864 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001865 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00001866 // Make sure that this wasn't declared as an enum and now used as a
1867 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001868 if (PrevTagDecl->getTagKind() != Kind) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001869 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1870 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00001871 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001872 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00001873 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001874 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00001875 // If this is a use or a forward declaration, we're good.
1876 if (TK != TK_Definition)
1877 return PrevDecl;
1878
1879 // Diagnose attempts to redefine a tag.
1880 if (PrevTagDecl->isDefinition()) {
1881 Diag(NameLoc, diag::err_redefinition, Name->getName());
1882 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1883 // If this is a redefinition, recover by making this struct be
1884 // anonymous, which will make any later references get the previous
1885 // definition.
1886 Name = 0;
1887 } else {
1888 // Okay, this is definition of a previously declared or referenced
1889 // tag. Move the location of the decl to be the definition site.
1890 PrevDecl->setLocation(NameLoc);
1891 return PrevDecl;
1892 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001893 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001894 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00001895 // If we get here, this is a definition of a new struct type in a nested
1896 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
1897 // type.
1898 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001899 // PrevDecl is a namespace.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001900 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00001901 // The tag name clashes with a namespace name, issue an error and
1902 // recover by making this tag be anonymous.
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00001903 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
1904 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
1905 Name = 0;
1906 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001907 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001908 }
1909
1910 // If there is an identifier, use the location of the identifier as the
1911 // location of the decl, otherwise use the location of the struct/union
1912 // keyword.
1913 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
1914
1915 // Otherwise, if this is the first time we've seen this tag, create the decl.
1916 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001917 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001918 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1919 // enum X { A, B, C } D; D should chain to X.
Chris Lattner0ed844b2008-04-04 06:12:32 +00001920 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00001921 // If this is an undefined enum, warn.
1922 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001923 } else {
1924 // struct/union/class
1925
Reid Spencer5f016e22007-07-11 17:01:13 +00001926 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
1927 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001928 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00001929 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenekdf042e62008-09-05 01:34:33 +00001930 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001931 else
Ted Kremenekdf042e62008-09-05 01:34:33 +00001932 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001933 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001934
1935 // If this has an identifier, add it to the scope stack.
1936 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00001937 // The scope passed in may not be a decl scope. Zip up the scope tree until
1938 // we find one that is.
1939 while ((S->getFlags() & Scope::DeclScope) == 0)
1940 S = S->getParent();
1941
1942 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001943 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00001944 }
Chris Lattnere1e79852008-02-06 00:51:33 +00001945
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00001946 if (Attr)
1947 ProcessDeclAttributeList(New, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00001948 return New;
1949}
1950
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001951/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
1952/// the logic for enums, we create separate decls for forward declarations.
1953/// This is called by ActOnTag, but eventually will replace its logic.
1954Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
1955 SourceLocation KWLoc, IdentifierInfo *Name,
1956 SourceLocation NameLoc, AttributeList *Attr) {
1957
1958 // If this is a named struct, check to see if there was a previous forward
1959 // declaration or definition.
1960 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
1961 ScopedDecl *PrevDecl =
1962 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
1963
1964 if (PrevDecl) {
1965 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
1966 "unexpected Decl type");
1967
1968 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
1969 // If this is a use of a previous tag, or if the tag is already declared
1970 // in the same scope (so that the definition/declaration completes or
1971 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00001972 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00001973 // Make sure that this wasn't declared as an enum and now used as a
1974 // struct or something similar.
1975 if (PrevTagDecl->getTagKind() != Kind) {
1976 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
1977 Diag(PrevDecl->getLocation(), diag::err_previous_use);
1978 // Recover by making this an anonymous redefinition.
1979 Name = 0;
1980 PrevDecl = 0;
1981 } else {
1982 // If this is a use, return the original decl.
1983
1984 // FIXME: In the future, return a variant or some other clue
1985 // for the consumer of this Decl to know it doesn't own it.
1986 // For our current ASTs this shouldn't be a problem, but will
1987 // need to be changed with DeclGroups.
1988 if (TK == TK_Reference)
1989 return PrevDecl;
1990
1991 // The new decl is a definition?
1992 if (TK == TK_Definition) {
1993 // Diagnose attempts to redefine a tag.
1994 if (RecordDecl* DefRecord =
1995 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
1996 Diag(NameLoc, diag::err_redefinition, Name->getName());
1997 Diag(DefRecord->getLocation(), diag::err_previous_definition);
1998 // If this is a redefinition, recover by making this struct be
1999 // anonymous, which will make any later references get the previous
2000 // definition.
2001 Name = 0;
2002 PrevDecl = 0;
2003 }
2004 // Okay, this is definition of a previously declared or referenced
2005 // tag. We're going to create a new Decl.
2006 }
2007 }
2008 // If we get here we have (another) forward declaration. Just create
2009 // a new decl.
2010 }
2011 else {
2012 // If we get here, this is a definition of a new struct type in a nested
2013 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2014 // new decl/type. We set PrevDecl to NULL so that the Records
2015 // have distinct types.
2016 PrevDecl = 0;
2017 }
2018 } else {
2019 // PrevDecl is a namespace.
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002020 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002021 // The tag name clashes with a namespace name, issue an error and
2022 // recover by making this tag be anonymous.
2023 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2024 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2025 Name = 0;
2026 }
2027 }
2028 }
2029
2030 // If there is an identifier, use the location of the identifier as the
2031 // location of the decl, otherwise use the location of the struct/union
2032 // keyword.
2033 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2034
2035 // Otherwise, if this is the first time we've seen this tag, create the decl.
2036 TagDecl *New;
2037
2038 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2039 // struct X { int A; } D; D should chain to X.
2040 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002041 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002042 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2043 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2044 else
2045 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2046 dyn_cast_or_null<RecordDecl>(PrevDecl));
2047
2048 // If this has an identifier, add it to the scope stack.
2049 if ((TK == TK_Definition || !PrevDecl) && Name) {
2050 // The scope passed in may not be a decl scope. Zip up the scope tree until
2051 // we find one that is.
2052 while ((S->getFlags() & Scope::DeclScope) == 0)
2053 S = S->getParent();
2054
2055 // Add it to the decl chain.
2056 PushOnScopeChains(New, S);
2057 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002058
2059 // Handle #pragma pack: if the #pragma pack stack has non-default
2060 // alignment, make up a packed attribute for this decl. These
2061 // attributes are checked when the ASTContext lays out the
2062 // structure.
2063 //
2064 // It is important for implementing the correct semantics that this
2065 // happen here (in act on tag decl). The #pragma pack stack is
2066 // maintained as a result of parser callbacks which can occur at
2067 // many points during the parsing of a struct declaration (because
2068 // the #pragma tokens are effectively skipped over during the
2069 // parsing of the struct).
2070 if (unsigned Alignment = PackContext.getAlignment())
2071 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002072
2073 if (Attr)
2074 ProcessDeclAttributeList(New, Attr);
2075
2076 return New;
2077}
2078
2079
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002080/// Collect the instance variables declared in an Objective-C object. Used in
2081/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002082static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002083 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002084 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002085 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2086
2087 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002088 for (ObjCInterfaceDecl::ivar_iterator
2089 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2090
Ted Kremenek01e67792008-08-20 03:26:33 +00002091 ObjCIvarDecl* ID = *I;
2092 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2093 ID->getIdentifier(),
2094 ID->getType(),
2095 ID->getBitWidth()));
2096 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002097}
2098
2099/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2100/// instance variables of ClassName into Decls.
2101void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2102 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002103 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002104 // Check that ClassName is a valid class
2105 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2106 if (!Class) {
2107 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2108 return;
2109 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002110 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002111 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002112}
2113
Eli Friedman1b76ada2008-06-03 21:01:11 +00002114QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
2115 // This method tries to turn a variable array into a constant
2116 // array even when the size isn't an ICE. This is necessary
2117 // for compatibility with code that depends on gcc's buggy
2118 // constant expression folding, like struct {char x[(int)(char*)2];}
2119 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc44eec62008-07-03 04:20:39 +00002120 APValue Result;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002121 if (VLATy->getSizeExpr() &&
Chris Lattnercf0f51d2008-07-11 19:19:21 +00002122 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2123 llvm::APSInt &Res = Result.getInt();
2124 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2125 return Context.getConstantArrayType(VLATy->getElementType(),
2126 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002127 }
2128 }
2129 return QualType();
2130}
2131
Steve Naroff08d92e42007-09-15 18:49:24 +00002132/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002133/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002134Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002135 SourceLocation DeclStart,
2136 Declarator &D, ExprTy *BitfieldWidth) {
2137 IdentifierInfo *II = D.getIdentifier();
2138 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002139 SourceLocation Loc = DeclStart;
2140 if (II) Loc = D.getIdentifierLoc();
2141
2142 // FIXME: Unnamed fields can be handled in various different ways, for
2143 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002144
Reid Spencer5f016e22007-07-11 17:01:13 +00002145 if (BitWidth) {
2146 // TODO: Validate.
2147 //printf("WARNING: BITFIELDS IGNORED!\n");
2148
2149 // 6.7.2.1p3
2150 // 6.7.2.1p4
2151
2152 } else {
2153 // Not a bitfield.
2154
2155 // validate II.
2156
2157 }
2158
2159 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002160 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2161 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002162
Reid Spencer5f016e22007-07-11 17:01:13 +00002163 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2164 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002165 if (T->isVariablyModifiedType()) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002166 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2167 if (!FixedTy.isNull()) {
2168 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2169 T = FixedTy;
2170 } else {
2171 // FIXME: This diagnostic needs work
2172 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2173 InvalidDecl = true;
2174 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002175 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002177 FieldDecl *NewFD;
2178
2179 if (getLangOptions().CPlusPlus) {
2180 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2181 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2182 Loc, II, T, BitWidth);
2183 if (II)
2184 PushOnScopeChains(NewFD, S);
2185 }
2186 else
2187 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002188
Chris Lattner3ff30c82008-06-29 00:02:00 +00002189 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002190
Steve Naroff5912a352007-08-28 20:14:24 +00002191 if (D.getInvalidType() || InvalidDecl)
2192 NewFD->setInvalidDecl();
2193 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002194}
2195
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002196/// TranslateIvarVisibility - Translate visibility from a token ID to an
2197/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002198static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002199TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002200 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002201 default: assert(0 && "Unknown visitibility kind");
2202 case tok::objc_private: return ObjCIvarDecl::Private;
2203 case tok::objc_public: return ObjCIvarDecl::Public;
2204 case tok::objc_protected: return ObjCIvarDecl::Protected;
2205 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002206 }
2207}
2208
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002209/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2210/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002211Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002212 SourceLocation DeclStart,
2213 Declarator &D, ExprTy *BitfieldWidth,
2214 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002215 IdentifierInfo *II = D.getIdentifier();
2216 Expr *BitWidth = (Expr*)BitfieldWidth;
2217 SourceLocation Loc = DeclStart;
2218 if (II) Loc = D.getIdentifierLoc();
2219
2220 // FIXME: Unnamed fields can be handled in various different ways, for
2221 // example, unnamed unions inject all members into the struct namespace!
2222
2223
2224 if (BitWidth) {
2225 // TODO: Validate.
2226 //printf("WARNING: BITFIELDS IGNORED!\n");
2227
2228 // 6.7.2.1p3
2229 // 6.7.2.1p4
2230
2231 } else {
2232 // Not a bitfield.
2233
2234 // validate II.
2235
2236 }
2237
2238 QualType T = GetTypeForDeclarator(D, S);
2239 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2240 bool InvalidDecl = false;
2241
2242 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2243 // than a variably modified type.
2244 if (T->isVariablyModifiedType()) {
2245 // FIXME: This diagnostic needs work
2246 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2247 InvalidDecl = true;
2248 }
2249
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002250 // Get the visibility (access control) for this ivar.
2251 ObjCIvarDecl::AccessControl ac =
2252 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2253 : ObjCIvarDecl::None;
2254
2255 // Construct the decl.
2256 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002257 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002258
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002259 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002260 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002261
2262 if (D.getInvalidType() || InvalidDecl)
2263 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002264
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002265 return NewID;
2266}
2267
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002268void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002269 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002270 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002271 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002272 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002273 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2274 assert(EnclosingDecl && "missing record or interface decl");
2275 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2276
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002277 if (Record)
2278 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2279 // Diagnose code like:
2280 // struct S { struct S {} X; };
2281 // We discover this when we complete the outer S. Reject and ignore the
2282 // outer S.
2283 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2284 DefRecord->getKindName());
2285 Diag(RecLoc, diag::err_previous_definition);
2286 Record->setInvalidDecl();
2287 return;
2288 }
2289
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 // Verify that all the fields are okay.
2291 unsigned NumNamedMembers = 0;
2292 llvm::SmallVector<FieldDecl*, 32> RecFields;
2293 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002294
Reid Spencer5f016e22007-07-11 17:01:13 +00002295 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002296
Steve Naroff74216642007-09-14 22:20:54 +00002297 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2298 assert(FD && "missing field decl");
2299
2300 // Remember all fields.
2301 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002302
2303 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002304 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002305
Reid Spencer5f016e22007-07-11 17:01:13 +00002306 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002307 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002308 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002309 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002310 FD->setInvalidDecl();
2311 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002312 continue;
2313 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002314 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2315 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002316 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002317 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002318 FD->setInvalidDecl();
2319 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002320 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002321 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002322 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002323 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002324 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002325 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002326 FD->setInvalidDecl();
2327 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002328 continue;
2329 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002330 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002331 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2332 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002333 FD->setInvalidDecl();
2334 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002335 continue;
2336 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002337 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002338 if (Record)
2339 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002340 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002341 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2342 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002343 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002344 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2345 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002346 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002347 Record->setHasFlexibleArrayMember(true);
2348 } else {
2349 // If this is a struct/class and this is not the last element, reject
2350 // it. Note that GCC supports variable sized arrays in the middle of
2351 // structures.
2352 if (i != NumFields-1) {
2353 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2354 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002355 FD->setInvalidDecl();
2356 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002357 continue;
2358 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 // We support flexible arrays at the end of structs in other structs
2360 // as an extension.
2361 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2362 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002363 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002364 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002365 }
2366 }
2367 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002368 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002369 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002370 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2371 FD->getName());
2372 FD->setInvalidDecl();
2373 EnclosingDecl->setInvalidDecl();
2374 continue;
2375 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002376 // Keep track of the number of named members.
2377 if (IdentifierInfo *II = FD->getIdentifier()) {
2378 // Detect duplicate member names.
2379 if (!FieldIDs.insert(II)) {
2380 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2381 // Find the previous decl.
2382 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002383 for (unsigned i = 0; ; ++i) {
2384 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002385 if (RecFields[i]->getIdentifier() == II) {
2386 PrevLoc = RecFields[i]->getLocation();
2387 break;
2388 }
2389 }
2390 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002391 FD->setInvalidDecl();
2392 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002393 continue;
2394 }
2395 ++NumNamedMembers;
2396 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002397 }
2398
Reid Spencer5f016e22007-07-11 17:01:13 +00002399 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002400 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002401 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002402 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2403 // Sema::ActOnFinishCXXClassDef.
2404 if (!isa<CXXRecordDecl>(Record))
2405 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002406 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002407 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2408 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2409 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2410 else if (ObjCImplementationDecl *IMPDecl =
2411 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002412 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2413 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002414 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002415 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002416 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002417
2418 if (Attr)
2419 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002420}
2421
Steve Naroff08d92e42007-09-15 18:49:24 +00002422Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002423 DeclTy *lastEnumConst,
2424 SourceLocation IdLoc, IdentifierInfo *Id,
2425 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002426 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 EnumConstantDecl *LastEnumConst =
2428 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2429 Expr *Val = static_cast<Expr*>(val);
2430
Chris Lattner31e05722007-08-26 06:24:45 +00002431 // The scope passed in may not be a decl scope. Zip up the scope tree until
2432 // we find one that is.
2433 while ((S->getFlags() & Scope::DeclScope) == 0)
2434 S = S->getParent();
2435
Reid Spencer5f016e22007-07-11 17:01:13 +00002436 // Verify that there isn't already something declared with this name in this
2437 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002438 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002439 // When in C++, we may get a TagDecl with the same name; in this case the
2440 // enum constant will 'hide' the tag.
2441 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2442 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002443 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002444 if (isa<EnumConstantDecl>(PrevDecl))
2445 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2446 else
2447 Diag(IdLoc, diag::err_redefinition, Id->getName());
2448 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002449 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 return 0;
2451 }
2452 }
2453
2454 llvm::APSInt EnumVal(32);
2455 QualType EltTy;
2456 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002457 // Make sure to promote the operand type to int.
2458 UsualUnaryConversions(Val);
2459
Reid Spencer5f016e22007-07-11 17:01:13 +00002460 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2461 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002462 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002463 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2464 Id->getName());
Chris Lattnera73349d2008-02-26 00:33:57 +00002465 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002466 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002467 } else {
2468 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002469 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002470 }
2471
2472 if (!Val) {
2473 if (LastEnumConst) {
2474 // Assign the last value + 1.
2475 EnumVal = LastEnumConst->getInitVal();
2476 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002477
2478 // Check for overflow on increment.
2479 if (EnumVal < LastEnumConst->getInitVal())
2480 Diag(IdLoc, diag::warn_enum_value_overflow);
2481
Chris Lattnerb7416f92007-08-27 17:37:24 +00002482 EltTy = LastEnumConst->getType();
2483 } else {
2484 // First value, set to zero.
2485 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002486 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002487 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002488 }
2489
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002490 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002491 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2492 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002493 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002494
2495 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002496 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002497 return New;
2498}
2499
Steve Naroff02408c62008-08-07 14:08:16 +00002500// FIXME: For consistency with ActOnFields(), we should have the parser
2501// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002502void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002503 DeclTy **Elements, unsigned NumElements) {
2504 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002505
Steve Naroff02408c62008-08-07 14:08:16 +00002506 if (Enum && Enum->isDefinition()) {
2507 // Diagnose code like:
2508 // enum e0 {
2509 // E0 = sizeof(enum e0 { E1 })
2510 // };
2511 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2512 Enum->getName());
2513 Diag(EnumLoc, diag::err_previous_definition);
2514 Enum->setInvalidDecl();
2515 return;
2516 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002517 // TODO: If the result value doesn't fit in an int, it must be a long or long
2518 // long value. ISO C does not support this, but GCC does as an extension,
2519 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002520 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002521
Chris Lattnerac609682007-08-28 06:15:15 +00002522 // Verify that all the values are okay, compute the size of the values, and
2523 // reverse the list.
2524 unsigned NumNegativeBits = 0;
2525 unsigned NumPositiveBits = 0;
2526
2527 // Keep track of whether all elements have type int.
2528 bool AllElementsInt = true;
2529
Reid Spencer5f016e22007-07-11 17:01:13 +00002530 EnumConstantDecl *EltList = 0;
2531 for (unsigned i = 0; i != NumElements; ++i) {
2532 EnumConstantDecl *ECD =
2533 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2534 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002535
2536 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002537 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002538 assert(InitVal.getBitWidth() >= IntWidth &&
2539 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002540 if (InitVal.getBitWidth() > IntWidth) {
2541 llvm::APSInt V(InitVal);
2542 V.trunc(IntWidth);
2543 V.extend(InitVal.getBitWidth());
2544 if (V != InitVal)
2545 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002546 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002547 }
Chris Lattnerac609682007-08-28 06:15:15 +00002548
2549 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002550 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002551 NumPositiveBits = std::max(NumPositiveBits,
2552 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002553 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002554 NumNegativeBits = std::max(NumNegativeBits,
2555 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002556
Chris Lattnerac609682007-08-28 06:15:15 +00002557 // Keep track of whether every enum element has type int (very commmon).
2558 if (AllElementsInt)
2559 AllElementsInt = ECD->getType() == Context.IntTy;
2560
Reid Spencer5f016e22007-07-11 17:01:13 +00002561 ECD->setNextDeclarator(EltList);
2562 EltList = ECD;
2563 }
2564
Chris Lattnerac609682007-08-28 06:15:15 +00002565 // Figure out the type that should be used for this enum.
2566 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2567 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002568 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00002569
2570 if (NumNegativeBits) {
2571 // If there is a negative value, figure out the smallest integer type (of
2572 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002573 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002574 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002575 BestWidth = IntWidth;
2576 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00002577 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002578
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002579 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002580 BestType = Context.LongTy;
2581 else {
Chris Lattner98be4942008-03-05 18:54:05 +00002582 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00002583
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002584 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00002585 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2586 BestType = Context.LongLongTy;
2587 }
2588 }
2589 } else {
2590 // If there is no negative value, figure out which of uint, ulong, ulonglong
2591 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002592 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00002593 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002594 BestWidth = IntWidth;
2595 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00002596 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00002597 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002598 } else {
2599 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002600 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00002601 "How could an initializer get larger than ULL?");
2602 BestType = Context.UnsignedLongLongTy;
2603 }
2604 }
2605
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002606 // Loop over all of the enumerator constants, changing their types to match
2607 // the type of the enum if needed.
2608 for (unsigned i = 0; i != NumElements; ++i) {
2609 EnumConstantDecl *ECD =
2610 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2611 if (!ECD) continue; // Already issued a diagnostic.
2612
2613 // Standard C says the enumerators have int type, but we allow, as an
2614 // extension, the enumerators to be larger than int size. If each
2615 // enumerator value fits in an int, type it as an int, otherwise type it the
2616 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2617 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00002618 if (ECD->getType() == Context.IntTy) {
2619 // Make sure the init value is signed.
2620 llvm::APSInt IV = ECD->getInitVal();
2621 IV.setIsSigned(true);
2622 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002623 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00002624 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002625
2626 // Determine whether the value fits into an int.
2627 llvm::APSInt InitVal = ECD->getInitVal();
2628 bool FitsInInt;
2629 if (InitVal.isUnsigned() || !InitVal.isNegative())
2630 FitsInInt = InitVal.getActiveBits() < IntWidth;
2631 else
2632 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2633
2634 // If it fits into an integer type, force it. Otherwise force it to match
2635 // the enum decl type.
2636 QualType NewTy;
2637 unsigned NewWidth;
2638 bool NewSign;
2639 if (FitsInInt) {
2640 NewTy = Context.IntTy;
2641 NewWidth = IntWidth;
2642 NewSign = true;
2643 } else if (ECD->getType() == BestType) {
2644 // Already the right type!
2645 continue;
2646 } else {
2647 NewTy = BestType;
2648 NewWidth = BestWidth;
2649 NewSign = BestType->isSignedIntegerType();
2650 }
2651
2652 // Adjust the APSInt value.
2653 InitVal.extOrTrunc(NewWidth);
2654 InitVal.setIsSigned(NewSign);
2655 ECD->setInitVal(InitVal);
2656
2657 // Adjust the Expr initializer and type.
2658 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2659 ECD->setType(NewTy);
2660 }
Chris Lattnerac609682007-08-28 06:15:15 +00002661
Chris Lattnere00b18c2007-08-28 18:24:31 +00002662 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00002663 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00002664}
2665
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002666Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2667 ExprTy *expr) {
2668 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2669
Chris Lattner8e25d862008-03-16 00:16:02 +00002670 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00002671}
2672
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002673Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00002674 SourceLocation LBrace,
2675 SourceLocation RBrace,
2676 const char *Lang,
2677 unsigned StrSize,
2678 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002679 LinkageSpecDecl::LanguageIDs Language;
2680 Decl *dcl = static_cast<Decl *>(D);
2681 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2682 Language = LinkageSpecDecl::lang_c;
2683 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2684 Language = LinkageSpecDecl::lang_cxx;
2685 else {
2686 Diag(Loc, diag::err_bad_language);
2687 return 0;
2688 }
2689
2690 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00002691 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00002692}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00002693
2694void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
2695 ExprTy *alignment, SourceLocation PragmaLoc,
2696 SourceLocation LParenLoc, SourceLocation RParenLoc) {
2697 Expr *Alignment = static_cast<Expr *>(alignment);
2698
2699 // If specified then alignment must be a "small" power of two.
2700 unsigned AlignmentVal = 0;
2701 if (Alignment) {
2702 llvm::APSInt Val;
2703 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
2704 !Val.isPowerOf2() ||
2705 Val.getZExtValue() > 16) {
2706 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
2707 delete Alignment;
2708 return; // Ignore
2709 }
2710
2711 AlignmentVal = (unsigned) Val.getZExtValue();
2712 }
2713
2714 switch (Kind) {
2715 case Action::PPK_Default: // pack([n])
2716 PackContext.setAlignment(AlignmentVal);
2717 break;
2718
2719 case Action::PPK_Show: // pack(show)
2720 // Show the current alignment, making sure to show the right value
2721 // for the default.
2722 AlignmentVal = PackContext.getAlignment();
2723 // FIXME: This should come from the target.
2724 if (AlignmentVal == 0)
2725 AlignmentVal = 8;
2726 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
2727 break;
2728
2729 case Action::PPK_Push: // pack(push [, id] [, [n])
2730 PackContext.push(Name);
2731 // Set the new alignment if specified.
2732 if (Alignment)
2733 PackContext.setAlignment(AlignmentVal);
2734 break;
2735
2736 case Action::PPK_Pop: // pack(pop [, id] [, n])
2737 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
2738 // "#pragma pack(pop, identifier, n) is undefined"
2739 if (Alignment && Name)
2740 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
2741
2742 // Do the pop.
2743 if (!PackContext.pop(Name)) {
2744 // If a name was specified then failure indicates the name
2745 // wasn't found. Otherwise failure indicates the stack was
2746 // empty.
2747 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
2748 Name ? "no record matching name" : "stack empty");
2749
2750 // FIXME: Warn about popping named records as MSVC does.
2751 } else {
2752 // Pop succeeded, set the new alignment if specified.
2753 if (Alignment)
2754 PackContext.setAlignment(AlignmentVal);
2755 }
2756 break;
2757
2758 default:
2759 assert(0 && "Invalid #pragma pack kind.");
2760 }
2761}
2762
2763bool PragmaPackStack::pop(IdentifierInfo *Name) {
2764 if (Stack.empty())
2765 return false;
2766
2767 // If name is empty just pop top.
2768 if (!Name) {
2769 Alignment = Stack.back().first;
2770 Stack.pop_back();
2771 return true;
2772 }
2773
2774 // Otherwise, find the named record.
2775 for (unsigned i = Stack.size(); i != 0; ) {
2776 --i;
2777 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
2778 // Found it, pop up to and including this record.
2779 Alignment = Stack[i].first;
2780 Stack.erase(Stack.begin() + i, Stack.end());
2781 return true;
2782 }
2783 }
2784
2785 return false;
2786}