blob: c8c253a3fba56185623de6fd66b7541a6ddad117 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-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 Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Daniel Dunbar81c7d472008-10-14 05:35:18 +000028#include "llvm/ADT/StringExtras.h"
Chris Lattner4b009652007-07-25 00:24:17 +000029using namespace clang;
30
Argiris Kirtzidis46403632008-08-01 10:35:27 +000031Sema::TypeTy *Sema::isTypeName(const IdentifierInfo &II, Scope *S) {
Steve Naroff6384a012008-04-02 14:35:35 +000032 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, false);
33
Douglas Gregor1d661552008-04-13 21:07:44 +000034 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
35 isa<ObjCInterfaceDecl>(IIDecl) ||
36 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000037 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000038 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000039}
40
Argiris Kirtzidis38f16712008-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 Lattneref87a202008-04-22 18:39:57 +000064void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000065 assert(getDCParent(DC) == CurContext &&
66 "The next DeclContext should be directly contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000067 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000068}
69
Chris Lattnerf3874bc2008-04-06 04:47:34 +000070void Sema::PopDeclContext() {
71 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000072 CurContext = getDCParent(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000073}
74
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000075/// Add this decl to the scope shadowed decl chains.
76void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000077 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-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).
Argiris Kirtzidis94805232008-07-17 17:49:50 +000087 IdentifierResolver::iterator
88 I = IdResolver.begin(TD->getIdentifier(),
89 TD->getDeclContext(), false/*LookInParentCtx*/);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +000090 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-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
Argiris Kirtzidis94805232008-07-17 17:49:50 +000095 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000096 return;
97 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +000098 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
99 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000100 // We are pushing the name of a function, which might be an
101 // overloaded name.
102 IdentifierResolver::iterator
103 I = IdResolver.begin(FD->getIdentifier(),
104 FD->getDeclContext(), false/*LookInParentCtx*/);
105 if (I != IdResolver.end() &&
106 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
107 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
108 // There is already a declaration with the same name in the same
109 // scope. It must be a function or an overloaded function.
110 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
111 if (!Ovl) {
112 // We haven't yet overloaded this function. Take the existing
113 // FunctionDecl and put it into an OverloadedFunctionDecl.
114 Ovl = OverloadedFunctionDecl::Create(Context,
115 FD->getDeclContext(),
116 FD->getIdentifier());
117 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
118
119 // Remove the name binding to the existing FunctionDecl...
120 IdResolver.RemoveDecl(*I);
121
122 // ... and put the OverloadedFunctionDecl in its place.
123 IdResolver.AddDecl(Ovl);
124 }
125
126 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
127 // to its list of overloads.
128 Ovl->addOverload(FD);
129
130 return;
131 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000132 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000133
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000134 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000135}
136
Steve Naroff9637a9b2007-10-09 22:01:59 +0000137void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000138 if (S->decl_empty()) return;
139 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000140
Chris Lattner4b009652007-07-25 00:24:17 +0000141 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
142 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000143 Decl *TmpD = static_cast<Decl*>(*I);
144 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000145
146 if (isa<CXXFieldDecl>(TmpD)) continue;
147
148 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
149 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000150
Chris Lattner4b009652007-07-25 00:24:17 +0000151 IdentifierInfo *II = D->getIdentifier();
152 if (!II) continue;
153
Ted Kremenek40e70e72008-09-03 18:03:35 +0000154 // We only want to remove the decls from the identifier decl chains for
155 // local scopes, when inside a function/method.
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000156 if (S->getFnParent() != 0)
157 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000158
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000159 // Chain this decl to the containing DeclContext.
160 D->setNext(CurContext->getDeclChain());
161 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000162 }
163}
164
Steve Naroffe57c21a2008-04-01 23:04:06 +0000165/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
166/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000167ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000168 // The third "scope" argument is 0 since we aren't enabling lazy built-in
169 // creation from this context.
170 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000171
Steve Naroff6384a012008-04-02 14:35:35 +0000172 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000173}
174
Steve Naroffe57c21a2008-04-01 23:04:06 +0000175/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000176/// namespace.
Steve Naroff6384a012008-04-02 14:35:35 +0000177Decl *Sema::LookupDecl(const IdentifierInfo *II, unsigned NSI,
178 Scope *S, bool enableLazyBuiltinCreation) {
Chris Lattner4b009652007-07-25 00:24:17 +0000179 if (II == 0) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000180 unsigned NS = NSI;
181 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
182 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000183
Chris Lattner4b009652007-07-25 00:24:17 +0000184 // Scan up the scope chain looking for a decl that matches this identifier
185 // that is in the appropriate namespace. This search should not take long, as
186 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000187 for (IdentifierResolver::iterator
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000188 I = IdResolver.begin(II, CurContext), E = IdResolver.end(); I != E; ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000189 if ((*I)->getIdentifierNamespace() & NS)
190 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000191
Chris Lattner4b009652007-07-25 00:24:17 +0000192 // If we didn't find a use of this identifier, and if the identifier
193 // corresponds to a compiler builtin, create the decl object for the builtin
194 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000195 if (NS & Decl::IDNS_Ordinary) {
Steve Naroff6384a012008-04-02 14:35:35 +0000196 if (enableLazyBuiltinCreation) {
197 // If this is a builtin on this (or all) targets, create the decl.
198 if (unsigned BuiltinID = II->getBuiltinID())
199 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
200 }
Steve Naroffe57c21a2008-04-01 23:04:06 +0000201 if (getLangOptions().ObjC1) {
202 // @interface and @compatibility_alias introduce typedef-like names.
203 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000204 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000205 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000206 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
207 if (IDI != ObjCInterfaceDecls.end())
208 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000209 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
210 if (I != ObjCAliasDecls.end())
211 return I->second->getClassInterface();
212 }
Chris Lattner4b009652007-07-25 00:24:17 +0000213 }
214 return 0;
215}
216
Chris Lattnera9c87f22008-05-05 22:18:14 +0000217void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000218 if (!Context.getBuiltinVaListType().isNull())
219 return;
220
221 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000222 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000223 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000224 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
225}
226
Chris Lattner4b009652007-07-25 00:24:17 +0000227/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
228/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000229ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
230 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000231 Builtin::ID BID = (Builtin::ID)bid;
232
Chris Lattnerb23469f2008-09-28 05:54:29 +0000233 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000234 InitBuiltinVaListType();
235
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000236 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000237 FunctionDecl *New = FunctionDecl::Create(Context,
238 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000239 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000240 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000241
Chris Lattnera9c87f22008-05-05 22:18:14 +0000242 // Create Decl objects for each parameter, adding them to the
243 // FunctionDecl.
244 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
245 llvm::SmallVector<ParmVarDecl*, 16> Params;
246 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
247 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
248 FT->getArgType(i), VarDecl::None, 0,
249 0));
250 New->setParams(&Params[0], Params.size());
251 }
252
253
254
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000255 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000256 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000257 return New;
258}
259
260/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
261/// and scope as a previous declaration 'Old'. Figure out how to resolve this
262/// situation, merging decls or emitting diagnostics as appropriate.
263///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000264TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000265 // Allow multiple definitions for ObjC built-in typedefs.
266 // FIXME: Verify the underlying types are equivalent!
267 if (getLangOptions().ObjC1) {
268 const IdentifierInfo *typeIdent = New->getIdentifier();
269 if (typeIdent == Ident_id) {
270 Context.setObjCIdType(New);
271 return New;
272 } else if (typeIdent == Ident_Class) {
273 Context.setObjCClassType(New);
274 return New;
275 } else if (typeIdent == Ident_SEL) {
276 Context.setObjCSelType(New);
277 return New;
278 } else if (typeIdent == Ident_Protocol) {
279 Context.setObjCProtoType(New->getUnderlyingType());
280 return New;
281 }
282 // Fall through - the typedef name was not a builtin type.
283 }
Chris Lattner4b009652007-07-25 00:24:17 +0000284 // Verify the old decl was also a typedef.
285 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
286 if (!Old) {
287 Diag(New->getLocation(), diag::err_redefinition_different_kind,
288 New->getName());
289 Diag(OldD->getLocation(), diag::err_previous_definition);
290 return New;
291 }
292
Chris Lattnerbef8d622008-07-25 18:44:27 +0000293 // If the typedef types are not identical, reject them in all languages and
294 // with any extensions enabled.
295 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
296 Context.getCanonicalType(Old->getUnderlyingType()) !=
297 Context.getCanonicalType(New->getUnderlyingType())) {
298 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
299 New->getUnderlyingType().getAsString(),
300 Old->getUnderlyingType().getAsString());
301 Diag(Old->getLocation(), diag::err_previous_definition);
302 return Old;
303 }
304
Eli Friedman324d5032008-06-11 06:20:39 +0000305 if (getLangOptions().Microsoft) return New;
306
Steve Naroffa9eae582008-01-30 23:46:05 +0000307 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
308 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
309 // *either* declaration is in a system header. The code below implements
310 // this adhoc compatibility rule. FIXME: The following code will not
311 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000312 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
313 SourceManager &SrcMgr = Context.getSourceManager();
314 if (SrcMgr.isInSystemHeader(Old->getLocation()))
315 return New;
316 if (SrcMgr.isInSystemHeader(New->getLocation()))
317 return New;
318 }
Eli Friedman324d5032008-06-11 06:20:39 +0000319
Ted Kremenek64845ce2008-05-23 21:28:18 +0000320 Diag(New->getLocation(), diag::err_redefinition, New->getName());
321 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000322 return New;
323}
324
Chris Lattner6953a072008-06-26 18:38:35 +0000325/// DeclhasAttr - returns true if decl Declaration already has the target
326/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000327static bool DeclHasAttr(const Decl *decl, const Attr *target) {
328 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
329 if (attr->getKind() == target->getKind())
330 return true;
331
332 return false;
333}
334
335/// MergeAttributes - append attributes from the Old decl to the New one.
336static void MergeAttributes(Decl *New, Decl *Old) {
337 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
338
Chris Lattner402b3372008-03-03 03:28:21 +0000339 while (attr) {
340 tmp = attr;
341 attr = attr->getNext();
342
343 if (!DeclHasAttr(New, tmp)) {
344 New->addAttr(tmp);
345 } else {
346 tmp->setNext(0);
347 delete(tmp);
348 }
349 }
Nuno Lopes77654342008-06-01 22:53:53 +0000350
351 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000352}
353
Chris Lattner3e254fb2008-04-08 04:40:51 +0000354/// MergeFunctionDecl - We just parsed a function 'New' from
355/// declarator D which has the same name and scope as a previous
356/// declaration 'Old'. Figure out how to resolve this situation,
357/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000358/// Redeclaration will be set true if this New is a redeclaration OldD.
359///
360/// In C++, New and Old must be declarations that are not
361/// overloaded. Use IsOverload to determine whether New and Old are
362/// overloaded, and to select the Old declaration that New should be
363/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000364FunctionDecl *
365Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000366 assert(!isa<OverloadedFunctionDecl>(OldD) &&
367 "Cannot merge with an overloaded function declaration");
368
Douglas Gregor42214c52008-04-21 02:02:58 +0000369 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000370 // Verify the old decl was also a function.
371 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
372 if (!Old) {
373 Diag(New->getLocation(), diag::err_redefinition_different_kind,
374 New->getName());
375 Diag(OldD->getLocation(), diag::err_previous_definition);
376 return New;
377 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000378
379 // Determine whether the previous declaration was a definition,
380 // implicit declaration, or a declaration.
381 diag::kind PrevDiag;
382 if (Old->isThisDeclarationADefinition())
383 PrevDiag = diag::err_previous_definition;
384 else if (Old->isImplicit())
385 PrevDiag = diag::err_previous_implicit_declaration;
386 else
387 PrevDiag = diag::err_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000388
Chris Lattner42a21742008-04-06 23:10:54 +0000389 QualType OldQType = Context.getCanonicalType(Old->getType());
390 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000391
Douglas Gregord2baafd2008-10-21 16:13:35 +0000392 if (getLangOptions().CPlusPlus) {
393 // (C++98 13.1p2):
394 // Certain function declarations cannot be overloaded:
395 // -- Function declarations that differ only in the return type
396 // cannot be overloaded.
397 QualType OldReturnType
398 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
399 QualType NewReturnType
400 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
401 if (OldReturnType != NewReturnType) {
402 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
403 Diag(Old->getLocation(), PrevDiag);
404 return New;
405 }
406
407 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
408 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
409 if (OldMethod && NewMethod) {
410 // -- Member function declarations with the same name and the
411 // same parameter types cannot be overloaded if any of them
412 // is a static member function declaration.
413 if (OldMethod->isStatic() || NewMethod->isStatic()) {
414 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
415 Diag(Old->getLocation(), PrevDiag);
416 return New;
417 }
418 }
419
420 // (C++98 8.3.5p3):
421 // All declarations for a function shall agree exactly in both the
422 // return type and the parameter-type-list.
423 if (OldQType == NewQType) {
424 // We have a redeclaration.
425 MergeAttributes(New, Old);
426 Redeclaration = true;
427 return MergeCXXFunctionDecl(New, Old);
428 }
429
430 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000431 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000432
433 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000434 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000435 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000436 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000437 MergeAttributes(New, Old);
438 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000439 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000440 }
Chris Lattner1470b072007-11-06 06:07:26 +0000441
Steve Naroff6c9e7922008-01-16 15:01:34 +0000442 // A function that has already been declared has been redeclared or defined
443 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000444
Chris Lattner4b009652007-07-25 00:24:17 +0000445 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
446 // TODO: This is totally simplistic. It should handle merging functions
447 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000448 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
449 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000450 return New;
451}
452
Steve Naroffb5e78152008-08-08 17:50:35 +0000453/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000454static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000455 if (VD->isFileVarDecl())
456 return (!VD->getInit() &&
457 (VD->getStorageClass() == VarDecl::None ||
458 VD->getStorageClass() == VarDecl::Static));
459 return false;
460}
461
462/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
463/// when dealing with C "tentative" external object definitions (C99 6.9.2).
464void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
465 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000466 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000467
468 for (IdentifierResolver::iterator
469 I = IdResolver.begin(VD->getIdentifier(),
470 VD->getDeclContext(), false/*LookInParentCtx*/),
471 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000472 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000473 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
474
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000475 // Handle the following case:
476 // int a[10];
477 // int a[]; - the code below makes sure we set the correct type.
478 // int a[11]; - this is an error, size isn't 10.
479 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
480 OldDecl->getType()->isConstantArrayType())
481 VD->setType(OldDecl->getType());
482
Steve Naroffb5e78152008-08-08 17:50:35 +0000483 // Check for "tentative" definitions. We can't accomplish this in
484 // MergeVarDecl since the initializer hasn't been attached.
485 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
486 continue;
487
488 // Handle __private_extern__ just like extern.
489 if (OldDecl->getStorageClass() != VarDecl::Extern &&
490 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
491 VD->getStorageClass() != VarDecl::Extern &&
492 VD->getStorageClass() != VarDecl::PrivateExtern) {
493 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
494 Diag(OldDecl->getLocation(), diag::err_previous_definition);
495 }
496 }
497 }
498}
499
Chris Lattner4b009652007-07-25 00:24:17 +0000500/// MergeVarDecl - We just parsed a variable 'New' which has the same name
501/// and scope as a previous declaration 'Old'. Figure out how to resolve this
502/// situation, merging decls or emitting diagnostics as appropriate.
503///
Steve Naroffb5e78152008-08-08 17:50:35 +0000504/// Tentative definition rules (C99 6.9.2p2) are checked by
505/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
506/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000507///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000508VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000509 // Verify the old decl was also a variable.
510 VarDecl *Old = dyn_cast<VarDecl>(OldD);
511 if (!Old) {
512 Diag(New->getLocation(), diag::err_redefinition_different_kind,
513 New->getName());
514 Diag(OldD->getLocation(), diag::err_previous_definition);
515 return New;
516 }
Chris Lattner402b3372008-03-03 03:28:21 +0000517
518 MergeAttributes(New, Old);
519
Chris Lattner4b009652007-07-25 00:24:17 +0000520 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000521 QualType OldCType = Context.getCanonicalType(Old->getType());
522 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000523 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000524 Diag(New->getLocation(), diag::err_redefinition, New->getName());
525 Diag(Old->getLocation(), diag::err_previous_definition);
526 return New;
527 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000528 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
529 if (New->getStorageClass() == VarDecl::Static &&
530 (Old->getStorageClass() == VarDecl::None ||
531 Old->getStorageClass() == VarDecl::Extern)) {
532 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
533 Diag(Old->getLocation(), diag::err_previous_definition);
534 return New;
535 }
536 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
537 if (New->getStorageClass() != VarDecl::Static &&
538 Old->getStorageClass() == VarDecl::Static) {
539 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
540 Diag(Old->getLocation(), diag::err_previous_definition);
541 return New;
542 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000543 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
544 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000545 Diag(New->getLocation(), diag::err_redefinition, New->getName());
546 Diag(Old->getLocation(), diag::err_previous_definition);
547 }
548 return New;
549}
550
Chris Lattner3e254fb2008-04-08 04:40:51 +0000551/// CheckParmsForFunctionDef - Check that the parameters of the given
552/// function are appropriate for the definition of a function. This
553/// takes care of any checks that cannot be performed on the
554/// declaration itself, e.g., that the types of each of the function
555/// parameters are complete.
556bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
557 bool HasInvalidParm = false;
558 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
559 ParmVarDecl *Param = FD->getParamDecl(p);
560
561 // C99 6.7.5.3p4: the parameters in a parameter type list in a
562 // function declarator that is part of a function definition of
563 // that function shall not have incomplete type.
564 if (Param->getType()->isIncompleteType() &&
565 !Param->isInvalidDecl()) {
566 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
567 Param->getType().getAsString());
568 Param->setInvalidDecl();
569 HasInvalidParm = true;
570 }
571 }
572
573 return HasInvalidParm;
574}
575
Chris Lattner4b009652007-07-25 00:24:17 +0000576/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
577/// no declarator (e.g. "struct foo;") is parsed.
578Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
579 // TODO: emit error on 'int;' or 'const enum foo;'.
580 // TODO: emit error on 'typedef int;'
581 // if (!DS.isMissingDeclaratorOk()) Diag(...);
582
Steve Naroffedafc0b2007-11-17 21:37:36 +0000583 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000584}
585
Steve Narofff0b23542008-01-10 22:15:12 +0000586bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000587 // Get the type before calling CheckSingleAssignmentConstraints(), since
588 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000589 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000590
Chris Lattner005ed752008-01-04 18:04:52 +0000591 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
592 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
593 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000594}
595
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000596bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000597 const ArrayType *AT = Context.getAsArrayType(DeclT);
598
599 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000600 // C99 6.7.8p14. We have an array of character type with unknown size
601 // being initialized to a string literal.
602 llvm::APSInt ConstVal(32);
603 ConstVal = strLiteral->getByteLength() + 1;
604 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000605 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000606 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000607 } else {
608 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000609 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000610 // FIXME: Avoid truncation for 64-bit length strings.
611 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000612 Diag(strLiteral->getSourceRange().getBegin(),
613 diag::warn_initializer_string_for_char_array_too_long,
614 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000615 }
616 // Set type from "char *" to "constant array of char".
617 strLiteral->setType(DeclT);
618 // For now, we always return false (meaning success).
619 return false;
620}
621
622StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000623 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000624 if (AT && AT->getElementType()->isCharType()) {
625 return dyn_cast<StringLiteral>(Init);
626 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000627 return 0;
628}
629
Douglas Gregor6428e762008-11-05 15:29:30 +0000630bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
631 SourceLocation InitLoc,
632 std::string InitEntity) {
Douglas Gregor81c29152008-10-29 00:13:59 +0000633 // C++ [dcl.init.ref]p1:
634 // A variable declared to be a T&, that is “reference to type T”
635 // (8.3.2), shall be initialized by an object, or function, of
636 // type T or by an object that can be converted into a T.
637 if (DeclType->isReferenceType())
638 return CheckReferenceInit(Init, DeclType);
639
Steve Naroff8e9337f2008-01-21 23:53:58 +0000640 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
641 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000642 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregor6428e762008-11-05 15:29:30 +0000643 return Diag(InitLoc,
Steve Naroff8e9337f2008-01-21 23:53:58 +0000644 diag::err_variable_object_no_init,
645 VAT->getSizeExpr()->getSourceRange());
646
Steve Naroffcb69fb72007-12-10 22:44:33 +0000647 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
648 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000649 // FIXME: Handle wide strings
650 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
651 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000652
Douglas Gregor6428e762008-11-05 15:29:30 +0000653 // C++ [dcl.init]p14:
654 // -- If the destination type is a (possibly cv-qualified) class
655 // type:
656 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
657 QualType DeclTypeC = Context.getCanonicalType(DeclType);
658 QualType InitTypeC = Context.getCanonicalType(Init->getType());
659
660 // -- If the initialization is direct-initialization, or if it is
661 // copy-initialization where the cv-unqualified version of the
662 // source type is the same class as, or a derived class of, the
663 // class of the destination, constructors are considered.
664 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
665 IsDerivedFrom(InitTypeC, DeclTypeC)) {
666 CXXConstructorDecl *Constructor
667 = PerformInitializationByConstructor(DeclType, &Init, 1,
668 InitLoc, Init->getSourceRange(),
669 InitEntity, IK_Copy);
670 return Constructor == 0;
671 }
672
673 // -- Otherwise (i.e., for the remaining copy-initialization
674 // cases), user-defined conversion sequences that can
675 // convert from the source type to the destination type or
676 // (when a conversion function is used) to a derived class
677 // thereof are enumerated as described in 13.3.1.4, and the
678 // best one is chosen through overload resolution
679 // (13.3). If the conversion cannot be done or is
680 // ambiguous, the initialization is ill-formed. The
681 // function selected is called with the initializer
682 // expression as its argument; if the function is a
683 // constructor, the call initializes a temporary of the
684 // destination type.
685 // FIXME: We're pretending to do copy elision here; return to
686 // this when we have ASTs for such things.
687 if (PerformImplicitConversion(Init, DeclType))
688 return Diag(InitLoc,
689 diag::err_typecheck_convert_incompatible,
690 DeclType.getAsString(), InitEntity,
691 "initializing",
692 Init->getSourceRange());
693 else
694 return false;
695 }
696
Steve Naroffb2f72412008-09-29 20:07:05 +0000697 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000698 if (DeclType->isArrayType())
699 return Diag(Init->getLocStart(),
700 diag::err_array_init_list_required,
701 Init->getSourceRange());
702
Steve Narofff0b23542008-01-10 22:15:12 +0000703 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +0000704 } else if (getLangOptions().CPlusPlus) {
705 // C++ [dcl.init]p14:
706 // [...] If the class is an aggregate (8.5.1), and the initializer
707 // is a brace-enclosed list, see 8.5.1.
708 //
709 // Note: 8.5.1 is handled below; here, we diagnose the case where
710 // we have an initializer list and a destination type that is not
711 // an aggregate.
712 // FIXME: In C++0x, this is yet another form of initialization.
713 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
714 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
715 if (!ClassDecl->isAggregate())
716 return Diag(InitLoc,
717 diag::err_init_non_aggr_init_list,
718 DeclType.getAsString(),
719 Init->getSourceRange());
720 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000721 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000722
Steve Naroffc4d4a482008-05-01 22:18:59 +0000723 InitListChecker CheckInitList(this, InitList, DeclType);
724 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000725}
726
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000727Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000728Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000729 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000730 IdentifierInfo *II = D.getIdentifier();
731
732 // All of these full declarators require an identifier. If it doesn't have
733 // one, the ParsedFreeStandingDeclSpec action should be used.
734 if (II == 0) {
Chris Lattner6fe8b272007-10-16 22:36:42 +0000735 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner87492f42007-08-28 06:17:15 +0000736 diag::err_declarator_need_ident,
Chris Lattner4b009652007-07-25 00:24:17 +0000737 D.getDeclSpec().getSourceRange(), D.getSourceRange());
738 return 0;
739 }
740
Chris Lattnera7549902007-08-26 06:24:45 +0000741 // The scope passed in may not be a decl scope. Zip up the scope tree until
742 // we find one that is.
743 while ((S->getFlags() & Scope::DeclScope) == 0)
744 S = S->getParent();
745
Chris Lattner4b009652007-07-25 00:24:17 +0000746 // See if this is a redefinition of a variable in the same scope.
Steve Naroff6384a012008-04-02 14:35:35 +0000747 Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000748 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000749 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000750
751 // In C++, the previous declaration we find might be a tag type
752 // (class or enum). In this case, the new declaration will hide the
753 // tag type.
754 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
755 PrevDecl = 0;
756
Chris Lattner82bb4792007-11-14 06:34:38 +0000757 QualType R = GetTypeForDeclarator(D, S);
758 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
759
Chris Lattner4b009652007-07-25 00:24:17 +0000760 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000761 // Check that there are no default arguments (C++ only).
762 if (getLangOptions().CPlusPlus)
763 CheckExtraCXXDefaultArguments(D);
764
Chris Lattner82bb4792007-11-14 06:34:38 +0000765 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000766 if (!NewTD) return 0;
767
768 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000769 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000770 // Merge the decl with the existing one if appropriate. If the decl is
771 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000772 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000773 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
774 if (NewTD == 0) return 0;
775 }
776 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000777 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000778 // C99 6.7.7p2: If a typedef name specifies a variably modified type
779 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000780 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
781 // FIXME: Diagnostic needs to be fixed.
782 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000783 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000784 }
785 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000786 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000787 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000788 switch (D.getDeclSpec().getStorageClassSpec()) {
789 default: assert(0 && "Unknown storage class!");
790 case DeclSpec::SCS_auto:
791 case DeclSpec::SCS_register:
792 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
793 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000794 InvalidDecl = true;
795 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000796 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
797 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
798 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000799 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000800 }
801
Chris Lattner4c7802b2008-03-15 21:24:04 +0000802 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000803 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
804 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
805
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000806 FunctionDecl *NewFD;
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000807 if (isCurrentClassName(*II, S)) {
808 // This is a C++ constructor declaration.
809 assert(D.getContext() == Declarator::MemberContext &&
810 "Constructors can only be declared in a member context");
811
812 // C++ [class.ctor]p3:
813 // A constructor shall not be virtual (10.3) or static (9.4). A
814 // constructor can be invoked for a const, volatile or const
815 // volatile object. A constructor shall not be declared const,
816 // volatile, or const volatile (9.3.2).
817 if (isVirtual) {
818 Diag(D.getIdentifierLoc(),
819 diag::err_constructor_cannot_be,
820 "virtual",
821 SourceRange(D.getDeclSpec().getVirtualSpecLoc()),
822 SourceRange(D.getIdentifierLoc()));
823 isVirtual = false;
824 }
825 if (SC == FunctionDecl::Static) {
826 Diag(D.getIdentifierLoc(),
827 diag::err_constructor_cannot_be,
828 "static",
829 SourceRange(D.getDeclSpec().getStorageClassSpecLoc()),
830 SourceRange(D.getIdentifierLoc()));
831 isVirtual = false;
832 }
833 if (D.getDeclSpec().hasTypeSpecifier()) {
834 // Constructors don't have return types, but the parser will
835 // happily parse something like:
836 //
837 // class X {
838 // float X(float);
839 // };
840 //
841 // The return type will be eliminated later.
842 Diag(D.getIdentifierLoc(),
843 diag::err_constructor_return_type,
844 SourceRange(D.getDeclSpec().getTypeSpecTypeLoc()),
845 SourceRange(D.getIdentifierLoc()));
846 }
847 if (R->getAsFunctionTypeProto()->getTypeQuals() != 0) {
848 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
849 if (FTI.TypeQuals & QualType::Const)
850 Diag(D.getIdentifierLoc(),
851 diag::err_invalid_qualified_constructor,
852 "const",
853 SourceRange(D.getIdentifierLoc()));
854 if (FTI.TypeQuals & QualType::Volatile)
855 Diag(D.getIdentifierLoc(),
856 diag::err_invalid_qualified_constructor,
857 "volatile",
858 SourceRange(D.getIdentifierLoc()));
859 if (FTI.TypeQuals & QualType::Restrict)
860 Diag(D.getIdentifierLoc(),
861 diag::err_invalid_qualified_constructor,
862 "restrict",
863 SourceRange(D.getIdentifierLoc()));
864 }
865
866 // Rebuild the function type "R" without any type qualifiers (in
867 // case any of the errors above fired) and with "void" as the
868 // return type, since constructors don't have return types. We
869 // *always* have to do this, because GetTypeForDeclarator will
870 // put in a result type of "int" when none was specified.
871 const FunctionTypeProto *Proto = R->getAsFunctionTypeProto();
872 R = Context.getFunctionType(Context.VoidTy, Proto->arg_type_begin(),
873 Proto->getNumArgs(),
874 Proto->isVariadic(),
875 0);
876
877 // Create the new declaration
878 NewFD = CXXConstructorDecl::Create(Context,
879 cast<CXXRecordDecl>(CurContext),
880 D.getIdentifierLoc(), II, R,
881 isExplicit, isInline,
882 /*isImplicitlyDeclared=*/false);
883
884 } else if (D.getContext() == Declarator::MemberContext) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000885 // This is a C++ method declaration.
886 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
887 D.getIdentifierLoc(), II, R,
888 (SC == FunctionDecl::Static), isInline,
889 LastDeclarator);
890 } else {
891 NewFD = FunctionDecl::Create(Context, CurContext,
892 D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000893 II, R, SC, isInline, LastDeclarator,
894 // FIXME: Move to DeclGroup...
895 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000896 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000897 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000898 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000899
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000900 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000901 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000902 // The parser guarantees this is a string.
903 StringLiteral *SE = cast<StringLiteral>(E);
904 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
905 SE->getByteLength())));
906 }
907
Chris Lattner3e254fb2008-04-08 04:40:51 +0000908 // Copy the parameter declarations from the declarator D to
909 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000910 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000911 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
912
913 // Create Decl objects for each parameter, adding them to the
914 // FunctionDecl.
915 llvm::SmallVector<ParmVarDecl*, 16> Params;
916
917 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
918 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000919 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000920 // We let through "const void" here because Sema::GetTypeForDeclarator
921 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000922 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
923 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000924 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
925 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000926 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
927
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000928 // In C++, the empty parameter-type-list must be spelled "void"; a
929 // typedef of void is not permitted.
930 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000931 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000932 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
933 }
Eli Friedman769e7302008-08-25 21:31:01 +0000934 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000935 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
936 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
937 }
938
939 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +0000940 } else if (R->getAsTypedefType()) {
941 // When we're declaring a function with a typedef, as in the
942 // following example, we'll need to synthesize (unnamed)
943 // parameters for use in the declaration.
944 //
945 // @code
946 // typedef void fn(int);
947 // fn f;
948 // @endcode
949 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
950 if (!FT) {
951 // This is a typedef of a function with no prototype, so we
952 // don't need to do anything.
953 } else if ((FT->getNumArgs() == 0) ||
954 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
955 FT->getArgType(0)->isVoidType())) {
956 // This is a zero-argument function. We don't need to do anything.
957 } else {
958 // Synthesize a parameter for each argument type.
959 llvm::SmallVector<ParmVarDecl*, 16> Params;
960 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
961 ArgType != FT->arg_type_end(); ++ArgType) {
962 Params.push_back(ParmVarDecl::Create(Context, CurContext,
963 SourceLocation(), 0,
964 *ArgType, VarDecl::None,
965 0, 0));
966 }
967
968 NewFD->setParams(&Params[0], Params.size());
969 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000970 }
971
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000972 // C++ constructors are handled by a separate routine, since they
973 // don't require any declaration merging (C++ [class.mfct]p2) and
974 // they aren't ever pushed into scope, because they can't be found
975 // by name lookup anyway (C++ [class.ctor]p2).
976 if (CXXConstructorDecl *ConDecl = dyn_cast<CXXConstructorDecl>(NewFD))
977 return ActOnConstructorDeclarator(ConDecl);
978
Steve Narofff8a09432008-01-09 23:34:55 +0000979 // Merge the decl with the existing one if appropriate. Since C functions
980 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000981 if (PrevDecl &&
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000982 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000983 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000984
985 // If C++, determine whether NewFD is an overload of PrevDecl or
986 // a declaration that requires merging. If it's an overload,
987 // there's no more work to do here; we'll just add the new
988 // function to the scope.
989 OverloadedFunctionDecl::function_iterator MatchedDecl;
990 if (!getLangOptions().CPlusPlus ||
991 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
992 Decl *OldDecl = PrevDecl;
993
994 // If PrevDecl was an overloaded function, extract the
995 // FunctionDecl that matched.
996 if (isa<OverloadedFunctionDecl>(PrevDecl))
997 OldDecl = *MatchedDecl;
998
999 // NewFD and PrevDecl represent declarations that need to be
1000 // merged.
1001 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1002
1003 if (NewFD == 0) return 0;
1004 if (Redeclaration) {
1005 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1006
1007 if (OldDecl == PrevDecl) {
1008 // Remove the name binding for the previous
1009 // declaration. We'll add the binding back later, but then
1010 // it will refer to the new declaration (which will
1011 // contain more information).
1012 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1013 } else {
1014 // We need to update the OverloadedFunctionDecl with the
1015 // latest declaration of this function, so that name
1016 // lookup will always refer to the latest declaration of
1017 // this function.
1018 *MatchedDecl = NewFD;
1019
1020 // Add the redeclaration to the current scope, since we'll
1021 // be skipping PushOnScopeChains.
1022 S->AddDecl(NewFD);
1023
1024 return NewFD;
1025 }
1026 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001027 }
Chris Lattner4b009652007-07-25 00:24:17 +00001028 }
1029 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001030
1031 // In C++, check default arguments now that we have merged decls.
1032 if (getLangOptions().CPlusPlus)
1033 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +00001034 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001035 // Check that there are no default arguments (C++ only).
1036 if (getLangOptions().CPlusPlus)
1037 CheckExtraCXXDefaultArguments(D);
1038
Ted Kremenek42730c52008-01-07 19:49:32 +00001039 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001040 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1041 D.getIdentifier()->getName());
1042 InvalidDecl = true;
1043 }
Chris Lattner4b009652007-07-25 00:24:17 +00001044
1045 VarDecl *NewVD;
1046 VarDecl::StorageClass SC;
1047 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001048 default: assert(0 && "Unknown storage class!");
1049 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1050 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1051 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1052 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1053 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1054 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001055 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001056 if (D.getContext() == Declarator::MemberContext) {
1057 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1058 // This is a static data member for a C++ class.
1059 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1060 D.getIdentifierLoc(), II,
1061 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001062 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001063 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001064 if (S->getFnParent() == 0) {
1065 // C99 6.9p2: The storage-class specifiers auto and register shall not
1066 // appear in the declaration specifiers in an external declaration.
1067 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1068 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1069 R.getAsString());
1070 InvalidDecl = true;
1071 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001072 }
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001073 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +00001074 II, R, SC, LastDeclarator,
1075 // FIXME: Move to DeclGroup...
1076 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001077 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001078 }
Chris Lattner4b009652007-07-25 00:24:17 +00001079 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001080 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001081
Daniel Dunbarced89142008-08-06 00:03:29 +00001082 // Handle GNU asm-label extension (encoded as an attribute).
1083 if (Expr *E = (Expr*) D.getAsmLabel()) {
1084 // The parser guarantees this is a string.
1085 StringLiteral *SE = cast<StringLiteral>(E);
1086 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1087 SE->getByteLength())));
1088 }
1089
Nate Begemanea583262008-03-14 18:07:10 +00001090 // Emit an error if an address space was applied to decl with local storage.
1091 // This includes arrays of objects with address space qualifiers, but not
1092 // automatic variables that point to other address spaces.
1093 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001094 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1095 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1096 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001097 }
Steve Narofff8a09432008-01-09 23:34:55 +00001098 // Merge the decl with the existing one if appropriate. If the decl is
1099 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001100 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001101 NewVD = MergeVarDecl(NewVD, PrevDecl);
1102 if (NewVD == 0) return 0;
1103 }
Chris Lattner4b009652007-07-25 00:24:17 +00001104 New = NewVD;
1105 }
1106
1107 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001108 if (II)
1109 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001110 // If any semantic error occurred, mark the decl as invalid.
1111 if (D.getInvalidType() || InvalidDecl)
1112 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001113
1114 return New;
1115}
1116
Steve Narofffc08f5e2008-10-27 11:34:16 +00001117void Sema::InitializerElementNotConstant(const Expr *Init) {
1118 Diag(Init->getExprLoc(),
1119 diag::err_init_element_not_constant, Init->getSourceRange());
1120}
1121
Eli Friedman02c22ce2008-05-20 13:48:25 +00001122bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1123 switch (Init->getStmtClass()) {
1124 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001125 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001126 return true;
1127 case Expr::ParenExprClass: {
1128 const ParenExpr* PE = cast<ParenExpr>(Init);
1129 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1130 }
1131 case Expr::CompoundLiteralExprClass:
1132 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1133 case Expr::DeclRefExprClass: {
1134 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001135 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1136 if (VD->hasGlobalStorage())
1137 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001138 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001139 return true;
1140 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001141 if (isa<FunctionDecl>(D))
1142 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001143 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001144 return true;
1145 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001146 case Expr::MemberExprClass: {
1147 const MemberExpr *M = cast<MemberExpr>(Init);
1148 if (M->isArrow())
1149 return CheckAddressConstantExpression(M->getBase());
1150 return CheckAddressConstantExpressionLValue(M->getBase());
1151 }
1152 case Expr::ArraySubscriptExprClass: {
1153 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1154 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1155 return CheckAddressConstantExpression(ASE->getBase()) ||
1156 CheckArithmeticConstantExpression(ASE->getIdx());
1157 }
1158 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001159 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001160 return false;
1161 case Expr::UnaryOperatorClass: {
1162 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1163
1164 // C99 6.6p9
1165 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001166 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001167
Steve Narofffc08f5e2008-10-27 11:34:16 +00001168 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001169 return true;
1170 }
1171 }
1172}
1173
1174bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1175 switch (Init->getStmtClass()) {
1176 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001177 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001178 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001179 case Expr::ParenExprClass:
1180 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001181 case Expr::StringLiteralClass:
1182 case Expr::ObjCStringLiteralClass:
1183 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001184 case Expr::CallExprClass:
1185 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1186 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1187 Builtin::BI__builtin___CFStringMakeConstantString)
1188 return false;
1189
Steve Narofffc08f5e2008-10-27 11:34:16 +00001190 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001191 return true;
1192
Eli Friedman02c22ce2008-05-20 13:48:25 +00001193 case Expr::UnaryOperatorClass: {
1194 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1195
1196 // C99 6.6p9
1197 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1198 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1199
1200 if (Exp->getOpcode() == UnaryOperator::Extension)
1201 return CheckAddressConstantExpression(Exp->getSubExpr());
1202
Steve Narofffc08f5e2008-10-27 11:34:16 +00001203 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001204 return true;
1205 }
1206 case Expr::BinaryOperatorClass: {
1207 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1208 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1209
1210 Expr *PExp = Exp->getLHS();
1211 Expr *IExp = Exp->getRHS();
1212 if (IExp->getType()->isPointerType())
1213 std::swap(PExp, IExp);
1214
1215 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1216 return CheckAddressConstantExpression(PExp) ||
1217 CheckArithmeticConstantExpression(IExp);
1218 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001219 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001220 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001221 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001222 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1223 // Check for implicit promotion
1224 if (SubExpr->getType()->isFunctionType() ||
1225 SubExpr->getType()->isArrayType())
1226 return CheckAddressConstantExpressionLValue(SubExpr);
1227 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001228
1229 // Check for pointer->pointer cast
1230 if (SubExpr->getType()->isPointerType())
1231 return CheckAddressConstantExpression(SubExpr);
1232
Eli Friedman1fad3c62008-08-25 20:46:57 +00001233 if (SubExpr->getType()->isIntegralType()) {
1234 // Check for the special-case of a pointer->int->pointer cast;
1235 // this isn't standard, but some code requires it. See
1236 // PR2720 for an example.
1237 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1238 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1239 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1240 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1241 if (IntWidth >= PointerWidth) {
1242 return CheckAddressConstantExpression(SubCast->getSubExpr());
1243 }
1244 }
1245 }
1246 }
1247 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001248 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001249 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001250
Steve Narofffc08f5e2008-10-27 11:34:16 +00001251 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001252 return true;
1253 }
1254 case Expr::ConditionalOperatorClass: {
1255 // FIXME: Should we pedwarn here?
1256 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1257 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001258 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001259 return true;
1260 }
1261 if (CheckArithmeticConstantExpression(Exp->getCond()))
1262 return true;
1263 if (Exp->getLHS() &&
1264 CheckAddressConstantExpression(Exp->getLHS()))
1265 return true;
1266 return CheckAddressConstantExpression(Exp->getRHS());
1267 }
1268 case Expr::AddrLabelExprClass:
1269 return false;
1270 }
1271}
1272
Eli Friedman998dffb2008-06-09 05:05:07 +00001273static const Expr* FindExpressionBaseAddress(const Expr* E);
1274
1275static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1276 switch (E->getStmtClass()) {
1277 default:
1278 return E;
1279 case Expr::ParenExprClass: {
1280 const ParenExpr* PE = cast<ParenExpr>(E);
1281 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1282 }
1283 case Expr::MemberExprClass: {
1284 const MemberExpr *M = cast<MemberExpr>(E);
1285 if (M->isArrow())
1286 return FindExpressionBaseAddress(M->getBase());
1287 return FindExpressionBaseAddressLValue(M->getBase());
1288 }
1289 case Expr::ArraySubscriptExprClass: {
1290 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1291 return FindExpressionBaseAddress(ASE->getBase());
1292 }
1293 case Expr::UnaryOperatorClass: {
1294 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1295
1296 if (Exp->getOpcode() == UnaryOperator::Deref)
1297 return FindExpressionBaseAddress(Exp->getSubExpr());
1298
1299 return E;
1300 }
1301 }
1302}
1303
1304static const Expr* FindExpressionBaseAddress(const Expr* E) {
1305 switch (E->getStmtClass()) {
1306 default:
1307 return E;
1308 case Expr::ParenExprClass: {
1309 const ParenExpr* PE = cast<ParenExpr>(E);
1310 return FindExpressionBaseAddress(PE->getSubExpr());
1311 }
1312 case Expr::UnaryOperatorClass: {
1313 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1314
1315 // C99 6.6p9
1316 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1317 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1318
1319 if (Exp->getOpcode() == UnaryOperator::Extension)
1320 return FindExpressionBaseAddress(Exp->getSubExpr());
1321
1322 return E;
1323 }
1324 case Expr::BinaryOperatorClass: {
1325 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1326
1327 Expr *PExp = Exp->getLHS();
1328 Expr *IExp = Exp->getRHS();
1329 if (IExp->getType()->isPointerType())
1330 std::swap(PExp, IExp);
1331
1332 return FindExpressionBaseAddress(PExp);
1333 }
1334 case Expr::ImplicitCastExprClass: {
1335 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1336
1337 // Check for implicit promotion
1338 if (SubExpr->getType()->isFunctionType() ||
1339 SubExpr->getType()->isArrayType())
1340 return FindExpressionBaseAddressLValue(SubExpr);
1341
1342 // Check for pointer->pointer cast
1343 if (SubExpr->getType()->isPointerType())
1344 return FindExpressionBaseAddress(SubExpr);
1345
1346 // We assume that we have an arithmetic expression here;
1347 // if we don't, we'll figure it out later
1348 return 0;
1349 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001350 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001351 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1352
1353 // Check for pointer->pointer cast
1354 if (SubExpr->getType()->isPointerType())
1355 return FindExpressionBaseAddress(SubExpr);
1356
1357 // We assume that we have an arithmetic expression here;
1358 // if we don't, we'll figure it out later
1359 return 0;
1360 }
1361 }
1362}
1363
Eli Friedman02c22ce2008-05-20 13:48:25 +00001364bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1365 switch (Init->getStmtClass()) {
1366 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001367 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001368 return true;
1369 case Expr::ParenExprClass: {
1370 const ParenExpr* PE = cast<ParenExpr>(Init);
1371 return CheckArithmeticConstantExpression(PE->getSubExpr());
1372 }
1373 case Expr::FloatingLiteralClass:
1374 case Expr::IntegerLiteralClass:
1375 case Expr::CharacterLiteralClass:
1376 case Expr::ImaginaryLiteralClass:
1377 case Expr::TypesCompatibleExprClass:
1378 case Expr::CXXBoolLiteralExprClass:
1379 return false;
1380 case Expr::CallExprClass: {
1381 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001382
1383 // Allow any constant foldable calls to builtins.
1384 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001385 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001386
Steve Narofffc08f5e2008-10-27 11:34:16 +00001387 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001388 return true;
1389 }
1390 case Expr::DeclRefExprClass: {
1391 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1392 if (isa<EnumConstantDecl>(D))
1393 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001394 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001395 return true;
1396 }
1397 case Expr::CompoundLiteralExprClass:
1398 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1399 // but vectors are allowed to be magic.
1400 if (Init->getType()->isVectorType())
1401 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001402 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001403 return true;
1404 case Expr::UnaryOperatorClass: {
1405 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1406
1407 switch (Exp->getOpcode()) {
1408 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1409 // See C99 6.6p3.
1410 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001411 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001412 return true;
1413 case UnaryOperator::SizeOf:
1414 case UnaryOperator::AlignOf:
1415 case UnaryOperator::OffsetOf:
1416 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1417 // See C99 6.5.3.4p2 and 6.6p3.
1418 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1419 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001420 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001421 return true;
1422 case UnaryOperator::Extension:
1423 case UnaryOperator::LNot:
1424 case UnaryOperator::Plus:
1425 case UnaryOperator::Minus:
1426 case UnaryOperator::Not:
1427 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1428 }
1429 }
1430 case Expr::SizeOfAlignOfTypeExprClass: {
1431 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1432 // Special check for void types, which are allowed as an extension
1433 if (Exp->getArgumentType()->isVoidType())
1434 return false;
1435 // alignof always evaluates to a constant.
1436 // FIXME: is sizeof(int[3.0]) a constant expression?
1437 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001438 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001439 return true;
1440 }
1441 return false;
1442 }
1443 case Expr::BinaryOperatorClass: {
1444 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1445
1446 if (Exp->getLHS()->getType()->isArithmeticType() &&
1447 Exp->getRHS()->getType()->isArithmeticType()) {
1448 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1449 CheckArithmeticConstantExpression(Exp->getRHS());
1450 }
1451
Eli Friedman998dffb2008-06-09 05:05:07 +00001452 if (Exp->getLHS()->getType()->isPointerType() &&
1453 Exp->getRHS()->getType()->isPointerType()) {
1454 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1455 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1456
1457 // Only allow a null (constant integer) base; we could
1458 // allow some additional cases if necessary, but this
1459 // is sufficient to cover offsetof-like constructs.
1460 if (!LHSBase && !RHSBase) {
1461 return CheckAddressConstantExpression(Exp->getLHS()) ||
1462 CheckAddressConstantExpression(Exp->getRHS());
1463 }
1464 }
1465
Steve Narofffc08f5e2008-10-27 11:34:16 +00001466 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001467 return true;
1468 }
1469 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001470 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001471 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001472 if (SubExpr->getType()->isArithmeticType())
1473 return CheckArithmeticConstantExpression(SubExpr);
1474
Eli Friedman266df142008-09-02 09:37:00 +00001475 if (SubExpr->getType()->isPointerType()) {
1476 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1477 // If the pointer has a null base, this is an offsetof-like construct
1478 if (!Base)
1479 return CheckAddressConstantExpression(SubExpr);
1480 }
1481
Steve Narofffc08f5e2008-10-27 11:34:16 +00001482 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001483 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001484 }
1485 case Expr::ConditionalOperatorClass: {
1486 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001487
1488 // If GNU extensions are disabled, we require all operands to be arithmetic
1489 // constant expressions.
1490 if (getLangOptions().NoExtensions) {
1491 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1492 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1493 CheckArithmeticConstantExpression(Exp->getRHS());
1494 }
1495
1496 // Otherwise, we have to emulate some of the behavior of fold here.
1497 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1498 // because it can constant fold things away. To retain compatibility with
1499 // GCC code, we see if we can fold the condition to a constant (which we
1500 // should always be able to do in theory). If so, we only require the
1501 // specified arm of the conditional to be a constant. This is a horrible
1502 // hack, but is require by real world code that uses __builtin_constant_p.
1503 APValue Val;
1504 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1505 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1506 // won't be able to either. Use it to emit the diagnostic though.
1507 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1508 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1509 return Res;
1510 }
1511
1512 // Verify that the side following the condition is also a constant.
1513 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1514 if (Val.getInt() == 0)
1515 std::swap(TrueSide, FalseSide);
1516
1517 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001518 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001519
1520 // Okay, the evaluated side evaluates to a constant, so we accept this.
1521 // Check to see if the other side is obviously not a constant. If so,
1522 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001523 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001524 Diag(Init->getExprLoc(),
1525 diag::ext_typecheck_expression_not_constant_but_accepted,
1526 FalseSide->getSourceRange());
1527 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001528 }
1529 }
1530}
1531
1532bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001533 Init = Init->IgnoreParens();
1534
Eli Friedman02c22ce2008-05-20 13:48:25 +00001535 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1536 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1537 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1538
Nuno Lopese7280452008-07-07 16:46:50 +00001539 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1540 return CheckForConstantInitializer(e->getInitializer(), DclT);
1541
Eli Friedman02c22ce2008-05-20 13:48:25 +00001542 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1543 unsigned numInits = Exp->getNumInits();
1544 for (unsigned i = 0; i < numInits; i++) {
1545 // FIXME: Need to get the type of the declaration for C++,
1546 // because it could be a reference?
1547 if (CheckForConstantInitializer(Exp->getInit(i),
1548 Exp->getInit(i)->getType()))
1549 return true;
1550 }
1551 return false;
1552 }
1553
1554 if (Init->isNullPointerConstant(Context))
1555 return false;
1556 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001557 QualType InitTy = Context.getCanonicalType(Init->getType())
1558 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001559 if (InitTy == Context.BoolTy) {
1560 // Special handling for pointers implicitly cast to bool;
1561 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1562 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1563 Expr* SubE = ICE->getSubExpr();
1564 if (SubE->getType()->isPointerType() ||
1565 SubE->getType()->isArrayType() ||
1566 SubE->getType()->isFunctionType()) {
1567 return CheckAddressConstantExpression(Init);
1568 }
1569 }
1570 } else if (InitTy->isIntegralType()) {
1571 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001572 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001573 SubE = CE->getSubExpr();
1574 // Special check for pointer cast to int; we allow as an extension
1575 // an address constant cast to an integer if the integer
1576 // is of an appropriate width (this sort of code is apparently used
1577 // in some places).
1578 // FIXME: Add pedwarn?
1579 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1580 if (SubE && (SubE->getType()->isPointerType() ||
1581 SubE->getType()->isArrayType() ||
1582 SubE->getType()->isFunctionType())) {
1583 unsigned IntWidth = Context.getTypeSize(Init->getType());
1584 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1585 if (IntWidth >= PointerWidth)
1586 return CheckAddressConstantExpression(Init);
1587 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001588 }
1589
1590 return CheckArithmeticConstantExpression(Init);
1591 }
1592
1593 if (Init->getType()->isPointerType())
1594 return CheckAddressConstantExpression(Init);
1595
Eli Friedman25086f02008-05-30 18:14:48 +00001596 // An array type at the top level that isn't an init-list must
1597 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001598 if (Init->getType()->isArrayType())
1599 return false;
1600
Nuno Lopes1dc26762008-09-01 18:42:41 +00001601 if (Init->getType()->isFunctionType())
1602 return false;
1603
Steve Naroffdff3fb22008-10-02 17:12:56 +00001604 // Allow block exprs at top level.
1605 if (Init->getType()->isBlockPointerType())
1606 return false;
1607
Steve Narofffc08f5e2008-10-27 11:34:16 +00001608 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001609 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001610}
1611
Steve Naroff6a0e2092007-09-12 14:07:44 +00001612void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001613 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001614 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001615 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001616
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001617 // If there is no declaration, there was an error parsing it. Just ignore
1618 // the initializer.
1619 if (RealDecl == 0) {
1620 delete Init;
1621 return;
1622 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001623
Steve Naroff420d0f52007-09-12 20:13:48 +00001624 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1625 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001626 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1627 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001628 RealDecl->setInvalidDecl();
1629 return;
1630 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001631 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001632 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001633 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001634 if (VDecl->isBlockVarDecl()) {
1635 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001636 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001637 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001638 VDecl->setInvalidDecl();
1639 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001640 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1641 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001642 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001643
1644 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1645 if (!getLangOptions().CPlusPlus) {
1646 if (SC == VarDecl::Static) // C99 6.7.8p4.
1647 CheckForConstantInitializer(Init, DclT);
1648 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001649 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001650 } else if (VDecl->isFileVarDecl()) {
1651 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001652 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001653 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00001654 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1655 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001656 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001657
Anders Carlssonea7140a2008-08-22 05:00:02 +00001658 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1659 if (!getLangOptions().CPlusPlus) {
1660 // C99 6.7.8p4. All file scoped initializers need to be constant.
1661 CheckForConstantInitializer(Init, DclT);
1662 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001663 }
1664 // If the type changed, it means we had an incomplete type that was
1665 // completed by the initializer. For example:
1666 // int ary[] = { 1, 3, 5 };
1667 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001668 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001669 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001670 Init->setType(DclT);
1671 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001672
1673 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001674 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001675 return;
1676}
1677
Douglas Gregor81c29152008-10-29 00:13:59 +00001678void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1679 Decl *RealDecl = static_cast<Decl *>(dcl);
1680
1681 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1682 QualType Type = Var->getType();
1683 // C++ [dcl.init.ref]p3:
1684 // The initializer can be omitted for a reference only in a
1685 // parameter declaration (8.3.5), in the declaration of a
1686 // function return type, in the declaration of a class member
1687 // within its class declaration (9.2), and where the extern
1688 // specifier is explicitly used.
Douglas Gregor5870a952008-11-03 20:45:27 +00001689 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001690 Diag(Var->getLocation(),
1691 diag::err_reference_var_requires_init,
1692 Var->getName(),
1693 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor5870a952008-11-03 20:45:27 +00001694 Var->setInvalidDecl();
1695 return;
1696 }
1697
1698 // C++ [dcl.init]p9:
1699 //
1700 // If no initializer is specified for an object, and the object
1701 // is of (possibly cv-qualified) non-POD class type (or array
1702 // thereof), the object shall be default-initialized; if the
1703 // object is of const-qualified type, the underlying class type
1704 // shall have a user-declared default constructor.
1705 if (getLangOptions().CPlusPlus) {
1706 QualType InitType = Type;
1707 if (const ArrayType *Array = Context.getAsArrayType(Type))
1708 InitType = Array->getElementType();
1709 if (InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001710 const CXXConstructorDecl *Constructor
1711 = PerformInitializationByConstructor(InitType, 0, 0,
1712 Var->getLocation(),
1713 SourceRange(Var->getLocation(),
1714 Var->getLocation()),
1715 Var->getName(),
1716 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00001717 if (!Constructor)
1718 Var->setInvalidDecl();
1719 }
1720 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001721
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001722#if 0
1723 // FIXME: Temporarily disabled because we are not properly parsing
1724 // linkage specifications on declarations, e.g.,
1725 //
1726 // extern "C" const CGPoint CGPointerZero;
1727 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001728 // C++ [dcl.init]p9:
1729 //
1730 // If no initializer is specified for an object, and the
1731 // object is of (possibly cv-qualified) non-POD class type (or
1732 // array thereof), the object shall be default-initialized; if
1733 // the object is of const-qualified type, the underlying class
1734 // type shall have a user-declared default
1735 // constructor. Otherwise, if no initializer is specified for
1736 // an object, the object and its subobjects, if any, have an
1737 // indeterminate initial value; if the object or any of its
1738 // subobjects are of const-qualified type, the program is
1739 // ill-formed.
1740 //
1741 // This isn't technically an error in C, so we don't diagnose it.
1742 //
1743 // FIXME: Actually perform the POD/user-defined default
1744 // constructor check.
1745 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001746 Context.getCanonicalType(Type).isConstQualified() &&
1747 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor81c29152008-10-29 00:13:59 +00001748 Diag(Var->getLocation(),
1749 diag::err_const_var_requires_init,
1750 Var->getName(),
1751 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001752#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00001753 }
1754}
1755
Chris Lattner4b009652007-07-25 00:24:17 +00001756/// The declarators are chained together backwards, reverse the list.
1757Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1758 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001759 Decl *GroupDecl = static_cast<Decl*>(group);
1760 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001761 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001762
1763 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1764 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001765 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001766 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001767 else { // reverse the list.
1768 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001769 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001770 Group->setNextDeclarator(NewGroup);
1771 NewGroup = Group;
1772 Group = Next;
1773 }
1774 }
1775 // Perform semantic analysis that depends on having fully processed both
1776 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001777 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001778 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1779 if (!IDecl)
1780 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001781 QualType T = IDecl->getType();
1782
1783 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1784 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001785 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1786 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001787 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001788 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1789 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001790 }
1791 }
1792 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1793 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001794 if (IDecl->isBlockVarDecl() &&
1795 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001796 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001797 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1798 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001799 IDecl->setInvalidDecl();
1800 }
1801 }
1802 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1803 // object that has file scope without an initializer, and without a
1804 // storage-class specifier or with the storage-class specifier "static",
1805 // constitutes a tentative definition. Note: A tentative definition with
1806 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001807 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001808 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001809 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1810 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001811 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001812 // C99 6.9.2p3: If the declaration of an identifier for an object is
1813 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1814 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001815 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1816 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001817 IDecl->setInvalidDecl();
1818 }
1819 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001820 if (IDecl->isFileVarDecl())
1821 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001822 }
1823 return NewGroup;
1824}
Steve Naroff91b03f72007-08-28 03:03:08 +00001825
Chris Lattner3e254fb2008-04-08 04:40:51 +00001826/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1827/// to introduce parameters into function prototype scope.
1828Sema::DeclTy *
1829Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00001830 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001831
1832 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001833 VarDecl::StorageClass StorageClass = VarDecl::None;
1834 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1835 StorageClass = VarDecl::Register;
1836 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001837 Diag(DS.getStorageClassSpecLoc(),
1838 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001839 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001840 }
1841 if (DS.isThreadSpecified()) {
1842 Diag(DS.getThreadSpecLoc(),
1843 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001844 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001845 }
1846
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001847 // Check that there are no default arguments inside the type of this
1848 // parameter (C++ only).
1849 if (getLangOptions().CPlusPlus)
1850 CheckExtraCXXDefaultArguments(D);
1851
Chris Lattner3e254fb2008-04-08 04:40:51 +00001852 // In this context, we *do not* check D.getInvalidType(). If the declarator
1853 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1854 // though it will not reflect the user specified type.
1855 QualType parmDeclType = GetTypeForDeclarator(D, S);
1856
1857 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1858
Chris Lattner4b009652007-07-25 00:24:17 +00001859 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1860 // Can this happen for params? We already checked that they don't conflict
1861 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001862 IdentifierInfo *II = D.getIdentifier();
1863 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1864 if (S->isDeclScope(PrevDecl)) {
1865 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1866 dyn_cast<NamedDecl>(PrevDecl)->getName());
1867
1868 // Recover by removing the name
1869 II = 0;
1870 D.SetIdentifier(0, D.getIdentifierLoc());
1871 }
Chris Lattner4b009652007-07-25 00:24:17 +00001872 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001873
1874 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1875 // Doing the promotion here has a win and a loss. The win is the type for
1876 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1877 // code generator). The loss is the orginal type isn't preserved. For example:
1878 //
1879 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1880 // int blockvardecl[5];
1881 // sizeof(parmvardecl); // size == 4
1882 // sizeof(blockvardecl); // size == 20
1883 // }
1884 //
1885 // For expressions, all implicit conversions are captured using the
1886 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1887 //
1888 // FIXME: If a source translation tool needs to see the original type, then
1889 // we need to consider storing both types (in ParmVarDecl)...
1890 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001891 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001892 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001893 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001894 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001895 parmDeclType = Context.getPointerType(parmDeclType);
1896
Chris Lattner3e254fb2008-04-08 04:40:51 +00001897 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1898 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001899 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001900 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001901
Chris Lattner3e254fb2008-04-08 04:40:51 +00001902 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001903 New->setInvalidDecl();
1904
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001905 if (II)
1906 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001907
Chris Lattner9b384ca2008-06-29 00:02:00 +00001908 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001909 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001910
Chris Lattner4b009652007-07-25 00:24:17 +00001911}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001912
Chris Lattnerea148702007-10-09 17:14:05 +00001913Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001914 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001915 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1916 "Not a function declarator!");
1917 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001918
Chris Lattner4b009652007-07-25 00:24:17 +00001919 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1920 // for a K&R function.
1921 if (!FTI.hasPrototype) {
1922 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001923 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001924 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1925 FTI.ArgInfo[i].Ident->getName());
1926 // Implicitly declare the argument as type 'int' for lack of a better
1927 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001928 DeclSpec DS;
1929 const char* PrevSpec; // unused
1930 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1931 PrevSpec);
1932 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1933 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1934 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001935 }
1936 }
Chris Lattner4b009652007-07-25 00:24:17 +00001937 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001938 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001939 }
1940
1941 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001942
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001943 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001944 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001945}
1946
1947Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1948 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00001949 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00001950
1951 // See if this is a redefinition.
1952 const FunctionDecl *Definition;
1953 if (FD->getBody(Definition)) {
1954 Diag(FD->getLocation(), diag::err_redefinition,
1955 FD->getName());
1956 Diag(Definition->getLocation(), diag::err_previous_definition);
1957 }
1958
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001959 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001960
1961 // Check the validity of our function parameters
1962 CheckParmsForFunctionDef(FD);
1963
1964 // Introduce our parameters into the function scope
1965 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1966 ParmVarDecl *Param = FD->getParamDecl(p);
1967 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001968 if (Param->getIdentifier())
1969 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001970 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001971
Chris Lattner4b009652007-07-25 00:24:17 +00001972 return FD;
1973}
1974
Steve Naroff99ee4302007-11-11 23:20:51 +00001975Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1976 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001977 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001978 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001979 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00001980 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001981 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001982 } else
1983 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001984 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001985 // Verify and clean out per-function state.
1986
1987 // Check goto/label use.
1988 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1989 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1990 // Verify that we have no forward references left. If so, there was a goto
1991 // or address of a label taken, but no definition of it. Label fwd
1992 // definitions are indicated with a null substmt.
1993 if (I->second->getSubStmt() == 0) {
1994 LabelStmt *L = I->second;
1995 // Emit error.
1996 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1997
1998 // At this point, we have gotos that use the bogus label. Stitch it into
1999 // the function body so that they aren't leaked and that the AST is well
2000 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002001 if (Body) {
2002 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2003 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2004 } else {
2005 // The whole function wasn't parsed correctly, just delete this.
2006 delete L;
2007 }
Chris Lattner4b009652007-07-25 00:24:17 +00002008 }
2009 }
2010 LabelMap.clear();
2011
Steve Naroff99ee4302007-11-11 23:20:51 +00002012 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002013}
2014
Chris Lattner4b009652007-07-25 00:24:17 +00002015/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2016/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002017ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2018 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002019 // Extension in C99. Legal in C90, but warn about it.
2020 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00002021 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002022 else
Chris Lattner4b009652007-07-25 00:24:17 +00002023 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2024
2025 // FIXME: handle stuff like:
2026 // void foo() { extern float X(); }
2027 // void bar() { X(); } <-- implicit decl for X in another scope.
2028
2029 // Set a Declarator for the implicit definition: int foo();
2030 const char *Dummy;
2031 DeclSpec DS;
2032 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2033 Error = Error; // Silence warning.
2034 assert(!Error && "Error setting up implicit decl!");
2035 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002036 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002037 D.SetIdentifier(&II, Loc);
2038
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002039 // Insert this function into translation-unit scope.
2040
2041 DeclContext *PrevDC = CurContext;
2042 CurContext = Context.getTranslationUnitDecl();
2043
Steve Naroff9104f3c2008-04-04 14:32:09 +00002044 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002045 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002046 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002047
2048 CurContext = PrevDC;
2049
Steve Naroff9104f3c2008-04-04 14:32:09 +00002050 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002051}
2052
2053
Chris Lattner82bb4792007-11-14 06:34:38 +00002054TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002055 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002056 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002057 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002058
2059 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002060 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2061 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002062 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002063 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002064 if (D.getInvalidType())
2065 NewTD->setInvalidDecl();
2066 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002067}
2068
Steve Naroff0acc9c92007-09-15 18:49:24 +00002069/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002070/// former case, Name will be non-null. In the later case, Name will be null.
2071/// TagType indicates what kind of tag this is. TK indicates whether this is a
2072/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002073Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00002074 SourceLocation KWLoc, IdentifierInfo *Name,
2075 SourceLocation NameLoc, AttributeList *Attr) {
2076 // If this is a use of an existing tag, it must have a name.
2077 assert((Name != 0 || TK == TK_Definition) &&
2078 "Nameless record must be a definition!");
2079
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002080 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002081 switch (TagType) {
2082 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002083 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2084 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2085 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2086 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002087 }
2088
Ted Kremenek46a837c2008-09-05 17:16:31 +00002089 // Two code paths: a new one for structs/unions/classes where we create
2090 // separate decls for forward declarations, and an old (eventually to
2091 // be removed) code path for enums.
2092 if (Kind != TagDecl::TK_enum)
2093 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
2094
Chris Lattner4b009652007-07-25 00:24:17 +00002095 // If this is a named struct, check to see if there was a previous forward
2096 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002097 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenekd4434152008-09-02 21:26:19 +00002098 ScopedDecl *PrevDecl =
2099 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
2100
2101 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002102 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2103 "unexpected Decl type");
2104 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002105 // If this is a use of a previous tag, or if the tag is already declared
2106 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002107 // rementions the tag), reuse the decl.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002108 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002109 // Make sure that this wasn't declared as an enum and now used as a
2110 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002111 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002112 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2113 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002114 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002115 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002116 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002117 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002118 // If this is a use or a forward declaration, we're good.
2119 if (TK != TK_Definition)
2120 return PrevDecl;
2121
2122 // Diagnose attempts to redefine a tag.
2123 if (PrevTagDecl->isDefinition()) {
2124 Diag(NameLoc, diag::err_redefinition, Name->getName());
2125 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2126 // If this is a redefinition, recover by making this struct be
2127 // anonymous, which will make any later references get the previous
2128 // definition.
2129 Name = 0;
2130 } else {
2131 // Okay, this is definition of a previously declared or referenced
2132 // tag. Move the location of the decl to be the definition site.
2133 PrevDecl->setLocation(NameLoc);
2134 return PrevDecl;
2135 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002136 }
Chris Lattner4b009652007-07-25 00:24:17 +00002137 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002138 // If we get here, this is a definition of a new struct type in a nested
2139 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2140 // type.
2141 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002142 // PrevDecl is a namespace.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002143 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002144 // The tag name clashes with a namespace name, issue an error and
2145 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002146 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2147 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2148 Name = 0;
2149 }
Chris Lattner4b009652007-07-25 00:24:17 +00002150 }
Chris Lattner4b009652007-07-25 00:24:17 +00002151 }
2152
2153 // If there is an identifier, use the location of the identifier as the
2154 // location of the decl, otherwise use the location of the struct/union
2155 // keyword.
2156 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2157
2158 // Otherwise, if this is the first time we've seen this tag, create the decl.
2159 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002160 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002161 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2162 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00002163 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002164 // If this is an undefined enum, warn.
2165 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002166 } else {
2167 // struct/union/class
2168
Chris Lattner4b009652007-07-25 00:24:17 +00002169 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2170 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002171 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002172 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek2c984042008-09-05 01:34:33 +00002173 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002174 else
Ted Kremenek2c984042008-09-05 01:34:33 +00002175 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002176 }
Chris Lattner4b009652007-07-25 00:24:17 +00002177
2178 // If this has an identifier, add it to the scope stack.
2179 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002180 // The scope passed in may not be a decl scope. Zip up the scope tree until
2181 // we find one that is.
2182 while ((S->getFlags() & Scope::DeclScope) == 0)
2183 S = S->getParent();
2184
2185 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002186 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002187 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00002188
Chris Lattnerd7e83d82008-06-28 23:58:55 +00002189 if (Attr)
2190 ProcessDeclAttributeList(New, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002191 return New;
2192}
2193
Ted Kremenek46a837c2008-09-05 17:16:31 +00002194/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2195/// the logic for enums, we create separate decls for forward declarations.
2196/// This is called by ActOnTag, but eventually will replace its logic.
2197Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
2198 SourceLocation KWLoc, IdentifierInfo *Name,
2199 SourceLocation NameLoc, AttributeList *Attr) {
2200
2201 // If this is a named struct, check to see if there was a previous forward
2202 // declaration or definition.
2203 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2204 ScopedDecl *PrevDecl =
2205 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
2206
2207 if (PrevDecl) {
2208 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2209 "unexpected Decl type");
2210
2211 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2212 // If this is a use of a previous tag, or if the tag is already declared
2213 // in the same scope (so that the definition/declaration completes or
2214 // rementions the tag), reuse the decl.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002215 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002216 // Make sure that this wasn't declared as an enum and now used as a
2217 // struct or something similar.
2218 if (PrevTagDecl->getTagKind() != Kind) {
2219 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2220 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2221 // Recover by making this an anonymous redefinition.
2222 Name = 0;
2223 PrevDecl = 0;
2224 } else {
2225 // If this is a use, return the original decl.
2226
2227 // FIXME: In the future, return a variant or some other clue
2228 // for the consumer of this Decl to know it doesn't own it.
2229 // For our current ASTs this shouldn't be a problem, but will
2230 // need to be changed with DeclGroups.
2231 if (TK == TK_Reference)
2232 return PrevDecl;
2233
2234 // The new decl is a definition?
2235 if (TK == TK_Definition) {
2236 // Diagnose attempts to redefine a tag.
2237 if (RecordDecl* DefRecord =
2238 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2239 Diag(NameLoc, diag::err_redefinition, Name->getName());
2240 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2241 // If this is a redefinition, recover by making this struct be
2242 // anonymous, which will make any later references get the previous
2243 // definition.
2244 Name = 0;
2245 PrevDecl = 0;
2246 }
2247 // Okay, this is definition of a previously declared or referenced
2248 // tag. We're going to create a new Decl.
2249 }
2250 }
2251 // If we get here we have (another) forward declaration. Just create
2252 // a new decl.
2253 }
2254 else {
2255 // If we get here, this is a definition of a new struct type in a nested
2256 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2257 // new decl/type. We set PrevDecl to NULL so that the Records
2258 // have distinct types.
2259 PrevDecl = 0;
2260 }
2261 } else {
2262 // PrevDecl is a namespace.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002263 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002264 // The tag name clashes with a namespace name, issue an error and
2265 // recover by making this tag be anonymous.
2266 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2267 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2268 Name = 0;
2269 }
2270 }
2271 }
2272
2273 // If there is an identifier, use the location of the identifier as the
2274 // location of the decl, otherwise use the location of the struct/union
2275 // keyword.
2276 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2277
2278 // Otherwise, if this is the first time we've seen this tag, create the decl.
2279 TagDecl *New;
2280
2281 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2282 // struct X { int A; } D; D should chain to X.
2283 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002284 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek46a837c2008-09-05 17:16:31 +00002285 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2286 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2287 else
2288 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2289 dyn_cast_or_null<RecordDecl>(PrevDecl));
2290
2291 // If this has an identifier, add it to the scope stack.
2292 if ((TK == TK_Definition || !PrevDecl) && Name) {
2293 // The scope passed in may not be a decl scope. Zip up the scope tree until
2294 // we find one that is.
2295 while ((S->getFlags() & Scope::DeclScope) == 0)
2296 S = S->getParent();
2297
2298 // Add it to the decl chain.
2299 PushOnScopeChains(New, S);
2300 }
Daniel Dunbar2cb762f2008-10-16 02:34:03 +00002301
2302 // Handle #pragma pack: if the #pragma pack stack has non-default
2303 // alignment, make up a packed attribute for this decl. These
2304 // attributes are checked when the ASTContext lays out the
2305 // structure.
2306 //
2307 // It is important for implementing the correct semantics that this
2308 // happen here (in act on tag decl). The #pragma pack stack is
2309 // maintained as a result of parser callbacks which can occur at
2310 // many points during the parsing of a struct declaration (because
2311 // the #pragma tokens are effectively skipped over during the
2312 // parsing of the struct).
2313 if (unsigned Alignment = PackContext.getAlignment())
2314 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek46a837c2008-09-05 17:16:31 +00002315
2316 if (Attr)
2317 ProcessDeclAttributeList(New, Attr);
2318
2319 return New;
2320}
2321
2322
Chris Lattner1bf58f62008-06-21 19:39:06 +00002323/// Collect the instance variables declared in an Objective-C object. Used in
2324/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002325static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002326 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002327 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002328 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2329
2330 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00002331 for (ObjCInterfaceDecl::ivar_iterator
2332 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2333
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002334 ObjCIvarDecl* ID = *I;
2335 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2336 ID->getIdentifier(),
2337 ID->getType(),
2338 ID->getBitWidth()));
2339 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002340}
2341
2342/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2343/// instance variables of ClassName into Decls.
2344void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2345 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002346 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002347 // Check that ClassName is a valid class
2348 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2349 if (!Class) {
2350 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2351 return;
2352 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002353 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002354 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00002355}
2356
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002357QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
2358 // This method tries to turn a variable array into a constant
2359 // array even when the size isn't an ICE. This is necessary
2360 // for compatibility with code that depends on gcc's buggy
2361 // constant expression folding, like struct {char x[(int)(char*)2];}
2362 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00002363 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002364 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00002365 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2366 llvm::APSInt &Res = Result.getInt();
2367 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2368 return Context.getConstantArrayType(VLATy->getElementType(),
2369 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002370 }
2371 }
2372 return QualType();
2373}
2374
Steve Naroff0acc9c92007-09-15 18:49:24 +00002375/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002376/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002377Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00002378 SourceLocation DeclStart,
2379 Declarator &D, ExprTy *BitfieldWidth) {
2380 IdentifierInfo *II = D.getIdentifier();
2381 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002382 SourceLocation Loc = DeclStart;
2383 if (II) Loc = D.getIdentifierLoc();
2384
2385 // FIXME: Unnamed fields can be handled in various different ways, for
2386 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00002387
Chris Lattner4b009652007-07-25 00:24:17 +00002388 if (BitWidth) {
2389 // TODO: Validate.
2390 //printf("WARNING: BITFIELDS IGNORED!\n");
2391
2392 // 6.7.2.1p3
2393 // 6.7.2.1p4
2394
2395 } else {
2396 // Not a bitfield.
2397
2398 // validate II.
2399
2400 }
2401
2402 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002403 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2404 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00002405
Chris Lattner4b009652007-07-25 00:24:17 +00002406 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2407 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002408 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002409 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2410 if (!FixedTy.isNull()) {
2411 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2412 T = FixedTy;
2413 } else {
2414 // FIXME: This diagnostic needs work
2415 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2416 InvalidDecl = true;
2417 }
Chris Lattner4b009652007-07-25 00:24:17 +00002418 }
Chris Lattner4b009652007-07-25 00:24:17 +00002419 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002420 FieldDecl *NewFD;
2421
2422 if (getLangOptions().CPlusPlus) {
2423 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2424 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2425 Loc, II, T, BitWidth);
2426 if (II)
2427 PushOnScopeChains(NewFD, S);
2428 }
2429 else
2430 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002431
Chris Lattner9b384ca2008-06-29 00:02:00 +00002432 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002433
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002434 if (D.getInvalidType() || InvalidDecl)
2435 NewFD->setInvalidDecl();
2436 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002437}
2438
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002439/// TranslateIvarVisibility - Translate visibility from a token ID to an
2440/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002441static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002442TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002443 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002444 default: assert(0 && "Unknown visitibility kind");
2445 case tok::objc_private: return ObjCIvarDecl::Private;
2446 case tok::objc_public: return ObjCIvarDecl::Public;
2447 case tok::objc_protected: return ObjCIvarDecl::Protected;
2448 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002449 }
2450}
2451
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002452/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2453/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002454Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002455 SourceLocation DeclStart,
2456 Declarator &D, ExprTy *BitfieldWidth,
2457 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002458 IdentifierInfo *II = D.getIdentifier();
2459 Expr *BitWidth = (Expr*)BitfieldWidth;
2460 SourceLocation Loc = DeclStart;
2461 if (II) Loc = D.getIdentifierLoc();
2462
2463 // FIXME: Unnamed fields can be handled in various different ways, for
2464 // example, unnamed unions inject all members into the struct namespace!
2465
2466
2467 if (BitWidth) {
2468 // TODO: Validate.
2469 //printf("WARNING: BITFIELDS IGNORED!\n");
2470
2471 // 6.7.2.1p3
2472 // 6.7.2.1p4
2473
2474 } else {
2475 // Not a bitfield.
2476
2477 // validate II.
2478
2479 }
2480
2481 QualType T = GetTypeForDeclarator(D, S);
2482 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2483 bool InvalidDecl = false;
2484
2485 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2486 // than a variably modified type.
2487 if (T->isVariablyModifiedType()) {
2488 // FIXME: This diagnostic needs work
2489 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2490 InvalidDecl = true;
2491 }
2492
Ted Kremenek173dd312008-07-23 18:04:17 +00002493 // Get the visibility (access control) for this ivar.
2494 ObjCIvarDecl::AccessControl ac =
2495 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2496 : ObjCIvarDecl::None;
2497
2498 // Construct the decl.
2499 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002500 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002501
Ted Kremenek173dd312008-07-23 18:04:17 +00002502 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002503 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002504
2505 if (D.getInvalidType() || InvalidDecl)
2506 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002507
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002508 return NewID;
2509}
2510
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002511void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002512 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002513 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002514 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002515 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002516 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2517 assert(EnclosingDecl && "missing record or interface decl");
2518 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2519
Ted Kremenek46a837c2008-09-05 17:16:31 +00002520 if (Record)
2521 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2522 // Diagnose code like:
2523 // struct S { struct S {} X; };
2524 // We discover this when we complete the outer S. Reject and ignore the
2525 // outer S.
2526 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2527 DefRecord->getKindName());
2528 Diag(RecLoc, diag::err_previous_definition);
2529 Record->setInvalidDecl();
2530 return;
2531 }
2532
Chris Lattner4b009652007-07-25 00:24:17 +00002533 // Verify that all the fields are okay.
2534 unsigned NumNamedMembers = 0;
2535 llvm::SmallVector<FieldDecl*, 32> RecFields;
2536 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002537
Chris Lattner4b009652007-07-25 00:24:17 +00002538 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002539
Steve Naroff9bb759f2007-09-14 22:20:54 +00002540 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2541 assert(FD && "missing field decl");
2542
2543 // Remember all fields.
2544 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002545
2546 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002547 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002548
Chris Lattner4b009652007-07-25 00:24:17 +00002549 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002550 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002551 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002552 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002553 FD->setInvalidDecl();
2554 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002555 continue;
2556 }
Chris Lattner4b009652007-07-25 00:24:17 +00002557 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2558 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002559 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002560 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002561 FD->setInvalidDecl();
2562 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002563 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002564 }
Chris Lattner4b009652007-07-25 00:24:17 +00002565 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002566 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002567 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002568 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002569 FD->setInvalidDecl();
2570 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002571 continue;
2572 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002573 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002574 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2575 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002576 FD->setInvalidDecl();
2577 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002578 continue;
2579 }
Chris Lattner4b009652007-07-25 00:24:17 +00002580 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002581 if (Record)
2582 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002583 }
Chris Lattner4b009652007-07-25 00:24:17 +00002584 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2585 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002586 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002587 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2588 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002589 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002590 Record->setHasFlexibleArrayMember(true);
2591 } else {
2592 // If this is a struct/class and this is not the last element, reject
2593 // it. Note that GCC supports variable sized arrays in the middle of
2594 // structures.
2595 if (i != NumFields-1) {
2596 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2597 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002598 FD->setInvalidDecl();
2599 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002600 continue;
2601 }
Chris Lattner4b009652007-07-25 00:24:17 +00002602 // We support flexible arrays at the end of structs in other structs
2603 // as an extension.
2604 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2605 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002606 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002607 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002608 }
2609 }
2610 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002611 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002612 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002613 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2614 FD->getName());
2615 FD->setInvalidDecl();
2616 EnclosingDecl->setInvalidDecl();
2617 continue;
2618 }
Chris Lattner4b009652007-07-25 00:24:17 +00002619 // Keep track of the number of named members.
2620 if (IdentifierInfo *II = FD->getIdentifier()) {
2621 // Detect duplicate member names.
2622 if (!FieldIDs.insert(II)) {
2623 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2624 // Find the previous decl.
2625 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00002626 for (unsigned i = 0; ; ++i) {
2627 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00002628 if (RecFields[i]->getIdentifier() == II) {
2629 PrevLoc = RecFields[i]->getLocation();
2630 break;
2631 }
2632 }
2633 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002634 FD->setInvalidDecl();
2635 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002636 continue;
2637 }
2638 ++NumNamedMembers;
2639 }
Chris Lattner4b009652007-07-25 00:24:17 +00002640 }
2641
Chris Lattner4b009652007-07-25 00:24:17 +00002642 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002643 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002644 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002645 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2646 // Sema::ActOnFinishCXXClassDef.
2647 if (!isa<CXXRecordDecl>(Record))
2648 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002649 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002650 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2651 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2652 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2653 else if (ObjCImplementationDecl *IMPDecl =
2654 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002655 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2656 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002657 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002658 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002659 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002660
2661 if (Attr)
2662 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002663}
2664
Steve Naroff0acc9c92007-09-15 18:49:24 +00002665Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002666 DeclTy *lastEnumConst,
2667 SourceLocation IdLoc, IdentifierInfo *Id,
2668 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002669 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002670 EnumConstantDecl *LastEnumConst =
2671 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2672 Expr *Val = static_cast<Expr*>(val);
2673
Chris Lattnera7549902007-08-26 06:24:45 +00002674 // The scope passed in may not be a decl scope. Zip up the scope tree until
2675 // we find one that is.
2676 while ((S->getFlags() & Scope::DeclScope) == 0)
2677 S = S->getParent();
2678
Chris Lattner4b009652007-07-25 00:24:17 +00002679 // Verify that there isn't already something declared with this name in this
2680 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002681 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002682 // When in C++, we may get a TagDecl with the same name; in this case the
2683 // enum constant will 'hide' the tag.
2684 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2685 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002686 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002687 if (isa<EnumConstantDecl>(PrevDecl))
2688 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2689 else
2690 Diag(IdLoc, diag::err_redefinition, Id->getName());
2691 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002692 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002693 return 0;
2694 }
2695 }
2696
2697 llvm::APSInt EnumVal(32);
2698 QualType EltTy;
2699 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002700 // Make sure to promote the operand type to int.
2701 UsualUnaryConversions(Val);
2702
Chris Lattner4b009652007-07-25 00:24:17 +00002703 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2704 SourceLocation ExpLoc;
2705 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2706 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2707 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002708 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002709 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002710 } else {
2711 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002712 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002713 }
2714
2715 if (!Val) {
2716 if (LastEnumConst) {
2717 // Assign the last value + 1.
2718 EnumVal = LastEnumConst->getInitVal();
2719 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002720
2721 // Check for overflow on increment.
2722 if (EnumVal < LastEnumConst->getInitVal())
2723 Diag(IdLoc, diag::warn_enum_value_overflow);
2724
Chris Lattnere7f53a42007-08-27 17:37:24 +00002725 EltTy = LastEnumConst->getType();
2726 } else {
2727 // First value, set to zero.
2728 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002729 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002730 }
Chris Lattner4b009652007-07-25 00:24:17 +00002731 }
2732
Chris Lattnere4650482008-03-15 06:12:44 +00002733 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002734 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2735 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002736 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002737
2738 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002739 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002740 return New;
2741}
2742
Steve Naroffb0726b82008-08-07 14:08:16 +00002743// FIXME: For consistency with ActOnFields(), we should have the parser
2744// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002745void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002746 DeclTy **Elements, unsigned NumElements) {
2747 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002748
Steve Naroffb0726b82008-08-07 14:08:16 +00002749 if (Enum && Enum->isDefinition()) {
2750 // Diagnose code like:
2751 // enum e0 {
2752 // E0 = sizeof(enum e0 { E1 })
2753 // };
2754 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2755 Enum->getName());
2756 Diag(EnumLoc, diag::err_previous_definition);
2757 Enum->setInvalidDecl();
2758 return;
2759 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002760 // TODO: If the result value doesn't fit in an int, it must be a long or long
2761 // long value. ISO C does not support this, but GCC does as an extension,
2762 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002763 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002764
Chris Lattner206754a2007-08-28 06:15:15 +00002765 // Verify that all the values are okay, compute the size of the values, and
2766 // reverse the list.
2767 unsigned NumNegativeBits = 0;
2768 unsigned NumPositiveBits = 0;
2769
2770 // Keep track of whether all elements have type int.
2771 bool AllElementsInt = true;
2772
Chris Lattner4b009652007-07-25 00:24:17 +00002773 EnumConstantDecl *EltList = 0;
2774 for (unsigned i = 0; i != NumElements; ++i) {
2775 EnumConstantDecl *ECD =
2776 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2777 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002778
2779 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002780 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002781 assert(InitVal.getBitWidth() >= IntWidth &&
2782 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002783 if (InitVal.getBitWidth() > IntWidth) {
2784 llvm::APSInt V(InitVal);
2785 V.trunc(IntWidth);
2786 V.extend(InitVal.getBitWidth());
2787 if (V != InitVal)
2788 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002789 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002790 }
Chris Lattner206754a2007-08-28 06:15:15 +00002791
2792 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002793 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002794 NumPositiveBits = std::max(NumPositiveBits,
2795 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002796 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002797 NumNegativeBits = std::max(NumNegativeBits,
2798 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002799
Chris Lattner206754a2007-08-28 06:15:15 +00002800 // Keep track of whether every enum element has type int (very commmon).
2801 if (AllElementsInt)
2802 AllElementsInt = ECD->getType() == Context.IntTy;
2803
Chris Lattner4b009652007-07-25 00:24:17 +00002804 ECD->setNextDeclarator(EltList);
2805 EltList = ECD;
2806 }
2807
Chris Lattner206754a2007-08-28 06:15:15 +00002808 // Figure out the type that should be used for this enum.
2809 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2810 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002811 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002812
2813 if (NumNegativeBits) {
2814 // If there is a negative value, figure out the smallest integer type (of
2815 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002816 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002817 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002818 BestWidth = IntWidth;
2819 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002820 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002821
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002822 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002823 BestType = Context.LongTy;
2824 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002825 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002826
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002827 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002828 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2829 BestType = Context.LongLongTy;
2830 }
2831 }
2832 } else {
2833 // If there is no negative value, figure out which of uint, ulong, ulonglong
2834 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002835 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002836 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002837 BestWidth = IntWidth;
2838 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002839 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002840 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002841 } else {
2842 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002843 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002844 "How could an initializer get larger than ULL?");
2845 BestType = Context.UnsignedLongLongTy;
2846 }
2847 }
2848
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002849 // Loop over all of the enumerator constants, changing their types to match
2850 // the type of the enum if needed.
2851 for (unsigned i = 0; i != NumElements; ++i) {
2852 EnumConstantDecl *ECD =
2853 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2854 if (!ECD) continue; // Already issued a diagnostic.
2855
2856 // Standard C says the enumerators have int type, but we allow, as an
2857 // extension, the enumerators to be larger than int size. If each
2858 // enumerator value fits in an int, type it as an int, otherwise type it the
2859 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2860 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002861 if (ECD->getType() == Context.IntTy) {
2862 // Make sure the init value is signed.
2863 llvm::APSInt IV = ECD->getInitVal();
2864 IV.setIsSigned(true);
2865 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002866 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002867 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002868
2869 // Determine whether the value fits into an int.
2870 llvm::APSInt InitVal = ECD->getInitVal();
2871 bool FitsInInt;
2872 if (InitVal.isUnsigned() || !InitVal.isNegative())
2873 FitsInInt = InitVal.getActiveBits() < IntWidth;
2874 else
2875 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2876
2877 // If it fits into an integer type, force it. Otherwise force it to match
2878 // the enum decl type.
2879 QualType NewTy;
2880 unsigned NewWidth;
2881 bool NewSign;
2882 if (FitsInInt) {
2883 NewTy = Context.IntTy;
2884 NewWidth = IntWidth;
2885 NewSign = true;
2886 } else if (ECD->getType() == BestType) {
2887 // Already the right type!
2888 continue;
2889 } else {
2890 NewTy = BestType;
2891 NewWidth = BestWidth;
2892 NewSign = BestType->isSignedIntegerType();
2893 }
2894
2895 // Adjust the APSInt value.
2896 InitVal.extOrTrunc(NewWidth);
2897 InitVal.setIsSigned(NewSign);
2898 ECD->setInitVal(InitVal);
2899
2900 // Adjust the Expr initializer and type.
2901 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2902 ECD->setType(NewTy);
2903 }
Chris Lattner206754a2007-08-28 06:15:15 +00002904
Chris Lattner90a018d2007-08-28 18:24:31 +00002905 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002906 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002907}
2908
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002909Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2910 ExprTy *expr) {
2911 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2912
Chris Lattner81db64a2008-03-16 00:16:02 +00002913 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002914}
2915
Chris Lattner806a5f52008-01-12 07:05:38 +00002916Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002917 SourceLocation LBrace,
2918 SourceLocation RBrace,
2919 const char *Lang,
2920 unsigned StrSize,
2921 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002922 LinkageSpecDecl::LanguageIDs Language;
2923 Decl *dcl = static_cast<Decl *>(D);
2924 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2925 Language = LinkageSpecDecl::lang_c;
2926 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2927 Language = LinkageSpecDecl::lang_cxx;
2928 else {
2929 Diag(Loc, diag::err_bad_language);
2930 return 0;
2931 }
2932
2933 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002934 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002935}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00002936
2937void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
2938 ExprTy *alignment, SourceLocation PragmaLoc,
2939 SourceLocation LParenLoc, SourceLocation RParenLoc) {
2940 Expr *Alignment = static_cast<Expr *>(alignment);
2941
2942 // If specified then alignment must be a "small" power of two.
2943 unsigned AlignmentVal = 0;
2944 if (Alignment) {
2945 llvm::APSInt Val;
2946 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
2947 !Val.isPowerOf2() ||
2948 Val.getZExtValue() > 16) {
2949 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
2950 delete Alignment;
2951 return; // Ignore
2952 }
2953
2954 AlignmentVal = (unsigned) Val.getZExtValue();
2955 }
2956
2957 switch (Kind) {
2958 case Action::PPK_Default: // pack([n])
2959 PackContext.setAlignment(AlignmentVal);
2960 break;
2961
2962 case Action::PPK_Show: // pack(show)
2963 // Show the current alignment, making sure to show the right value
2964 // for the default.
2965 AlignmentVal = PackContext.getAlignment();
2966 // FIXME: This should come from the target.
2967 if (AlignmentVal == 0)
2968 AlignmentVal = 8;
2969 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
2970 break;
2971
2972 case Action::PPK_Push: // pack(push [, id] [, [n])
2973 PackContext.push(Name);
2974 // Set the new alignment if specified.
2975 if (Alignment)
2976 PackContext.setAlignment(AlignmentVal);
2977 break;
2978
2979 case Action::PPK_Pop: // pack(pop [, id] [, n])
2980 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
2981 // "#pragma pack(pop, identifier, n) is undefined"
2982 if (Alignment && Name)
2983 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
2984
2985 // Do the pop.
2986 if (!PackContext.pop(Name)) {
2987 // If a name was specified then failure indicates the name
2988 // wasn't found. Otherwise failure indicates the stack was
2989 // empty.
2990 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
2991 Name ? "no record matching name" : "stack empty");
2992
2993 // FIXME: Warn about popping named records as MSVC does.
2994 } else {
2995 // Pop succeeded, set the new alignment if specified.
2996 if (Alignment)
2997 PackContext.setAlignment(AlignmentVal);
2998 }
2999 break;
3000
3001 default:
3002 assert(0 && "Invalid #pragma pack kind.");
3003 }
3004}
3005
3006bool PragmaPackStack::pop(IdentifierInfo *Name) {
3007 if (Stack.empty())
3008 return false;
3009
3010 // If name is empty just pop top.
3011 if (!Name) {
3012 Alignment = Stack.back().first;
3013 Stack.pop_back();
3014 return true;
3015 }
3016
3017 // Otherwise, find the named record.
3018 for (unsigned i = Stack.size(); i != 0; ) {
3019 --i;
3020 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3021 // Found it, pop up to and including this record.
3022 Alignment = Stack[i].first;
3023 Stack.erase(Stack.begin() + i, Stack.end());
3024 return true;
3025 }
3026 }
3027
3028 return false;
3029}