blob: 38a5c3780b7fca09b2eb30fb1b22fd1f9f85e739 [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 Gregor8210a8e2008-11-05 20:51:48 +0000803 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000804 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
805
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000806 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000807 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000808 // This is a C++ constructor declaration.
809 assert(D.getContext() == Declarator::MemberContext &&
810 "Constructors can only be declared in a member context");
811
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000812 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000813
814 // Create the new declaration
815 NewFD = CXXConstructorDecl::Create(Context,
816 cast<CXXRecordDecl>(CurContext),
817 D.getIdentifierLoc(), II, R,
818 isExplicit, isInline,
819 /*isImplicitlyDeclared=*/false);
820
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000821 if (isInvalidDecl)
822 NewFD->setInvalidDecl();
823 } else if (D.getKind() == Declarator::DK_Destructor) {
824 // This is a C++ destructor declaration.
825 assert(D.getContext() == Declarator::MemberContext &&
826 "Destructor can only be declared in a member context");
827
828 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
829
830 NewFD = CXXDestructorDecl::Create(Context,
831 cast<CXXRecordDecl>(CurContext),
832 D.getIdentifierLoc(), II, R,
833 isInline,
834 /*isImplicitlyDeclared=*/false);
835
836 if (isInvalidDecl)
837 NewFD->setInvalidDecl();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000838 } else if (D.getContext() == Declarator::MemberContext) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000839 // This is a C++ method declaration.
840 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
841 D.getIdentifierLoc(), II, R,
842 (SC == FunctionDecl::Static), isInline,
843 LastDeclarator);
844 } else {
845 NewFD = FunctionDecl::Create(Context, CurContext,
846 D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000847 II, R, SC, isInline, LastDeclarator,
848 // FIXME: Move to DeclGroup...
849 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000850 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000851 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000852 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000853
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000854 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000855 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000856 // The parser guarantees this is a string.
857 StringLiteral *SE = cast<StringLiteral>(E);
858 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
859 SE->getByteLength())));
860 }
861
Chris Lattner3e254fb2008-04-08 04:40:51 +0000862 // Copy the parameter declarations from the declarator D to
863 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000864 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000865 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
866
867 // Create Decl objects for each parameter, adding them to the
868 // FunctionDecl.
869 llvm::SmallVector<ParmVarDecl*, 16> Params;
870
871 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
872 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000873 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000874 // We let through "const void" here because Sema::GetTypeForDeclarator
875 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000876 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
877 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000878 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
879 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000880 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
881
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000882 // In C++, the empty parameter-type-list must be spelled "void"; a
883 // typedef of void is not permitted.
884 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000885 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000886 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
887 }
Eli Friedman769e7302008-08-25 21:31:01 +0000888 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000889 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
890 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
891 }
892
893 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +0000894 } else if (R->getAsTypedefType()) {
895 // When we're declaring a function with a typedef, as in the
896 // following example, we'll need to synthesize (unnamed)
897 // parameters for use in the declaration.
898 //
899 // @code
900 // typedef void fn(int);
901 // fn f;
902 // @endcode
903 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
904 if (!FT) {
905 // This is a typedef of a function with no prototype, so we
906 // don't need to do anything.
907 } else if ((FT->getNumArgs() == 0) ||
908 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
909 FT->getArgType(0)->isVoidType())) {
910 // This is a zero-argument function. We don't need to do anything.
911 } else {
912 // Synthesize a parameter for each argument type.
913 llvm::SmallVector<ParmVarDecl*, 16> Params;
914 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
915 ArgType != FT->arg_type_end(); ++ArgType) {
916 Params.push_back(ParmVarDecl::Create(Context, CurContext,
917 SourceLocation(), 0,
918 *ArgType, VarDecl::None,
919 0, 0));
920 }
921
922 NewFD->setParams(&Params[0], Params.size());
923 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000924 }
925
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000926 // C++ constructors and destructors are handled by separate
927 // routines, since they don't require any declaration merging (C++
928 // [class.mfct]p2) and they aren't ever pushed into scope, because
929 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
930 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
931 return ActOnConstructorDeclarator(Constructor);
932 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
933 return ActOnDestructorDeclarator(Destructor);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000934
Steve Narofff8a09432008-01-09 23:34:55 +0000935 // Merge the decl with the existing one if appropriate. Since C functions
936 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000937 if (PrevDecl &&
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000938 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, CurContext, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000939 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000940
941 // If C++, determine whether NewFD is an overload of PrevDecl or
942 // a declaration that requires merging. If it's an overload,
943 // there's no more work to do here; we'll just add the new
944 // function to the scope.
945 OverloadedFunctionDecl::function_iterator MatchedDecl;
946 if (!getLangOptions().CPlusPlus ||
947 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
948 Decl *OldDecl = PrevDecl;
949
950 // If PrevDecl was an overloaded function, extract the
951 // FunctionDecl that matched.
952 if (isa<OverloadedFunctionDecl>(PrevDecl))
953 OldDecl = *MatchedDecl;
954
955 // NewFD and PrevDecl represent declarations that need to be
956 // merged.
957 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
958
959 if (NewFD == 0) return 0;
960 if (Redeclaration) {
961 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
962
963 if (OldDecl == PrevDecl) {
964 // Remove the name binding for the previous
965 // declaration. We'll add the binding back later, but then
966 // it will refer to the new declaration (which will
967 // contain more information).
968 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
969 } else {
970 // We need to update the OverloadedFunctionDecl with the
971 // latest declaration of this function, so that name
972 // lookup will always refer to the latest declaration of
973 // this function.
974 *MatchedDecl = NewFD;
975
976 // Add the redeclaration to the current scope, since we'll
977 // be skipping PushOnScopeChains.
978 S->AddDecl(NewFD);
979
980 return NewFD;
981 }
982 }
Douglas Gregor42214c52008-04-21 02:02:58 +0000983 }
Chris Lattner4b009652007-07-25 00:24:17 +0000984 }
985 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000986
987 // In C++, check default arguments now that we have merged decls.
988 if (getLangOptions().CPlusPlus)
989 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +0000990 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000991 // Check that there are no default arguments (C++ only).
992 if (getLangOptions().CPlusPlus)
993 CheckExtraCXXDefaultArguments(D);
994
Ted Kremenek42730c52008-01-07 19:49:32 +0000995 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +0000996 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
997 D.getIdentifier()->getName());
998 InvalidDecl = true;
999 }
Chris Lattner4b009652007-07-25 00:24:17 +00001000
1001 VarDecl *NewVD;
1002 VarDecl::StorageClass SC;
1003 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001004 default: assert(0 && "Unknown storage class!");
1005 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1006 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1007 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1008 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1009 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1010 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Chris Lattner4b009652007-07-25 00:24:17 +00001011 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001012 if (D.getContext() == Declarator::MemberContext) {
1013 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1014 // This is a static data member for a C++ class.
1015 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
1016 D.getIdentifierLoc(), II,
1017 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001018 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001019 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001020 if (S->getFnParent() == 0) {
1021 // C99 6.9p2: The storage-class specifiers auto and register shall not
1022 // appear in the declaration specifiers in an external declaration.
1023 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1024 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1025 R.getAsString());
1026 InvalidDecl = true;
1027 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001028 }
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001029 NewVD = VarDecl::Create(Context, CurContext, D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +00001030 II, R, SC, LastDeclarator,
1031 // FIXME: Move to DeclGroup...
1032 D.getDeclSpec().getSourceRange().getBegin());
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001033 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001034 }
Chris Lattner4b009652007-07-25 00:24:17 +00001035 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001036 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001037
Daniel Dunbarced89142008-08-06 00:03:29 +00001038 // Handle GNU asm-label extension (encoded as an attribute).
1039 if (Expr *E = (Expr*) D.getAsmLabel()) {
1040 // The parser guarantees this is a string.
1041 StringLiteral *SE = cast<StringLiteral>(E);
1042 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1043 SE->getByteLength())));
1044 }
1045
Nate Begemanea583262008-03-14 18:07:10 +00001046 // Emit an error if an address space was applied to decl with local storage.
1047 // This includes arrays of objects with address space qualifiers, but not
1048 // automatic variables that point to other address spaces.
1049 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001050 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1051 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1052 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001053 }
Steve Narofff8a09432008-01-09 23:34:55 +00001054 // Merge the decl with the existing one if appropriate. If the decl is
1055 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00001056 if (PrevDecl && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001057 NewVD = MergeVarDecl(NewVD, PrevDecl);
1058 if (NewVD == 0) return 0;
1059 }
Chris Lattner4b009652007-07-25 00:24:17 +00001060 New = NewVD;
1061 }
1062
1063 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001064 if (II)
1065 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001066 // If any semantic error occurred, mark the decl as invalid.
1067 if (D.getInvalidType() || InvalidDecl)
1068 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001069
1070 return New;
1071}
1072
Steve Narofffc08f5e2008-10-27 11:34:16 +00001073void Sema::InitializerElementNotConstant(const Expr *Init) {
1074 Diag(Init->getExprLoc(),
1075 diag::err_init_element_not_constant, Init->getSourceRange());
1076}
1077
Eli Friedman02c22ce2008-05-20 13:48:25 +00001078bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1079 switch (Init->getStmtClass()) {
1080 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001081 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001082 return true;
1083 case Expr::ParenExprClass: {
1084 const ParenExpr* PE = cast<ParenExpr>(Init);
1085 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1086 }
1087 case Expr::CompoundLiteralExprClass:
1088 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1089 case Expr::DeclRefExprClass: {
1090 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001091 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1092 if (VD->hasGlobalStorage())
1093 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001094 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001095 return true;
1096 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001097 if (isa<FunctionDecl>(D))
1098 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001099 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001100 return true;
1101 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001102 case Expr::MemberExprClass: {
1103 const MemberExpr *M = cast<MemberExpr>(Init);
1104 if (M->isArrow())
1105 return CheckAddressConstantExpression(M->getBase());
1106 return CheckAddressConstantExpressionLValue(M->getBase());
1107 }
1108 case Expr::ArraySubscriptExprClass: {
1109 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1110 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1111 return CheckAddressConstantExpression(ASE->getBase()) ||
1112 CheckArithmeticConstantExpression(ASE->getIdx());
1113 }
1114 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001115 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001116 return false;
1117 case Expr::UnaryOperatorClass: {
1118 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1119
1120 // C99 6.6p9
1121 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001122 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001123
Steve Narofffc08f5e2008-10-27 11:34:16 +00001124 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001125 return true;
1126 }
1127 }
1128}
1129
1130bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1131 switch (Init->getStmtClass()) {
1132 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001133 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001134 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001135 case Expr::ParenExprClass:
1136 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001137 case Expr::StringLiteralClass:
1138 case Expr::ObjCStringLiteralClass:
1139 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001140 case Expr::CallExprClass:
1141 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1142 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1143 Builtin::BI__builtin___CFStringMakeConstantString)
1144 return false;
1145
Steve Narofffc08f5e2008-10-27 11:34:16 +00001146 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001147 return true;
1148
Eli Friedman02c22ce2008-05-20 13:48:25 +00001149 case Expr::UnaryOperatorClass: {
1150 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1151
1152 // C99 6.6p9
1153 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1154 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1155
1156 if (Exp->getOpcode() == UnaryOperator::Extension)
1157 return CheckAddressConstantExpression(Exp->getSubExpr());
1158
Steve Narofffc08f5e2008-10-27 11:34:16 +00001159 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001160 return true;
1161 }
1162 case Expr::BinaryOperatorClass: {
1163 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1164 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1165
1166 Expr *PExp = Exp->getLHS();
1167 Expr *IExp = Exp->getRHS();
1168 if (IExp->getType()->isPointerType())
1169 std::swap(PExp, IExp);
1170
1171 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1172 return CheckAddressConstantExpression(PExp) ||
1173 CheckArithmeticConstantExpression(IExp);
1174 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001175 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001176 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001177 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001178 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1179 // Check for implicit promotion
1180 if (SubExpr->getType()->isFunctionType() ||
1181 SubExpr->getType()->isArrayType())
1182 return CheckAddressConstantExpressionLValue(SubExpr);
1183 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001184
1185 // Check for pointer->pointer cast
1186 if (SubExpr->getType()->isPointerType())
1187 return CheckAddressConstantExpression(SubExpr);
1188
Eli Friedman1fad3c62008-08-25 20:46:57 +00001189 if (SubExpr->getType()->isIntegralType()) {
1190 // Check for the special-case of a pointer->int->pointer cast;
1191 // this isn't standard, but some code requires it. See
1192 // PR2720 for an example.
1193 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1194 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1195 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1196 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1197 if (IntWidth >= PointerWidth) {
1198 return CheckAddressConstantExpression(SubCast->getSubExpr());
1199 }
1200 }
1201 }
1202 }
1203 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001204 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001205 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001206
Steve Narofffc08f5e2008-10-27 11:34:16 +00001207 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001208 return true;
1209 }
1210 case Expr::ConditionalOperatorClass: {
1211 // FIXME: Should we pedwarn here?
1212 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1213 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001214 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001215 return true;
1216 }
1217 if (CheckArithmeticConstantExpression(Exp->getCond()))
1218 return true;
1219 if (Exp->getLHS() &&
1220 CheckAddressConstantExpression(Exp->getLHS()))
1221 return true;
1222 return CheckAddressConstantExpression(Exp->getRHS());
1223 }
1224 case Expr::AddrLabelExprClass:
1225 return false;
1226 }
1227}
1228
Eli Friedman998dffb2008-06-09 05:05:07 +00001229static const Expr* FindExpressionBaseAddress(const Expr* E);
1230
1231static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1232 switch (E->getStmtClass()) {
1233 default:
1234 return E;
1235 case Expr::ParenExprClass: {
1236 const ParenExpr* PE = cast<ParenExpr>(E);
1237 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1238 }
1239 case Expr::MemberExprClass: {
1240 const MemberExpr *M = cast<MemberExpr>(E);
1241 if (M->isArrow())
1242 return FindExpressionBaseAddress(M->getBase());
1243 return FindExpressionBaseAddressLValue(M->getBase());
1244 }
1245 case Expr::ArraySubscriptExprClass: {
1246 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1247 return FindExpressionBaseAddress(ASE->getBase());
1248 }
1249 case Expr::UnaryOperatorClass: {
1250 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1251
1252 if (Exp->getOpcode() == UnaryOperator::Deref)
1253 return FindExpressionBaseAddress(Exp->getSubExpr());
1254
1255 return E;
1256 }
1257 }
1258}
1259
1260static const Expr* FindExpressionBaseAddress(const Expr* E) {
1261 switch (E->getStmtClass()) {
1262 default:
1263 return E;
1264 case Expr::ParenExprClass: {
1265 const ParenExpr* PE = cast<ParenExpr>(E);
1266 return FindExpressionBaseAddress(PE->getSubExpr());
1267 }
1268 case Expr::UnaryOperatorClass: {
1269 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1270
1271 // C99 6.6p9
1272 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1273 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1274
1275 if (Exp->getOpcode() == UnaryOperator::Extension)
1276 return FindExpressionBaseAddress(Exp->getSubExpr());
1277
1278 return E;
1279 }
1280 case Expr::BinaryOperatorClass: {
1281 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1282
1283 Expr *PExp = Exp->getLHS();
1284 Expr *IExp = Exp->getRHS();
1285 if (IExp->getType()->isPointerType())
1286 std::swap(PExp, IExp);
1287
1288 return FindExpressionBaseAddress(PExp);
1289 }
1290 case Expr::ImplicitCastExprClass: {
1291 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1292
1293 // Check for implicit promotion
1294 if (SubExpr->getType()->isFunctionType() ||
1295 SubExpr->getType()->isArrayType())
1296 return FindExpressionBaseAddressLValue(SubExpr);
1297
1298 // Check for pointer->pointer cast
1299 if (SubExpr->getType()->isPointerType())
1300 return FindExpressionBaseAddress(SubExpr);
1301
1302 // We assume that we have an arithmetic expression here;
1303 // if we don't, we'll figure it out later
1304 return 0;
1305 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001306 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001307 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1308
1309 // Check for pointer->pointer cast
1310 if (SubExpr->getType()->isPointerType())
1311 return FindExpressionBaseAddress(SubExpr);
1312
1313 // We assume that we have an arithmetic expression here;
1314 // if we don't, we'll figure it out later
1315 return 0;
1316 }
1317 }
1318}
1319
Eli Friedman02c22ce2008-05-20 13:48:25 +00001320bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1321 switch (Init->getStmtClass()) {
1322 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001323 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001324 return true;
1325 case Expr::ParenExprClass: {
1326 const ParenExpr* PE = cast<ParenExpr>(Init);
1327 return CheckArithmeticConstantExpression(PE->getSubExpr());
1328 }
1329 case Expr::FloatingLiteralClass:
1330 case Expr::IntegerLiteralClass:
1331 case Expr::CharacterLiteralClass:
1332 case Expr::ImaginaryLiteralClass:
1333 case Expr::TypesCompatibleExprClass:
1334 case Expr::CXXBoolLiteralExprClass:
1335 return false;
1336 case Expr::CallExprClass: {
1337 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001338
1339 // Allow any constant foldable calls to builtins.
1340 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001341 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001342
Steve Narofffc08f5e2008-10-27 11:34:16 +00001343 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001344 return true;
1345 }
1346 case Expr::DeclRefExprClass: {
1347 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1348 if (isa<EnumConstantDecl>(D))
1349 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001350 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001351 return true;
1352 }
1353 case Expr::CompoundLiteralExprClass:
1354 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1355 // but vectors are allowed to be magic.
1356 if (Init->getType()->isVectorType())
1357 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001358 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001359 return true;
1360 case Expr::UnaryOperatorClass: {
1361 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1362
1363 switch (Exp->getOpcode()) {
1364 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1365 // See C99 6.6p3.
1366 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001367 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001368 return true;
1369 case UnaryOperator::SizeOf:
1370 case UnaryOperator::AlignOf:
1371 case UnaryOperator::OffsetOf:
1372 // sizeof(E) is a constantexpr if and only if E is not evaluted.
1373 // See C99 6.5.3.4p2 and 6.6p3.
1374 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1375 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001376 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001377 return true;
1378 case UnaryOperator::Extension:
1379 case UnaryOperator::LNot:
1380 case UnaryOperator::Plus:
1381 case UnaryOperator::Minus:
1382 case UnaryOperator::Not:
1383 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1384 }
1385 }
1386 case Expr::SizeOfAlignOfTypeExprClass: {
1387 const SizeOfAlignOfTypeExpr *Exp = cast<SizeOfAlignOfTypeExpr>(Init);
1388 // Special check for void types, which are allowed as an extension
1389 if (Exp->getArgumentType()->isVoidType())
1390 return false;
1391 // alignof always evaluates to a constant.
1392 // FIXME: is sizeof(int[3.0]) a constant expression?
1393 if (Exp->isSizeOf() && !Exp->getArgumentType()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001394 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001395 return true;
1396 }
1397 return false;
1398 }
1399 case Expr::BinaryOperatorClass: {
1400 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1401
1402 if (Exp->getLHS()->getType()->isArithmeticType() &&
1403 Exp->getRHS()->getType()->isArithmeticType()) {
1404 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1405 CheckArithmeticConstantExpression(Exp->getRHS());
1406 }
1407
Eli Friedman998dffb2008-06-09 05:05:07 +00001408 if (Exp->getLHS()->getType()->isPointerType() &&
1409 Exp->getRHS()->getType()->isPointerType()) {
1410 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1411 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1412
1413 // Only allow a null (constant integer) base; we could
1414 // allow some additional cases if necessary, but this
1415 // is sufficient to cover offsetof-like constructs.
1416 if (!LHSBase && !RHSBase) {
1417 return CheckAddressConstantExpression(Exp->getLHS()) ||
1418 CheckAddressConstantExpression(Exp->getRHS());
1419 }
1420 }
1421
Steve Narofffc08f5e2008-10-27 11:34:16 +00001422 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001423 return true;
1424 }
1425 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001426 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001427 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001428 if (SubExpr->getType()->isArithmeticType())
1429 return CheckArithmeticConstantExpression(SubExpr);
1430
Eli Friedman266df142008-09-02 09:37:00 +00001431 if (SubExpr->getType()->isPointerType()) {
1432 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1433 // If the pointer has a null base, this is an offsetof-like construct
1434 if (!Base)
1435 return CheckAddressConstantExpression(SubExpr);
1436 }
1437
Steve Narofffc08f5e2008-10-27 11:34:16 +00001438 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001439 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001440 }
1441 case Expr::ConditionalOperatorClass: {
1442 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001443
1444 // If GNU extensions are disabled, we require all operands to be arithmetic
1445 // constant expressions.
1446 if (getLangOptions().NoExtensions) {
1447 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1448 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1449 CheckArithmeticConstantExpression(Exp->getRHS());
1450 }
1451
1452 // Otherwise, we have to emulate some of the behavior of fold here.
1453 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1454 // because it can constant fold things away. To retain compatibility with
1455 // GCC code, we see if we can fold the condition to a constant (which we
1456 // should always be able to do in theory). If so, we only require the
1457 // specified arm of the conditional to be a constant. This is a horrible
1458 // hack, but is require by real world code that uses __builtin_constant_p.
1459 APValue Val;
1460 if (!Exp->getCond()->tryEvaluate(Val, Context)) {
1461 // If the tryEvaluate couldn't fold it, CheckArithmeticConstantExpression
1462 // won't be able to either. Use it to emit the diagnostic though.
1463 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
1464 assert(Res && "tryEvaluate couldn't evaluate this constant?");
1465 return Res;
1466 }
1467
1468 // Verify that the side following the condition is also a constant.
1469 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1470 if (Val.getInt() == 0)
1471 std::swap(TrueSide, FalseSide);
1472
1473 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001474 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001475
1476 // Okay, the evaluated side evaluates to a constant, so we accept this.
1477 // Check to see if the other side is obviously not a constant. If so,
1478 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001479 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001480 Diag(Init->getExprLoc(),
1481 diag::ext_typecheck_expression_not_constant_but_accepted,
1482 FalseSide->getSourceRange());
1483 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001484 }
1485 }
1486}
1487
1488bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001489 Init = Init->IgnoreParens();
1490
Eli Friedman02c22ce2008-05-20 13:48:25 +00001491 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1492 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1493 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1494
Nuno Lopese7280452008-07-07 16:46:50 +00001495 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1496 return CheckForConstantInitializer(e->getInitializer(), DclT);
1497
Eli Friedman02c22ce2008-05-20 13:48:25 +00001498 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1499 unsigned numInits = Exp->getNumInits();
1500 for (unsigned i = 0; i < numInits; i++) {
1501 // FIXME: Need to get the type of the declaration for C++,
1502 // because it could be a reference?
1503 if (CheckForConstantInitializer(Exp->getInit(i),
1504 Exp->getInit(i)->getType()))
1505 return true;
1506 }
1507 return false;
1508 }
1509
1510 if (Init->isNullPointerConstant(Context))
1511 return false;
1512 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001513 QualType InitTy = Context.getCanonicalType(Init->getType())
1514 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001515 if (InitTy == Context.BoolTy) {
1516 // Special handling for pointers implicitly cast to bool;
1517 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1518 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1519 Expr* SubE = ICE->getSubExpr();
1520 if (SubE->getType()->isPointerType() ||
1521 SubE->getType()->isArrayType() ||
1522 SubE->getType()->isFunctionType()) {
1523 return CheckAddressConstantExpression(Init);
1524 }
1525 }
1526 } else if (InitTy->isIntegralType()) {
1527 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001528 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001529 SubE = CE->getSubExpr();
1530 // Special check for pointer cast to int; we allow as an extension
1531 // an address constant cast to an integer if the integer
1532 // is of an appropriate width (this sort of code is apparently used
1533 // in some places).
1534 // FIXME: Add pedwarn?
1535 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1536 if (SubE && (SubE->getType()->isPointerType() ||
1537 SubE->getType()->isArrayType() ||
1538 SubE->getType()->isFunctionType())) {
1539 unsigned IntWidth = Context.getTypeSize(Init->getType());
1540 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1541 if (IntWidth >= PointerWidth)
1542 return CheckAddressConstantExpression(Init);
1543 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001544 }
1545
1546 return CheckArithmeticConstantExpression(Init);
1547 }
1548
1549 if (Init->getType()->isPointerType())
1550 return CheckAddressConstantExpression(Init);
1551
Eli Friedman25086f02008-05-30 18:14:48 +00001552 // An array type at the top level that isn't an init-list must
1553 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001554 if (Init->getType()->isArrayType())
1555 return false;
1556
Nuno Lopes1dc26762008-09-01 18:42:41 +00001557 if (Init->getType()->isFunctionType())
1558 return false;
1559
Steve Naroffdff3fb22008-10-02 17:12:56 +00001560 // Allow block exprs at top level.
1561 if (Init->getType()->isBlockPointerType())
1562 return false;
1563
Steve Narofffc08f5e2008-10-27 11:34:16 +00001564 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001565 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001566}
1567
Steve Naroff6a0e2092007-09-12 14:07:44 +00001568void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001569 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001570 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001571 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001572
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001573 // If there is no declaration, there was an error parsing it. Just ignore
1574 // the initializer.
1575 if (RealDecl == 0) {
1576 delete Init;
1577 return;
1578 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001579
Steve Naroff420d0f52007-09-12 20:13:48 +00001580 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1581 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001582 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1583 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001584 RealDecl->setInvalidDecl();
1585 return;
1586 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001587 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001588 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001589 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001590 if (VDecl->isBlockVarDecl()) {
1591 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001592 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001593 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001594 VDecl->setInvalidDecl();
1595 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001596 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1597 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001598 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001599
1600 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1601 if (!getLangOptions().CPlusPlus) {
1602 if (SC == VarDecl::Static) // C99 6.7.8p4.
1603 CheckForConstantInitializer(Init, DclT);
1604 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001605 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001606 } else if (VDecl->isFileVarDecl()) {
1607 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001608 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001609 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00001610 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1611 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001612 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001613
Anders Carlssonea7140a2008-08-22 05:00:02 +00001614 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1615 if (!getLangOptions().CPlusPlus) {
1616 // C99 6.7.8p4. All file scoped initializers need to be constant.
1617 CheckForConstantInitializer(Init, DclT);
1618 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001619 }
1620 // If the type changed, it means we had an incomplete type that was
1621 // completed by the initializer. For example:
1622 // int ary[] = { 1, 3, 5 };
1623 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001624 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001625 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001626 Init->setType(DclT);
1627 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001628
1629 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001630 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001631 return;
1632}
1633
Douglas Gregor81c29152008-10-29 00:13:59 +00001634void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1635 Decl *RealDecl = static_cast<Decl *>(dcl);
1636
1637 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1638 QualType Type = Var->getType();
1639 // C++ [dcl.init.ref]p3:
1640 // The initializer can be omitted for a reference only in a
1641 // parameter declaration (8.3.5), in the declaration of a
1642 // function return type, in the declaration of a class member
1643 // within its class declaration (9.2), and where the extern
1644 // specifier is explicitly used.
Douglas Gregor5870a952008-11-03 20:45:27 +00001645 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001646 Diag(Var->getLocation(),
1647 diag::err_reference_var_requires_init,
1648 Var->getName(),
1649 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor5870a952008-11-03 20:45:27 +00001650 Var->setInvalidDecl();
1651 return;
1652 }
1653
1654 // C++ [dcl.init]p9:
1655 //
1656 // If no initializer is specified for an object, and the object
1657 // is of (possibly cv-qualified) non-POD class type (or array
1658 // thereof), the object shall be default-initialized; if the
1659 // object is of const-qualified type, the underlying class type
1660 // shall have a user-declared default constructor.
1661 if (getLangOptions().CPlusPlus) {
1662 QualType InitType = Type;
1663 if (const ArrayType *Array = Context.getAsArrayType(Type))
1664 InitType = Array->getElementType();
1665 if (InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001666 const CXXConstructorDecl *Constructor
1667 = PerformInitializationByConstructor(InitType, 0, 0,
1668 Var->getLocation(),
1669 SourceRange(Var->getLocation(),
1670 Var->getLocation()),
1671 Var->getName(),
1672 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00001673 if (!Constructor)
1674 Var->setInvalidDecl();
1675 }
1676 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001677
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001678#if 0
1679 // FIXME: Temporarily disabled because we are not properly parsing
1680 // linkage specifications on declarations, e.g.,
1681 //
1682 // extern "C" const CGPoint CGPointerZero;
1683 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001684 // C++ [dcl.init]p9:
1685 //
1686 // If no initializer is specified for an object, and the
1687 // object is of (possibly cv-qualified) non-POD class type (or
1688 // array thereof), the object shall be default-initialized; if
1689 // the object is of const-qualified type, the underlying class
1690 // type shall have a user-declared default
1691 // constructor. Otherwise, if no initializer is specified for
1692 // an object, the object and its subobjects, if any, have an
1693 // indeterminate initial value; if the object or any of its
1694 // subobjects are of const-qualified type, the program is
1695 // ill-formed.
1696 //
1697 // This isn't technically an error in C, so we don't diagnose it.
1698 //
1699 // FIXME: Actually perform the POD/user-defined default
1700 // constructor check.
1701 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001702 Context.getCanonicalType(Type).isConstQualified() &&
1703 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor81c29152008-10-29 00:13:59 +00001704 Diag(Var->getLocation(),
1705 diag::err_const_var_requires_init,
1706 Var->getName(),
1707 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001708#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00001709 }
1710}
1711
Chris Lattner4b009652007-07-25 00:24:17 +00001712/// The declarators are chained together backwards, reverse the list.
1713Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1714 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001715 Decl *GroupDecl = static_cast<Decl*>(group);
1716 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001717 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001718
1719 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1720 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001721 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001722 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001723 else { // reverse the list.
1724 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001725 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001726 Group->setNextDeclarator(NewGroup);
1727 NewGroup = Group;
1728 Group = Next;
1729 }
1730 }
1731 // Perform semantic analysis that depends on having fully processed both
1732 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001733 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001734 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1735 if (!IDecl)
1736 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001737 QualType T = IDecl->getType();
1738
1739 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1740 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001741 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1742 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001743 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001744 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1745 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001746 }
1747 }
1748 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1749 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001750 if (IDecl->isBlockVarDecl() &&
1751 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001752 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001753 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1754 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001755 IDecl->setInvalidDecl();
1756 }
1757 }
1758 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1759 // object that has file scope without an initializer, and without a
1760 // storage-class specifier or with the storage-class specifier "static",
1761 // constitutes a tentative definition. Note: A tentative definition with
1762 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001763 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001764 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001765 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1766 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001767 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001768 // C99 6.9.2p3: If the declaration of an identifier for an object is
1769 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1770 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001771 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1772 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001773 IDecl->setInvalidDecl();
1774 }
1775 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001776 if (IDecl->isFileVarDecl())
1777 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001778 }
1779 return NewGroup;
1780}
Steve Naroff91b03f72007-08-28 03:03:08 +00001781
Chris Lattner3e254fb2008-04-08 04:40:51 +00001782/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1783/// to introduce parameters into function prototype scope.
1784Sema::DeclTy *
1785Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00001786 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001787
1788 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001789 VarDecl::StorageClass StorageClass = VarDecl::None;
1790 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1791 StorageClass = VarDecl::Register;
1792 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001793 Diag(DS.getStorageClassSpecLoc(),
1794 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001795 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001796 }
1797 if (DS.isThreadSpecified()) {
1798 Diag(DS.getThreadSpecLoc(),
1799 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001800 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001801 }
1802
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001803 // Check that there are no default arguments inside the type of this
1804 // parameter (C++ only).
1805 if (getLangOptions().CPlusPlus)
1806 CheckExtraCXXDefaultArguments(D);
1807
Chris Lattner3e254fb2008-04-08 04:40:51 +00001808 // In this context, we *do not* check D.getInvalidType(). If the declarator
1809 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1810 // though it will not reflect the user specified type.
1811 QualType parmDeclType = GetTypeForDeclarator(D, S);
1812
1813 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1814
Chris Lattner4b009652007-07-25 00:24:17 +00001815 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1816 // Can this happen for params? We already checked that they don't conflict
1817 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001818 IdentifierInfo *II = D.getIdentifier();
1819 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1820 if (S->isDeclScope(PrevDecl)) {
1821 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1822 dyn_cast<NamedDecl>(PrevDecl)->getName());
1823
1824 // Recover by removing the name
1825 II = 0;
1826 D.SetIdentifier(0, D.getIdentifierLoc());
1827 }
Chris Lattner4b009652007-07-25 00:24:17 +00001828 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001829
1830 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1831 // Doing the promotion here has a win and a loss. The win is the type for
1832 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1833 // code generator). The loss is the orginal type isn't preserved. For example:
1834 //
1835 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1836 // int blockvardecl[5];
1837 // sizeof(parmvardecl); // size == 4
1838 // sizeof(blockvardecl); // size == 20
1839 // }
1840 //
1841 // For expressions, all implicit conversions are captured using the
1842 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1843 //
1844 // FIXME: If a source translation tool needs to see the original type, then
1845 // we need to consider storing both types (in ParmVarDecl)...
1846 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001847 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001848 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001849 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001850 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001851 parmDeclType = Context.getPointerType(parmDeclType);
1852
Chris Lattner3e254fb2008-04-08 04:40:51 +00001853 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1854 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001855 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001856 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001857
Chris Lattner3e254fb2008-04-08 04:40:51 +00001858 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001859 New->setInvalidDecl();
1860
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001861 if (II)
1862 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001863
Chris Lattner9b384ca2008-06-29 00:02:00 +00001864 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001865 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001866
Chris Lattner4b009652007-07-25 00:24:17 +00001867}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001868
Chris Lattnerea148702007-10-09 17:14:05 +00001869Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001870 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001871 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1872 "Not a function declarator!");
1873 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001874
Chris Lattner4b009652007-07-25 00:24:17 +00001875 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
1876 // for a K&R function.
1877 if (!FTI.hasPrototype) {
1878 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001879 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001880 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
1881 FTI.ArgInfo[i].Ident->getName());
1882 // Implicitly declare the argument as type 'int' for lack of a better
1883 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001884 DeclSpec DS;
1885 const char* PrevSpec; // unused
1886 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
1887 PrevSpec);
1888 Declarator ParamD(DS, Declarator::KNRTypeListContext);
1889 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
1890 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00001891 }
1892 }
Chris Lattner4b009652007-07-25 00:24:17 +00001893 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001894 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00001895 }
1896
1897 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00001898
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001899 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001900 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001901}
1902
1903Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
1904 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00001905 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00001906
1907 // See if this is a redefinition.
1908 const FunctionDecl *Definition;
1909 if (FD->getBody(Definition)) {
1910 Diag(FD->getLocation(), diag::err_redefinition,
1911 FD->getName());
1912 Diag(Definition->getLocation(), diag::err_previous_definition);
1913 }
1914
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001915 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001916
1917 // Check the validity of our function parameters
1918 CheckParmsForFunctionDef(FD);
1919
1920 // Introduce our parameters into the function scope
1921 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
1922 ParmVarDecl *Param = FD->getParamDecl(p);
1923 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001924 if (Param->getIdentifier())
1925 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00001926 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001927
Chris Lattner4b009652007-07-25 00:24:17 +00001928 return FD;
1929}
1930
Steve Naroff99ee4302007-11-11 23:20:51 +00001931Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
1932 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001933 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001934 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001935 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00001936 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00001937 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00001938 } else
1939 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00001940 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00001941 // Verify and clean out per-function state.
1942
1943 // Check goto/label use.
1944 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
1945 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
1946 // Verify that we have no forward references left. If so, there was a goto
1947 // or address of a label taken, but no definition of it. Label fwd
1948 // definitions are indicated with a null substmt.
1949 if (I->second->getSubStmt() == 0) {
1950 LabelStmt *L = I->second;
1951 // Emit error.
1952 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
1953
1954 // At this point, we have gotos that use the bogus label. Stitch it into
1955 // the function body so that they aren't leaked and that the AST is well
1956 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00001957 if (Body) {
1958 L->setSubStmt(new NullStmt(L->getIdentLoc()));
1959 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
1960 } else {
1961 // The whole function wasn't parsed correctly, just delete this.
1962 delete L;
1963 }
Chris Lattner4b009652007-07-25 00:24:17 +00001964 }
1965 }
1966 LabelMap.clear();
1967
Steve Naroff99ee4302007-11-11 23:20:51 +00001968 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00001969}
1970
Chris Lattner4b009652007-07-25 00:24:17 +00001971/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
1972/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00001973ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
1974 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001975 // Extension in C99. Legal in C90, but warn about it.
1976 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00001977 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00001978 else
Chris Lattner4b009652007-07-25 00:24:17 +00001979 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
1980
1981 // FIXME: handle stuff like:
1982 // void foo() { extern float X(); }
1983 // void bar() { X(); } <-- implicit decl for X in another scope.
1984
1985 // Set a Declarator for the implicit definition: int foo();
1986 const char *Dummy;
1987 DeclSpec DS;
1988 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
1989 Error = Error; // Silence warning.
1990 assert(!Error && "Error setting up implicit decl!");
1991 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00001992 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00001993 D.SetIdentifier(&II, Loc);
1994
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00001995 // Insert this function into translation-unit scope.
1996
1997 DeclContext *PrevDC = CurContext;
1998 CurContext = Context.getTranslationUnitDecl();
1999
Steve Naroff9104f3c2008-04-04 14:32:09 +00002000 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002001 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002002 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002003
2004 CurContext = PrevDC;
2005
Steve Naroff9104f3c2008-04-04 14:32:09 +00002006 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002007}
2008
2009
Chris Lattner82bb4792007-11-14 06:34:38 +00002010TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002011 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002012 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002013 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002014
2015 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002016 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2017 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002018 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002019 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002020 if (D.getInvalidType())
2021 NewTD->setInvalidDecl();
2022 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002023}
2024
Steve Naroff0acc9c92007-09-15 18:49:24 +00002025/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002026/// former case, Name will be non-null. In the later case, Name will be null.
2027/// TagType indicates what kind of tag this is. TK indicates whether this is a
2028/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002029Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Chris Lattner4b009652007-07-25 00:24:17 +00002030 SourceLocation KWLoc, IdentifierInfo *Name,
2031 SourceLocation NameLoc, AttributeList *Attr) {
2032 // If this is a use of an existing tag, it must have a name.
2033 assert((Name != 0 || TK == TK_Definition) &&
2034 "Nameless record must be a definition!");
2035
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002036 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002037 switch (TagType) {
2038 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002039 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2040 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2041 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2042 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002043 }
2044
Ted Kremenek46a837c2008-09-05 17:16:31 +00002045 // Two code paths: a new one for structs/unions/classes where we create
2046 // separate decls for forward declarations, and an old (eventually to
2047 // be removed) code path for enums.
2048 if (Kind != TagDecl::TK_enum)
2049 return ActOnTagStruct(S, Kind, TK, KWLoc, Name, NameLoc, Attr);
2050
Chris Lattner4b009652007-07-25 00:24:17 +00002051 // If this is a named struct, check to see if there was a previous forward
2052 // declaration or definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002053 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
Ted Kremenekd4434152008-09-02 21:26:19 +00002054 ScopedDecl *PrevDecl =
2055 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
2056
2057 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002058 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2059 "unexpected Decl type");
2060 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002061 // If this is a use of a previous tag, or if the tag is already declared
2062 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002063 // rementions the tag), reuse the decl.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002064 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002065 // Make sure that this wasn't declared as an enum and now used as a
2066 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002067 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002068 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2069 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002070 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002071 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002072 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002073 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002074 // If this is a use or a forward declaration, we're good.
2075 if (TK != TK_Definition)
2076 return PrevDecl;
2077
2078 // Diagnose attempts to redefine a tag.
2079 if (PrevTagDecl->isDefinition()) {
2080 Diag(NameLoc, diag::err_redefinition, Name->getName());
2081 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2082 // If this is a redefinition, recover by making this struct be
2083 // anonymous, which will make any later references get the previous
2084 // definition.
2085 Name = 0;
2086 } else {
2087 // Okay, this is definition of a previously declared or referenced
2088 // tag. Move the location of the decl to be the definition site.
2089 PrevDecl->setLocation(NameLoc);
2090 return PrevDecl;
2091 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002092 }
Chris Lattner4b009652007-07-25 00:24:17 +00002093 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002094 // If we get here, this is a definition of a new struct type in a nested
2095 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2096 // type.
2097 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002098 // PrevDecl is a namespace.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002099 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002100 // The tag name clashes with a namespace name, issue an error and
2101 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002102 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2103 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2104 Name = 0;
2105 }
Chris Lattner4b009652007-07-25 00:24:17 +00002106 }
Chris Lattner4b009652007-07-25 00:24:17 +00002107 }
2108
2109 // If there is an identifier, use the location of the identifier as the
2110 // location of the decl, otherwise use the location of the struct/union
2111 // keyword.
2112 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2113
2114 // Otherwise, if this is the first time we've seen this tag, create the decl.
2115 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002116 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002117 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2118 // enum X { A, B, C } D; D should chain to X.
Chris Lattnereee57c02008-04-04 06:12:32 +00002119 New = EnumDecl::Create(Context, CurContext, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002120 // If this is an undefined enum, warn.
2121 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002122 } else {
2123 // struct/union/class
2124
Chris Lattner4b009652007-07-25 00:24:17 +00002125 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2126 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002127 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002128 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek2c984042008-09-05 01:34:33 +00002129 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002130 else
Ted Kremenek2c984042008-09-05 01:34:33 +00002131 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002132 }
Chris Lattner4b009652007-07-25 00:24:17 +00002133
2134 // If this has an identifier, add it to the scope stack.
2135 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002136 // The scope passed in may not be a decl scope. Zip up the scope tree until
2137 // we find one that is.
2138 while ((S->getFlags() & Scope::DeclScope) == 0)
2139 S = S->getParent();
2140
2141 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002142 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002143 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00002144
Chris Lattnerd7e83d82008-06-28 23:58:55 +00002145 if (Attr)
2146 ProcessDeclAttributeList(New, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002147 return New;
2148}
2149
Ted Kremenek46a837c2008-09-05 17:16:31 +00002150/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2151/// the logic for enums, we create separate decls for forward declarations.
2152/// This is called by ActOnTag, but eventually will replace its logic.
2153Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
2154 SourceLocation KWLoc, IdentifierInfo *Name,
2155 SourceLocation NameLoc, AttributeList *Attr) {
2156
2157 // If this is a named struct, check to see if there was a previous forward
2158 // declaration or definition.
2159 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2160 ScopedDecl *PrevDecl =
2161 dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag, S));
2162
2163 if (PrevDecl) {
2164 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2165 "unexpected Decl type");
2166
2167 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2168 // If this is a use of a previous tag, or if the tag is already declared
2169 // in the same scope (so that the definition/declaration completes or
2170 // rementions the tag), reuse the decl.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002171 if (TK == TK_Reference || isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002172 // Make sure that this wasn't declared as an enum and now used as a
2173 // struct or something similar.
2174 if (PrevTagDecl->getTagKind() != Kind) {
2175 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2176 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2177 // Recover by making this an anonymous redefinition.
2178 Name = 0;
2179 PrevDecl = 0;
2180 } else {
2181 // If this is a use, return the original decl.
2182
2183 // FIXME: In the future, return a variant or some other clue
2184 // for the consumer of this Decl to know it doesn't own it.
2185 // For our current ASTs this shouldn't be a problem, but will
2186 // need to be changed with DeclGroups.
2187 if (TK == TK_Reference)
2188 return PrevDecl;
2189
2190 // The new decl is a definition?
2191 if (TK == TK_Definition) {
2192 // Diagnose attempts to redefine a tag.
2193 if (RecordDecl* DefRecord =
2194 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2195 Diag(NameLoc, diag::err_redefinition, Name->getName());
2196 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2197 // If this is a redefinition, recover by making this struct be
2198 // anonymous, which will make any later references get the previous
2199 // definition.
2200 Name = 0;
2201 PrevDecl = 0;
2202 }
2203 // Okay, this is definition of a previously declared or referenced
2204 // tag. We're going to create a new Decl.
2205 }
2206 }
2207 // If we get here we have (another) forward declaration. Just create
2208 // a new decl.
2209 }
2210 else {
2211 // If we get here, this is a definition of a new struct type in a nested
2212 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2213 // new decl/type. We set PrevDecl to NULL so that the Records
2214 // have distinct types.
2215 PrevDecl = 0;
2216 }
2217 } else {
2218 // PrevDecl is a namespace.
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002219 if (isDeclInScope(PrevDecl, CurContext, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002220 // The tag name clashes with a namespace name, issue an error and
2221 // recover by making this tag be anonymous.
2222 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2223 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2224 Name = 0;
2225 }
2226 }
2227 }
2228
2229 // If there is an identifier, use the location of the identifier as the
2230 // location of the decl, otherwise use the location of the struct/union
2231 // keyword.
2232 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2233
2234 // Otherwise, if this is the first time we've seen this tag, create the decl.
2235 TagDecl *New;
2236
2237 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2238 // struct X { int A; } D; D should chain to X.
2239 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002240 // FIXME: Look for a way to use RecordDecl for simple structs.
Ted Kremenek46a837c2008-09-05 17:16:31 +00002241 New = CXXRecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2242 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2243 else
2244 New = RecordDecl::Create(Context, Kind, CurContext, Loc, Name,
2245 dyn_cast_or_null<RecordDecl>(PrevDecl));
2246
2247 // If this has an identifier, add it to the scope stack.
2248 if ((TK == TK_Definition || !PrevDecl) && Name) {
2249 // The scope passed in may not be a decl scope. Zip up the scope tree until
2250 // we find one that is.
2251 while ((S->getFlags() & Scope::DeclScope) == 0)
2252 S = S->getParent();
2253
2254 // Add it to the decl chain.
2255 PushOnScopeChains(New, S);
2256 }
Daniel Dunbar2cb762f2008-10-16 02:34:03 +00002257
2258 // Handle #pragma pack: if the #pragma pack stack has non-default
2259 // alignment, make up a packed attribute for this decl. These
2260 // attributes are checked when the ASTContext lays out the
2261 // structure.
2262 //
2263 // It is important for implementing the correct semantics that this
2264 // happen here (in act on tag decl). The #pragma pack stack is
2265 // maintained as a result of parser callbacks which can occur at
2266 // many points during the parsing of a struct declaration (because
2267 // the #pragma tokens are effectively skipped over during the
2268 // parsing of the struct).
2269 if (unsigned Alignment = PackContext.getAlignment())
2270 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek46a837c2008-09-05 17:16:31 +00002271
2272 if (Attr)
2273 ProcessDeclAttributeList(New, Attr);
2274
2275 return New;
2276}
2277
2278
Chris Lattner1bf58f62008-06-21 19:39:06 +00002279/// Collect the instance variables declared in an Objective-C object. Used in
2280/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002281static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002282 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002283 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002284 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2285
2286 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00002287 for (ObjCInterfaceDecl::ivar_iterator
2288 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2289
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002290 ObjCIvarDecl* ID = *I;
2291 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2292 ID->getIdentifier(),
2293 ID->getType(),
2294 ID->getBitWidth()));
2295 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002296}
2297
2298/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2299/// instance variables of ClassName into Decls.
2300void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2301 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002302 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002303 // Check that ClassName is a valid class
2304 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2305 if (!Class) {
2306 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2307 return;
2308 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002309 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002310 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00002311}
2312
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002313QualType Sema::TryFixInvalidVariablyModifiedType(QualType T) {
2314 // This method tries to turn a variable array into a constant
2315 // array even when the size isn't an ICE. This is necessary
2316 // for compatibility with code that depends on gcc's buggy
2317 // constant expression folding, like struct {char x[(int)(char*)2];}
2318 if (const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T)) {
Anders Carlssonc7436af2008-07-03 04:20:39 +00002319 APValue Result;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002320 if (VLATy->getSizeExpr() &&
Chris Lattner334b1942008-07-11 19:19:21 +00002321 VLATy->getSizeExpr()->tryEvaluate(Result, Context) && Result.isInt()) {
2322 llvm::APSInt &Res = Result.getInt();
2323 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2324 return Context.getConstantArrayType(VLATy->getElementType(),
2325 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002326 }
2327 }
2328 return QualType();
2329}
2330
Steve Naroff0acc9c92007-09-15 18:49:24 +00002331/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002332/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002333Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00002334 SourceLocation DeclStart,
2335 Declarator &D, ExprTy *BitfieldWidth) {
2336 IdentifierInfo *II = D.getIdentifier();
2337 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002338 SourceLocation Loc = DeclStart;
2339 if (II) Loc = D.getIdentifierLoc();
2340
2341 // FIXME: Unnamed fields can be handled in various different ways, for
2342 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00002343
Chris Lattner4b009652007-07-25 00:24:17 +00002344 if (BitWidth) {
2345 // TODO: Validate.
2346 //printf("WARNING: BITFIELDS IGNORED!\n");
2347
2348 // 6.7.2.1p3
2349 // 6.7.2.1p4
2350
2351 } else {
2352 // Not a bitfield.
2353
2354 // validate II.
2355
2356 }
2357
2358 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002359 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2360 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00002361
Chris Lattner4b009652007-07-25 00:24:17 +00002362 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2363 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002364 if (T->isVariablyModifiedType()) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002365 QualType FixedTy = TryFixInvalidVariablyModifiedType(T);
2366 if (!FixedTy.isNull()) {
2367 Diag(Loc, diag::warn_illegal_constant_array_size, Loc);
2368 T = FixedTy;
2369 } else {
2370 // FIXME: This diagnostic needs work
2371 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2372 InvalidDecl = true;
2373 }
Chris Lattner4b009652007-07-25 00:24:17 +00002374 }
Chris Lattner4b009652007-07-25 00:24:17 +00002375 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002376 FieldDecl *NewFD;
2377
2378 if (getLangOptions().CPlusPlus) {
2379 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2380 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2381 Loc, II, T, BitWidth);
2382 if (II)
2383 PushOnScopeChains(NewFD, S);
2384 }
2385 else
2386 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002387
Chris Lattner9b384ca2008-06-29 00:02:00 +00002388 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002389
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002390 if (D.getInvalidType() || InvalidDecl)
2391 NewFD->setInvalidDecl();
2392 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002393}
2394
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002395/// TranslateIvarVisibility - Translate visibility from a token ID to an
2396/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002397static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002398TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002399 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002400 default: assert(0 && "Unknown visitibility kind");
2401 case tok::objc_private: return ObjCIvarDecl::Private;
2402 case tok::objc_public: return ObjCIvarDecl::Public;
2403 case tok::objc_protected: return ObjCIvarDecl::Protected;
2404 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002405 }
2406}
2407
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002408/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2409/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002410Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002411 SourceLocation DeclStart,
2412 Declarator &D, ExprTy *BitfieldWidth,
2413 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002414 IdentifierInfo *II = D.getIdentifier();
2415 Expr *BitWidth = (Expr*)BitfieldWidth;
2416 SourceLocation Loc = DeclStart;
2417 if (II) Loc = D.getIdentifierLoc();
2418
2419 // FIXME: Unnamed fields can be handled in various different ways, for
2420 // example, unnamed unions inject all members into the struct namespace!
2421
2422
2423 if (BitWidth) {
2424 // TODO: Validate.
2425 //printf("WARNING: BITFIELDS IGNORED!\n");
2426
2427 // 6.7.2.1p3
2428 // 6.7.2.1p4
2429
2430 } else {
2431 // Not a bitfield.
2432
2433 // validate II.
2434
2435 }
2436
2437 QualType T = GetTypeForDeclarator(D, S);
2438 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2439 bool InvalidDecl = false;
2440
2441 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2442 // than a variably modified type.
2443 if (T->isVariablyModifiedType()) {
2444 // FIXME: This diagnostic needs work
2445 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2446 InvalidDecl = true;
2447 }
2448
Ted Kremenek173dd312008-07-23 18:04:17 +00002449 // Get the visibility (access control) for this ivar.
2450 ObjCIvarDecl::AccessControl ac =
2451 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2452 : ObjCIvarDecl::None;
2453
2454 // Construct the decl.
2455 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002456 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002457
Ted Kremenek173dd312008-07-23 18:04:17 +00002458 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002459 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002460
2461 if (D.getInvalidType() || InvalidDecl)
2462 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002463
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002464 return NewID;
2465}
2466
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002467void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002468 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002469 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002470 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002471 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002472 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2473 assert(EnclosingDecl && "missing record or interface decl");
2474 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2475
Ted Kremenek46a837c2008-09-05 17:16:31 +00002476 if (Record)
2477 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2478 // Diagnose code like:
2479 // struct S { struct S {} X; };
2480 // We discover this when we complete the outer S. Reject and ignore the
2481 // outer S.
2482 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2483 DefRecord->getKindName());
2484 Diag(RecLoc, diag::err_previous_definition);
2485 Record->setInvalidDecl();
2486 return;
2487 }
2488
Chris Lattner4b009652007-07-25 00:24:17 +00002489 // Verify that all the fields are okay.
2490 unsigned NumNamedMembers = 0;
2491 llvm::SmallVector<FieldDecl*, 32> RecFields;
2492 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002493
Chris Lattner4b009652007-07-25 00:24:17 +00002494 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002495
Steve Naroff9bb759f2007-09-14 22:20:54 +00002496 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2497 assert(FD && "missing field decl");
2498
2499 // Remember all fields.
2500 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002501
2502 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002503 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002504
Chris Lattner4b009652007-07-25 00:24:17 +00002505 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002506 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002507 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002508 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002509 FD->setInvalidDecl();
2510 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002511 continue;
2512 }
Chris Lattner4b009652007-07-25 00:24:17 +00002513 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2514 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002515 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002516 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002517 FD->setInvalidDecl();
2518 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002519 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002520 }
Chris Lattner4b009652007-07-25 00:24:17 +00002521 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002522 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002523 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002524 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002525 FD->setInvalidDecl();
2526 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002527 continue;
2528 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002529 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002530 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2531 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002532 FD->setInvalidDecl();
2533 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002534 continue;
2535 }
Chris Lattner4b009652007-07-25 00:24:17 +00002536 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002537 if (Record)
2538 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002539 }
Chris Lattner4b009652007-07-25 00:24:17 +00002540 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2541 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002542 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002543 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2544 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002545 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002546 Record->setHasFlexibleArrayMember(true);
2547 } else {
2548 // If this is a struct/class and this is not the last element, reject
2549 // it. Note that GCC supports variable sized arrays in the middle of
2550 // structures.
2551 if (i != NumFields-1) {
2552 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2553 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002554 FD->setInvalidDecl();
2555 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002556 continue;
2557 }
Chris Lattner4b009652007-07-25 00:24:17 +00002558 // We support flexible arrays at the end of structs in other structs
2559 // as an extension.
2560 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2561 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002562 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002563 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002564 }
2565 }
2566 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002567 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002568 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002569 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2570 FD->getName());
2571 FD->setInvalidDecl();
2572 EnclosingDecl->setInvalidDecl();
2573 continue;
2574 }
Chris Lattner4b009652007-07-25 00:24:17 +00002575 // Keep track of the number of named members.
2576 if (IdentifierInfo *II = FD->getIdentifier()) {
2577 // Detect duplicate member names.
2578 if (!FieldIDs.insert(II)) {
2579 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2580 // Find the previous decl.
2581 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00002582 for (unsigned i = 0; ; ++i) {
2583 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00002584 if (RecFields[i]->getIdentifier() == II) {
2585 PrevLoc = RecFields[i]->getLocation();
2586 break;
2587 }
2588 }
2589 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002590 FD->setInvalidDecl();
2591 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002592 continue;
2593 }
2594 ++NumNamedMembers;
2595 }
Chris Lattner4b009652007-07-25 00:24:17 +00002596 }
2597
Chris Lattner4b009652007-07-25 00:24:17 +00002598 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002599 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002600 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002601 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2602 // Sema::ActOnFinishCXXClassDef.
2603 if (!isa<CXXRecordDecl>(Record))
2604 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002605 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002606 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2607 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2608 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2609 else if (ObjCImplementationDecl *IMPDecl =
2610 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002611 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2612 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002613 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002614 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002615 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002616
2617 if (Attr)
2618 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002619}
2620
Steve Naroff0acc9c92007-09-15 18:49:24 +00002621Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002622 DeclTy *lastEnumConst,
2623 SourceLocation IdLoc, IdentifierInfo *Id,
2624 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002625 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002626 EnumConstantDecl *LastEnumConst =
2627 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2628 Expr *Val = static_cast<Expr*>(val);
2629
Chris Lattnera7549902007-08-26 06:24:45 +00002630 // The scope passed in may not be a decl scope. Zip up the scope tree until
2631 // we find one that is.
2632 while ((S->getFlags() & Scope::DeclScope) == 0)
2633 S = S->getParent();
2634
Chris Lattner4b009652007-07-25 00:24:17 +00002635 // Verify that there isn't already something declared with this name in this
2636 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002637 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002638 // When in C++, we may get a TagDecl with the same name; in this case the
2639 // enum constant will 'hide' the tag.
2640 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2641 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002642 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002643 if (isa<EnumConstantDecl>(PrevDecl))
2644 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2645 else
2646 Diag(IdLoc, diag::err_redefinition, Id->getName());
2647 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002648 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002649 return 0;
2650 }
2651 }
2652
2653 llvm::APSInt EnumVal(32);
2654 QualType EltTy;
2655 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002656 // Make sure to promote the operand type to int.
2657 UsualUnaryConversions(Val);
2658
Chris Lattner4b009652007-07-25 00:24:17 +00002659 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2660 SourceLocation ExpLoc;
2661 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2662 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2663 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002664 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002665 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002666 } else {
2667 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002668 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002669 }
2670
2671 if (!Val) {
2672 if (LastEnumConst) {
2673 // Assign the last value + 1.
2674 EnumVal = LastEnumConst->getInitVal();
2675 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002676
2677 // Check for overflow on increment.
2678 if (EnumVal < LastEnumConst->getInitVal())
2679 Diag(IdLoc, diag::warn_enum_value_overflow);
2680
Chris Lattnere7f53a42007-08-27 17:37:24 +00002681 EltTy = LastEnumConst->getType();
2682 } else {
2683 // First value, set to zero.
2684 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002685 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002686 }
Chris Lattner4b009652007-07-25 00:24:17 +00002687 }
2688
Chris Lattnere4650482008-03-15 06:12:44 +00002689 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002690 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2691 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002692 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002693
2694 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002695 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002696 return New;
2697}
2698
Steve Naroffb0726b82008-08-07 14:08:16 +00002699// FIXME: For consistency with ActOnFields(), we should have the parser
2700// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002701void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002702 DeclTy **Elements, unsigned NumElements) {
2703 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002704
Steve Naroffb0726b82008-08-07 14:08:16 +00002705 if (Enum && Enum->isDefinition()) {
2706 // Diagnose code like:
2707 // enum e0 {
2708 // E0 = sizeof(enum e0 { E1 })
2709 // };
2710 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2711 Enum->getName());
2712 Diag(EnumLoc, diag::err_previous_definition);
2713 Enum->setInvalidDecl();
2714 return;
2715 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002716 // TODO: If the result value doesn't fit in an int, it must be a long or long
2717 // long value. ISO C does not support this, but GCC does as an extension,
2718 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002719 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002720
Chris Lattner206754a2007-08-28 06:15:15 +00002721 // Verify that all the values are okay, compute the size of the values, and
2722 // reverse the list.
2723 unsigned NumNegativeBits = 0;
2724 unsigned NumPositiveBits = 0;
2725
2726 // Keep track of whether all elements have type int.
2727 bool AllElementsInt = true;
2728
Chris Lattner4b009652007-07-25 00:24:17 +00002729 EnumConstantDecl *EltList = 0;
2730 for (unsigned i = 0; i != NumElements; ++i) {
2731 EnumConstantDecl *ECD =
2732 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2733 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002734
2735 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002736 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002737 assert(InitVal.getBitWidth() >= IntWidth &&
2738 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002739 if (InitVal.getBitWidth() > IntWidth) {
2740 llvm::APSInt V(InitVal);
2741 V.trunc(IntWidth);
2742 V.extend(InitVal.getBitWidth());
2743 if (V != InitVal)
2744 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002745 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002746 }
Chris Lattner206754a2007-08-28 06:15:15 +00002747
2748 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002749 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002750 NumPositiveBits = std::max(NumPositiveBits,
2751 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002752 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002753 NumNegativeBits = std::max(NumNegativeBits,
2754 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002755
Chris Lattner206754a2007-08-28 06:15:15 +00002756 // Keep track of whether every enum element has type int (very commmon).
2757 if (AllElementsInt)
2758 AllElementsInt = ECD->getType() == Context.IntTy;
2759
Chris Lattner4b009652007-07-25 00:24:17 +00002760 ECD->setNextDeclarator(EltList);
2761 EltList = ECD;
2762 }
2763
Chris Lattner206754a2007-08-28 06:15:15 +00002764 // Figure out the type that should be used for this enum.
2765 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2766 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002767 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002768
2769 if (NumNegativeBits) {
2770 // If there is a negative value, figure out the smallest integer type (of
2771 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002772 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002773 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002774 BestWidth = IntWidth;
2775 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002776 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002777
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002778 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002779 BestType = Context.LongTy;
2780 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002781 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002782
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002783 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002784 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2785 BestType = Context.LongLongTy;
2786 }
2787 }
2788 } else {
2789 // If there is no negative value, figure out which of uint, ulong, ulonglong
2790 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002791 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002792 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002793 BestWidth = IntWidth;
2794 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002795 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002796 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002797 } else {
2798 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002799 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002800 "How could an initializer get larger than ULL?");
2801 BestType = Context.UnsignedLongLongTy;
2802 }
2803 }
2804
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002805 // Loop over all of the enumerator constants, changing their types to match
2806 // the type of the enum if needed.
2807 for (unsigned i = 0; i != NumElements; ++i) {
2808 EnumConstantDecl *ECD =
2809 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2810 if (!ECD) continue; // Already issued a diagnostic.
2811
2812 // Standard C says the enumerators have int type, but we allow, as an
2813 // extension, the enumerators to be larger than int size. If each
2814 // enumerator value fits in an int, type it as an int, otherwise type it the
2815 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
2816 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002817 if (ECD->getType() == Context.IntTy) {
2818 // Make sure the init value is signed.
2819 llvm::APSInt IV = ECD->getInitVal();
2820 IV.setIsSigned(true);
2821 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002822 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002823 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002824
2825 // Determine whether the value fits into an int.
2826 llvm::APSInt InitVal = ECD->getInitVal();
2827 bool FitsInInt;
2828 if (InitVal.isUnsigned() || !InitVal.isNegative())
2829 FitsInInt = InitVal.getActiveBits() < IntWidth;
2830 else
2831 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
2832
2833 // If it fits into an integer type, force it. Otherwise force it to match
2834 // the enum decl type.
2835 QualType NewTy;
2836 unsigned NewWidth;
2837 bool NewSign;
2838 if (FitsInInt) {
2839 NewTy = Context.IntTy;
2840 NewWidth = IntWidth;
2841 NewSign = true;
2842 } else if (ECD->getType() == BestType) {
2843 // Already the right type!
2844 continue;
2845 } else {
2846 NewTy = BestType;
2847 NewWidth = BestWidth;
2848 NewSign = BestType->isSignedIntegerType();
2849 }
2850
2851 // Adjust the APSInt value.
2852 InitVal.extOrTrunc(NewWidth);
2853 InitVal.setIsSigned(NewSign);
2854 ECD->setInitVal(InitVal);
2855
2856 // Adjust the Expr initializer and type.
2857 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr()));
2858 ECD->setType(NewTy);
2859 }
Chris Lattner206754a2007-08-28 06:15:15 +00002860
Chris Lattner90a018d2007-08-28 18:24:31 +00002861 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002862 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00002863}
2864
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002865Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
2866 ExprTy *expr) {
2867 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
2868
Chris Lattner81db64a2008-03-16 00:16:02 +00002869 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00002870}
2871
Chris Lattner806a5f52008-01-12 07:05:38 +00002872Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00002873 SourceLocation LBrace,
2874 SourceLocation RBrace,
2875 const char *Lang,
2876 unsigned StrSize,
2877 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00002878 LinkageSpecDecl::LanguageIDs Language;
2879 Decl *dcl = static_cast<Decl *>(D);
2880 if (strncmp(Lang, "\"C\"", StrSize) == 0)
2881 Language = LinkageSpecDecl::lang_c;
2882 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
2883 Language = LinkageSpecDecl::lang_cxx;
2884 else {
2885 Diag(Loc, diag::err_bad_language);
2886 return 0;
2887 }
2888
2889 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00002890 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00002891}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00002892
2893void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
2894 ExprTy *alignment, SourceLocation PragmaLoc,
2895 SourceLocation LParenLoc, SourceLocation RParenLoc) {
2896 Expr *Alignment = static_cast<Expr *>(alignment);
2897
2898 // If specified then alignment must be a "small" power of two.
2899 unsigned AlignmentVal = 0;
2900 if (Alignment) {
2901 llvm::APSInt Val;
2902 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
2903 !Val.isPowerOf2() ||
2904 Val.getZExtValue() > 16) {
2905 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
2906 delete Alignment;
2907 return; // Ignore
2908 }
2909
2910 AlignmentVal = (unsigned) Val.getZExtValue();
2911 }
2912
2913 switch (Kind) {
2914 case Action::PPK_Default: // pack([n])
2915 PackContext.setAlignment(AlignmentVal);
2916 break;
2917
2918 case Action::PPK_Show: // pack(show)
2919 // Show the current alignment, making sure to show the right value
2920 // for the default.
2921 AlignmentVal = PackContext.getAlignment();
2922 // FIXME: This should come from the target.
2923 if (AlignmentVal == 0)
2924 AlignmentVal = 8;
2925 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
2926 break;
2927
2928 case Action::PPK_Push: // pack(push [, id] [, [n])
2929 PackContext.push(Name);
2930 // Set the new alignment if specified.
2931 if (Alignment)
2932 PackContext.setAlignment(AlignmentVal);
2933 break;
2934
2935 case Action::PPK_Pop: // pack(pop [, id] [, n])
2936 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
2937 // "#pragma pack(pop, identifier, n) is undefined"
2938 if (Alignment && Name)
2939 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
2940
2941 // Do the pop.
2942 if (!PackContext.pop(Name)) {
2943 // If a name was specified then failure indicates the name
2944 // wasn't found. Otherwise failure indicates the stack was
2945 // empty.
2946 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
2947 Name ? "no record matching name" : "stack empty");
2948
2949 // FIXME: Warn about popping named records as MSVC does.
2950 } else {
2951 // Pop succeeded, set the new alignment if specified.
2952 if (Alignment)
2953 PackContext.setAlignment(AlignmentVal);
2954 }
2955 break;
2956
2957 default:
2958 assert(0 && "Invalid #pragma pack kind.");
2959 }
2960}
2961
2962bool PragmaPackStack::pop(IdentifierInfo *Name) {
2963 if (Stack.empty())
2964 return false;
2965
2966 // If name is empty just pop top.
2967 if (!Name) {
2968 Alignment = Stack.back().first;
2969 Stack.pop_back();
2970 return true;
2971 }
2972
2973 // Otherwise, find the named record.
2974 for (unsigned i = Stack.size(); i != 0; ) {
2975 --i;
2976 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
2977 // Found it, pop up to and including this record.
2978 Alignment = Stack[i].first;
2979 Stack.erase(Stack.begin() + i, Stack.end());
2980 return true;
2981 }
2982 }
2983
2984 return false;
2985}