blob: ea2a3ad9a75d4bececca555ad2d85b568ecf85b7 [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
Douglas Gregorb0212bd2008-11-17 20:34:05 +000031Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000032 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000033 DeclContext *DC = 0;
34 if (SS) {
35 if (SS->isInvalid())
36 return 0;
37 DC = static_cast<DeclContext*>(SS->getScopeRep());
38 }
39 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroff6384a012008-04-02 14:35:35 +000040
Douglas Gregor1d661552008-04-13 21:07:44 +000041 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
42 isa<ObjCInterfaceDecl>(IIDecl) ||
43 isa<TagDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000044 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000045 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000046}
47
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000048DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000049 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000050 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000051 if (MD->isOutOfLineDefinition())
52 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000053
54 // A C++ inline method is parsed *after* the topmost class it was declared in
55 // is fully parsed (it's "complete").
56 // The parsing of a C++ inline method happens at the declaration context of
57 // the topmost (non-nested) class it is declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000058 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
59 DC = MD->getParent();
60 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getParent()))
61 DC = RD;
62
63 // Return the declaration context of the topmost class the inline method is
64 // declared in.
65 return DC;
66 }
67
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000068 if (isa<ObjCMethodDecl>(DC))
69 return Context.getTranslationUnitDecl();
70
71 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
72 return SD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000073
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000074 return DC->getParent();
75}
76
Chris Lattneref87a202008-04-22 18:39:57 +000077void Sema::PushDeclContext(DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000078 assert(getContainingDC(DC) == CurContext &&
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000079 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000080 CurContext = DC;
Chris Lattnereee57c02008-04-04 06:12:32 +000081}
82
Chris Lattnerf3874bc2008-04-06 04:47:34 +000083void Sema::PopDeclContext() {
84 assert(CurContext && "DeclContext imbalance!");
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000085 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000086}
87
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000088/// Add this decl to the scope shadowed decl chains.
89void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000090 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +000091
92 // C++ [basic.scope]p4:
93 // -- exactly one declaration shall declare a class name or
94 // enumeration name that is not a typedef name and the other
95 // declarations shall all refer to the same object or
96 // enumerator, or all refer to functions and function templates;
97 // in this case the class name or enumeration name is hidden.
98 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
99 // We are pushing the name of a tag (enum or class).
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000100 IdentifierResolver::iterator
101 I = IdResolver.begin(TD->getIdentifier(),
102 TD->getDeclContext(), false/*LookInParentCtx*/);
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000103 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000104 // There is already a declaration with the same name in the same
105 // scope. It must be found before we find the new declaration,
106 // so swap the order on the shadowed declaration chain.
107
Argiris Kirtzidis94805232008-07-17 17:49:50 +0000108 IdResolver.AddShadowedDecl(TD, *I);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000109 return;
110 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000111 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
112 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregord2baafd2008-10-21 16:13:35 +0000113 // We are pushing the name of a function, which might be an
114 // overloaded name.
115 IdentifierResolver::iterator
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000116 I = IdResolver.begin(FD->getDeclName(),
Douglas Gregord2baafd2008-10-21 16:13:35 +0000117 FD->getDeclContext(), false/*LookInParentCtx*/);
118 if (I != IdResolver.end() &&
119 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
120 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
121 // There is already a declaration with the same name in the same
122 // scope. It must be a function or an overloaded function.
123 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
124 if (!Ovl) {
125 // We haven't yet overloaded this function. Take the existing
126 // FunctionDecl and put it into an OverloadedFunctionDecl.
127 Ovl = OverloadedFunctionDecl::Create(Context,
128 FD->getDeclContext(),
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000129 FD->getDeclName());
Douglas Gregord2baafd2008-10-21 16:13:35 +0000130 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
131
132 // Remove the name binding to the existing FunctionDecl...
133 IdResolver.RemoveDecl(*I);
134
135 // ... and put the OverloadedFunctionDecl in its place.
136 IdResolver.AddDecl(Ovl);
137 }
138
139 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
140 // to its list of overloads.
141 Ovl->addOverload(FD);
142
143 return;
144 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000145 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000146
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000147 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000148}
149
Steve Naroff9637a9b2007-10-09 22:01:59 +0000150void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000151 if (S->decl_empty()) return;
152 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000153
Chris Lattner4b009652007-07-25 00:24:17 +0000154 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
155 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000156 Decl *TmpD = static_cast<Decl*>(*I);
157 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000158
159 if (isa<CXXFieldDecl>(TmpD)) continue;
160
161 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
162 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000163
Chris Lattner4b009652007-07-25 00:24:17 +0000164 IdentifierInfo *II = D->getIdentifier();
165 if (!II) continue;
166
Ted Kremenek40e70e72008-09-03 18:03:35 +0000167 // We only want to remove the decls from the identifier decl chains for
168 // local scopes, when inside a function/method.
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000169 if (S->getFnParent() != 0)
170 IdResolver.RemoveDecl(D);
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000171
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000172 // Chain this decl to the containing DeclContext.
173 D->setNext(CurContext->getDeclChain());
174 CurContext->setDeclChain(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000175 }
176}
177
Steve Naroffe57c21a2008-04-01 23:04:06 +0000178/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
179/// return 0 if one not found.
Steve Naroffe57c21a2008-04-01 23:04:06 +0000180ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-04-02 18:30:49 +0000181 // The third "scope" argument is 0 since we aren't enabling lazy built-in
182 // creation from this context.
183 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000184
Steve Naroff6384a012008-04-02 14:35:35 +0000185 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000186}
187
Steve Naroffe57c21a2008-04-01 23:04:06 +0000188/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000189/// namespace.
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000190Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000191 const DeclContext *LookupCtx,
192 bool enableLazyBuiltinCreation) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000193 if (!Name) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000194 unsigned NS = NSI;
195 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
196 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000197
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000198 IdentifierResolver::iterator
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000199 I = LookupCtx ? IdResolver.begin(Name, LookupCtx, false/*LookInParentCtx*/)
200 : IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/);
Chris Lattner4b009652007-07-25 00:24:17 +0000201 // Scan up the scope chain looking for a decl that matches this identifier
202 // that is in the appropriate namespace. This search should not take long, as
203 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000204 for (; I != IdResolver.end(); ++I)
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000205 if ((*I)->getIdentifierNamespace() & NS)
206 return *I;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000207
Chris Lattner4b009652007-07-25 00:24:17 +0000208 // If we didn't find a use of this identifier, and if the identifier
209 // corresponds to a compiler builtin, create the decl object for the builtin
210 // now, injecting it into translation unit scope, and return it.
Douglas Gregor1d661552008-04-13 21:07:44 +0000211 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000212 IdentifierInfo *II = Name.getAsIdentifierInfo();
213 if (enableLazyBuiltinCreation && II &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000214 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-04-02 14:35:35 +0000215 // If this is a builtin on this (or all) targets, create the decl.
216 if (unsigned BuiltinID = II->getBuiltinID())
217 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
218 }
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000219 if (getLangOptions().ObjC1 && II) {
Steve Naroffe57c21a2008-04-01 23:04:06 +0000220 // @interface and @compatibility_alias introduce typedef-like names.
221 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroff64334ea2008-04-02 00:39:51 +0000222 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000223 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000224 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
225 if (IDI != ObjCInterfaceDecls.end())
226 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000227 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
228 if (I != ObjCAliasDecls.end())
229 return I->second->getClassInterface();
230 }
Chris Lattner4b009652007-07-25 00:24:17 +0000231 }
232 return 0;
233}
234
Chris Lattnera9c87f22008-05-05 22:18:14 +0000235void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000236 if (!Context.getBuiltinVaListType().isNull())
237 return;
238
239 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000240 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000241 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000242 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
243}
244
Chris Lattner4b009652007-07-25 00:24:17 +0000245/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
246/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000247ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
248 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000249 Builtin::ID BID = (Builtin::ID)bid;
250
Chris Lattnerb23469f2008-09-28 05:54:29 +0000251 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000252 InitBuiltinVaListType();
253
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000254 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000255 FunctionDecl *New = FunctionDecl::Create(Context,
256 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000257 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000258 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000259
Chris Lattnera9c87f22008-05-05 22:18:14 +0000260 // Create Decl objects for each parameter, adding them to the
261 // FunctionDecl.
262 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
263 llvm::SmallVector<ParmVarDecl*, 16> Params;
264 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
265 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
266 FT->getArgType(i), VarDecl::None, 0,
267 0));
268 New->setParams(&Params[0], Params.size());
269 }
270
271
272
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000273 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000274 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000275 return New;
276}
277
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000278/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
279/// everything from the standard library is defined.
280NamespaceDecl *Sema::GetStdNamespace() {
281 if (!StdNamespace) {
282 DeclContext *Global = Context.getTranslationUnitDecl();
283 Decl *Std = LookupDecl(Ident_StdNs, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
284 0, Global, /*enableLazyBuiltinCreation=*/false);
285 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
286 }
287 return StdNamespace;
288}
289
Chris Lattner4b009652007-07-25 00:24:17 +0000290/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
291/// and scope as a previous declaration 'Old'. Figure out how to resolve this
292/// situation, merging decls or emitting diagnostics as appropriate.
293///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000294TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-09-09 14:32:20 +0000295 // Allow multiple definitions for ObjC built-in typedefs.
296 // FIXME: Verify the underlying types are equivalent!
297 if (getLangOptions().ObjC1) {
298 const IdentifierInfo *typeIdent = New->getIdentifier();
299 if (typeIdent == Ident_id) {
300 Context.setObjCIdType(New);
301 return New;
302 } else if (typeIdent == Ident_Class) {
303 Context.setObjCClassType(New);
304 return New;
305 } else if (typeIdent == Ident_SEL) {
306 Context.setObjCSelType(New);
307 return New;
308 } else if (typeIdent == Ident_Protocol) {
309 Context.setObjCProtoType(New->getUnderlyingType());
310 return New;
311 }
312 // Fall through - the typedef name was not a builtin type.
313 }
Chris Lattner4b009652007-07-25 00:24:17 +0000314 // Verify the old decl was also a typedef.
315 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
316 if (!Old) {
317 Diag(New->getLocation(), diag::err_redefinition_different_kind,
318 New->getName());
319 Diag(OldD->getLocation(), diag::err_previous_definition);
320 return New;
321 }
322
Chris Lattnerbef8d622008-07-25 18:44:27 +0000323 // If the typedef types are not identical, reject them in all languages and
324 // with any extensions enabled.
325 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
326 Context.getCanonicalType(Old->getUnderlyingType()) !=
327 Context.getCanonicalType(New->getUnderlyingType())) {
328 Diag(New->getLocation(), diag::err_redefinition_different_typedef,
329 New->getUnderlyingType().getAsString(),
330 Old->getUnderlyingType().getAsString());
331 Diag(Old->getLocation(), diag::err_previous_definition);
332 return Old;
333 }
334
Eli Friedman324d5032008-06-11 06:20:39 +0000335 if (getLangOptions().Microsoft) return New;
336
Steve Naroffa9eae582008-01-30 23:46:05 +0000337 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
338 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
339 // *either* declaration is in a system header. The code below implements
340 // this adhoc compatibility rule. FIXME: The following code will not
341 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar4dbd8572008-09-12 18:10:20 +0000342 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
343 SourceManager &SrcMgr = Context.getSourceManager();
344 if (SrcMgr.isInSystemHeader(Old->getLocation()))
345 return New;
346 if (SrcMgr.isInSystemHeader(New->getLocation()))
347 return New;
348 }
Eli Friedman324d5032008-06-11 06:20:39 +0000349
Ted Kremenek64845ce2008-05-23 21:28:18 +0000350 Diag(New->getLocation(), diag::err_redefinition, New->getName());
351 Diag(Old->getLocation(), diag::err_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000352 return New;
353}
354
Chris Lattner6953a072008-06-26 18:38:35 +0000355/// DeclhasAttr - returns true if decl Declaration already has the target
356/// attribute.
Chris Lattner402b3372008-03-03 03:28:21 +0000357static bool DeclHasAttr(const Decl *decl, const Attr *target) {
358 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
359 if (attr->getKind() == target->getKind())
360 return true;
361
362 return false;
363}
364
365/// MergeAttributes - append attributes from the Old decl to the New one.
366static void MergeAttributes(Decl *New, Decl *Old) {
367 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
368
Chris Lattner402b3372008-03-03 03:28:21 +0000369 while (attr) {
370 tmp = attr;
371 attr = attr->getNext();
372
373 if (!DeclHasAttr(New, tmp)) {
374 New->addAttr(tmp);
375 } else {
376 tmp->setNext(0);
377 delete(tmp);
378 }
379 }
Nuno Lopes77654342008-06-01 22:53:53 +0000380
381 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000382}
383
Chris Lattner3e254fb2008-04-08 04:40:51 +0000384/// MergeFunctionDecl - We just parsed a function 'New' from
385/// declarator D which has the same name and scope as a previous
386/// declaration 'Old'. Figure out how to resolve this situation,
387/// merging decls or emitting diagnostics as appropriate.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000388/// Redeclaration will be set true if this New is a redeclaration OldD.
389///
390/// In C++, New and Old must be declarations that are not
391/// overloaded. Use IsOverload to determine whether New and Old are
392/// overloaded, and to select the Old declaration that New should be
393/// merged with.
Douglas Gregor42214c52008-04-21 02:02:58 +0000394FunctionDecl *
395Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000396 assert(!isa<OverloadedFunctionDecl>(OldD) &&
397 "Cannot merge with an overloaded function declaration");
398
Douglas Gregor42214c52008-04-21 02:02:58 +0000399 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000400 // Verify the old decl was also a function.
401 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
402 if (!Old) {
403 Diag(New->getLocation(), diag::err_redefinition_different_kind,
404 New->getName());
405 Diag(OldD->getLocation(), diag::err_previous_definition);
406 return New;
407 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000408
409 // Determine whether the previous declaration was a definition,
410 // implicit declaration, or a declaration.
411 diag::kind PrevDiag;
412 if (Old->isThisDeclarationADefinition())
413 PrevDiag = diag::err_previous_definition;
414 else if (Old->isImplicit())
415 PrevDiag = diag::err_previous_implicit_declaration;
416 else
417 PrevDiag = diag::err_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000418
Chris Lattner42a21742008-04-06 23:10:54 +0000419 QualType OldQType = Context.getCanonicalType(Old->getType());
420 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000421
Douglas Gregord2baafd2008-10-21 16:13:35 +0000422 if (getLangOptions().CPlusPlus) {
423 // (C++98 13.1p2):
424 // Certain function declarations cannot be overloaded:
425 // -- Function declarations that differ only in the return type
426 // cannot be overloaded.
427 QualType OldReturnType
428 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
429 QualType NewReturnType
430 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
431 if (OldReturnType != NewReturnType) {
432 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
433 Diag(Old->getLocation(), PrevDiag);
434 return New;
435 }
436
437 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
438 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
439 if (OldMethod && NewMethod) {
440 // -- Member function declarations with the same name and the
441 // same parameter types cannot be overloaded if any of them
442 // is a static member function declaration.
443 if (OldMethod->isStatic() || NewMethod->isStatic()) {
444 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
445 Diag(Old->getLocation(), PrevDiag);
446 return New;
447 }
448 }
449
450 // (C++98 8.3.5p3):
451 // All declarations for a function shall agree exactly in both the
452 // return type and the parameter-type-list.
453 if (OldQType == NewQType) {
454 // We have a redeclaration.
455 MergeAttributes(New, Old);
456 Redeclaration = true;
457 return MergeCXXFunctionDecl(New, Old);
458 }
459
460 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000461 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000462
463 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000464 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000465 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000466 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000467 MergeAttributes(New, Old);
468 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000469 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000470 }
Chris Lattner1470b072007-11-06 06:07:26 +0000471
Steve Naroff6c9e7922008-01-16 15:01:34 +0000472 // A function that has already been declared has been redeclared or defined
473 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000474
Chris Lattner4b009652007-07-25 00:24:17 +0000475 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
476 // TODO: This is totally simplistic. It should handle merging functions
477 // together etc, merging extern int X; int X; ...
Steve Naroff6c9e7922008-01-16 15:01:34 +0000478 Diag(New->getLocation(), diag::err_conflicting_types, New->getName());
479 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000480 return New;
481}
482
Steve Naroffb5e78152008-08-08 17:50:35 +0000483/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000484static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000485 if (VD->isFileVarDecl())
486 return (!VD->getInit() &&
487 (VD->getStorageClass() == VarDecl::None ||
488 VD->getStorageClass() == VarDecl::Static));
489 return false;
490}
491
492/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
493/// when dealing with C "tentative" external object definitions (C99 6.9.2).
494void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
495 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000496 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000497
498 for (IdentifierResolver::iterator
499 I = IdResolver.begin(VD->getIdentifier(),
500 VD->getDeclContext(), false/*LookInParentCtx*/),
501 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000502 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000503 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
504
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000505 // Handle the following case:
506 // int a[10];
507 // int a[]; - the code below makes sure we set the correct type.
508 // int a[11]; - this is an error, size isn't 10.
509 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
510 OldDecl->getType()->isConstantArrayType())
511 VD->setType(OldDecl->getType());
512
Steve Naroffb5e78152008-08-08 17:50:35 +0000513 // Check for "tentative" definitions. We can't accomplish this in
514 // MergeVarDecl since the initializer hasn't been attached.
515 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
516 continue;
517
518 // Handle __private_extern__ just like extern.
519 if (OldDecl->getStorageClass() != VarDecl::Extern &&
520 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
521 VD->getStorageClass() != VarDecl::Extern &&
522 VD->getStorageClass() != VarDecl::PrivateExtern) {
523 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
524 Diag(OldDecl->getLocation(), diag::err_previous_definition);
525 }
526 }
527 }
528}
529
Chris Lattner4b009652007-07-25 00:24:17 +0000530/// MergeVarDecl - We just parsed a variable 'New' which has the same name
531/// and scope as a previous declaration 'Old'. Figure out how to resolve this
532/// situation, merging decls or emitting diagnostics as appropriate.
533///
Steve Naroffb5e78152008-08-08 17:50:35 +0000534/// Tentative definition rules (C99 6.9.2p2) are checked by
535/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
536/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000537///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000538VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000539 // Verify the old decl was also a variable.
540 VarDecl *Old = dyn_cast<VarDecl>(OldD);
541 if (!Old) {
542 Diag(New->getLocation(), diag::err_redefinition_different_kind,
543 New->getName());
544 Diag(OldD->getLocation(), diag::err_previous_definition);
545 return New;
546 }
Chris Lattner402b3372008-03-03 03:28:21 +0000547
548 MergeAttributes(New, Old);
549
Chris Lattner4b009652007-07-25 00:24:17 +0000550 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000551 QualType OldCType = Context.getCanonicalType(Old->getType());
552 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000553 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000554 Diag(New->getLocation(), diag::err_redefinition, New->getName());
555 Diag(Old->getLocation(), diag::err_previous_definition);
556 return New;
557 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000558 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
559 if (New->getStorageClass() == VarDecl::Static &&
560 (Old->getStorageClass() == VarDecl::None ||
561 Old->getStorageClass() == VarDecl::Extern)) {
562 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
563 Diag(Old->getLocation(), diag::err_previous_definition);
564 return New;
565 }
566 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
567 if (New->getStorageClass() != VarDecl::Static &&
568 Old->getStorageClass() == VarDecl::Static) {
569 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
570 Diag(Old->getLocation(), diag::err_previous_definition);
571 return New;
572 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000573 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
574 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner4b009652007-07-25 00:24:17 +0000575 Diag(New->getLocation(), diag::err_redefinition, New->getName());
576 Diag(Old->getLocation(), diag::err_previous_definition);
577 }
578 return New;
579}
580
Chris Lattner3e254fb2008-04-08 04:40:51 +0000581/// CheckParmsForFunctionDef - Check that the parameters of the given
582/// function are appropriate for the definition of a function. This
583/// takes care of any checks that cannot be performed on the
584/// declaration itself, e.g., that the types of each of the function
585/// parameters are complete.
586bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
587 bool HasInvalidParm = false;
588 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
589 ParmVarDecl *Param = FD->getParamDecl(p);
590
591 // C99 6.7.5.3p4: the parameters in a parameter type list in a
592 // function declarator that is part of a function definition of
593 // that function shall not have incomplete type.
594 if (Param->getType()->isIncompleteType() &&
595 !Param->isInvalidDecl()) {
596 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
597 Param->getType().getAsString());
598 Param->setInvalidDecl();
599 HasInvalidParm = true;
600 }
601 }
602
603 return HasInvalidParm;
604}
605
Chris Lattner4b009652007-07-25 00:24:17 +0000606/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
607/// no declarator (e.g. "struct foo;") is parsed.
608Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
609 // TODO: emit error on 'int;' or 'const enum foo;'.
610 // TODO: emit error on 'typedef int;'
611 // if (!DS.isMissingDeclaratorOk()) Diag(...);
612
Steve Naroffedafc0b2007-11-17 21:37:36 +0000613 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000614}
615
Steve Narofff0b23542008-01-10 22:15:12 +0000616bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000617 // Get the type before calling CheckSingleAssignmentConstraints(), since
618 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000619 QualType InitType = Init->getType();
Steve Naroffe14e5542007-09-02 02:04:30 +0000620
Chris Lattner005ed752008-01-04 18:04:52 +0000621 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
622 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
623 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000624}
625
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000626bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000627 const ArrayType *AT = Context.getAsArrayType(DeclT);
628
629 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000630 // C99 6.7.8p14. We have an array of character type with unknown size
631 // being initialized to a string literal.
632 llvm::APSInt ConstVal(32);
633 ConstVal = strLiteral->getByteLength() + 1;
634 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000635 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000636 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000637 } else {
638 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000639 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000640 // FIXME: Avoid truncation for 64-bit length strings.
641 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000642 Diag(strLiteral->getSourceRange().getBegin(),
643 diag::warn_initializer_string_for_char_array_too_long,
644 strLiteral->getSourceRange());
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000645 }
646 // Set type from "char *" to "constant array of char".
647 strLiteral->setType(DeclT);
648 // For now, we always return false (meaning success).
649 return false;
650}
651
652StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000653 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000654 if (AT && AT->getElementType()->isCharType()) {
655 return dyn_cast<StringLiteral>(Init);
656 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000657 return 0;
658}
659
Douglas Gregor6428e762008-11-05 15:29:30 +0000660bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
661 SourceLocation InitLoc,
662 std::string InitEntity) {
Douglas Gregor81c29152008-10-29 00:13:59 +0000663 // C++ [dcl.init.ref]p1:
664 // A variable declared to be a T&, that is “reference to type T”
665 // (8.3.2), shall be initialized by an object, or function, of
666 // type T or by an object that can be converted into a T.
667 if (DeclType->isReferenceType())
668 return CheckReferenceInit(Init, DeclType);
669
Steve Naroff8e9337f2008-01-21 23:53:58 +0000670 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
671 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000672 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Douglas Gregor6428e762008-11-05 15:29:30 +0000673 return Diag(InitLoc,
Steve Naroff8e9337f2008-01-21 23:53:58 +0000674 diag::err_variable_object_no_init,
675 VAT->getSizeExpr()->getSourceRange());
676
Steve Naroffcb69fb72007-12-10 22:44:33 +0000677 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
678 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000679 // FIXME: Handle wide strings
680 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
681 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000682
Douglas Gregor6428e762008-11-05 15:29:30 +0000683 // C++ [dcl.init]p14:
684 // -- If the destination type is a (possibly cv-qualified) class
685 // type:
686 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
687 QualType DeclTypeC = Context.getCanonicalType(DeclType);
688 QualType InitTypeC = Context.getCanonicalType(Init->getType());
689
690 // -- If the initialization is direct-initialization, or if it is
691 // copy-initialization where the cv-unqualified version of the
692 // source type is the same class as, or a derived class of, the
693 // class of the destination, constructors are considered.
694 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
695 IsDerivedFrom(InitTypeC, DeclTypeC)) {
696 CXXConstructorDecl *Constructor
697 = PerformInitializationByConstructor(DeclType, &Init, 1,
698 InitLoc, Init->getSourceRange(),
699 InitEntity, IK_Copy);
700 return Constructor == 0;
701 }
702
703 // -- Otherwise (i.e., for the remaining copy-initialization
704 // cases), user-defined conversion sequences that can
705 // convert from the source type to the destination type or
706 // (when a conversion function is used) to a derived class
707 // thereof are enumerated as described in 13.3.1.4, and the
708 // best one is chosen through overload resolution
709 // (13.3). If the conversion cannot be done or is
710 // ambiguous, the initialization is ill-formed. The
711 // function selected is called with the initializer
712 // expression as its argument; if the function is a
713 // constructor, the call initializes a temporary of the
714 // destination type.
715 // FIXME: We're pretending to do copy elision here; return to
716 // this when we have ASTs for such things.
717 if (PerformImplicitConversion(Init, DeclType))
718 return Diag(InitLoc,
719 diag::err_typecheck_convert_incompatible,
720 DeclType.getAsString(), InitEntity,
721 "initializing",
722 Init->getSourceRange());
723 else
724 return false;
725 }
726
Steve Naroffb2f72412008-09-29 20:07:05 +0000727 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000728 if (DeclType->isArrayType())
729 return Diag(Init->getLocStart(),
730 diag::err_array_init_list_required,
731 Init->getSourceRange());
732
Steve Narofff0b23542008-01-10 22:15:12 +0000733 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +0000734 } else if (getLangOptions().CPlusPlus) {
735 // C++ [dcl.init]p14:
736 // [...] If the class is an aggregate (8.5.1), and the initializer
737 // is a brace-enclosed list, see 8.5.1.
738 //
739 // Note: 8.5.1 is handled below; here, we diagnose the case where
740 // we have an initializer list and a destination type that is not
741 // an aggregate.
742 // FIXME: In C++0x, this is yet another form of initialization.
743 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
744 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
745 if (!ClassDecl->isAggregate())
746 return Diag(InitLoc,
747 diag::err_init_non_aggr_init_list,
748 DeclType.getAsString(),
749 Init->getSourceRange());
750 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000751 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000752
Steve Naroffc4d4a482008-05-01 22:18:59 +0000753 InitListChecker CheckInitList(this, InitList, DeclType);
754 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000755}
756
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000757Sema::DeclTy *
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000758Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000759 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Chris Lattner4b009652007-07-25 00:24:17 +0000760 IdentifierInfo *II = D.getIdentifier();
761
762 // All of these full declarators require an identifier. If it doesn't have
763 // one, the ParsedFreeStandingDeclSpec action should be used.
764 if (II == 0) {
Chris Lattnercd61d592008-11-11 06:13:16 +0000765 if (!D.getInvalidType()) // Reject this if we think it is valid.
766 Diag(D.getDeclSpec().getSourceRange().getBegin(),
767 diag::err_declarator_need_ident,
768 D.getDeclSpec().getSourceRange(), D.getSourceRange());
Chris Lattner4b009652007-07-25 00:24:17 +0000769 return 0;
770 }
771
Chris Lattnera7549902007-08-26 06:24:45 +0000772 // The scope passed in may not be a decl scope. Zip up the scope tree until
773 // we find one that is.
774 while ((S->getFlags() & Scope::DeclScope) == 0)
775 S = S->getParent();
776
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000777 DeclContext *DC;
778 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000779 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000780 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000781
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000782 // See if this is a redefinition of a variable in the same scope.
783 if (!D.getCXXScopeSpec().isSet()) {
784 DC = CurContext;
785 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S);
786 } else { // Something like "int foo::x;"
787 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
788 PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S, DC);
789
790 // C++ 7.3.1.2p2:
791 // Members (including explicit specializations of templates) of a named
792 // namespace can also be defined outside that namespace by explicit
793 // qualification of the name being defined, provided that the entity being
794 // defined was already declared in the namespace and the definition appears
795 // after the point of declaration in a namespace that encloses the
796 // declarations namespace.
797 //
798 if (PrevDecl == 0) {
799 // No previous declaration in the qualifying scope.
800 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member,
801 II->getName(), D.getCXXScopeSpec().getRange());
802 } else if (!CurContext->Encloses(DC)) {
803 // The qualifying scope doesn't enclose the original declaration.
804 // Emit diagnostic based on current scope.
805 SourceLocation L = D.getIdentifierLoc();
806 SourceRange R = D.getCXXScopeSpec().getRange();
807 if (isa<FunctionDecl>(CurContext)) {
808 Diag(L, diag::err_invalid_declarator_in_function, II->getName(), R);
809 } else {
810 Diag(L, diag::err_invalid_declarator_scope, II->getName(),
811 cast<NamedDecl>(DC)->getName(), R);
812 }
813 }
814 }
815
Douglas Gregor1d661552008-04-13 21:07:44 +0000816 // In C++, the previous declaration we find might be a tag type
817 // (class or enum). In this case, the new declaration will hide the
818 // tag type.
819 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
820 PrevDecl = 0;
821
Chris Lattner82bb4792007-11-14 06:34:38 +0000822 QualType R = GetTypeForDeclarator(D, S);
823 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
824
Chris Lattner4b009652007-07-25 00:24:17 +0000825 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor2b9422f2008-05-07 04:49:29 +0000826 // Check that there are no default arguments (C++ only).
827 if (getLangOptions().CPlusPlus)
828 CheckExtraCXXDefaultArguments(D);
829
Chris Lattner82bb4792007-11-14 06:34:38 +0000830 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +0000831 if (!NewTD) return 0;
832
833 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +0000834 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +0000835 // Merge the decl with the existing one if appropriate. If the decl is
836 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000837 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +0000838 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
839 if (NewTD == 0) return 0;
840 }
841 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000842 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +0000843 // C99 6.7.7p2: If a typedef name specifies a variably modified type
844 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +0000845 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
846 // FIXME: Diagnostic needs to be fixed.
847 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroff5eb879b2007-08-31 17:20:07 +0000848 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +0000849 }
850 }
Chris Lattner82bb4792007-11-14 06:34:38 +0000851 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +0000852 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +0000853 switch (D.getDeclSpec().getStorageClassSpec()) {
854 default: assert(0 && "Unknown storage class!");
855 case DeclSpec::SCS_auto:
856 case DeclSpec::SCS_register:
Sebastian Redl9f5337b2008-11-14 23:42:31 +0000857 case DeclSpec::SCS_mutable:
Chris Lattner4b009652007-07-25 00:24:17 +0000858 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
859 R.getAsString());
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000860 InvalidDecl = true;
861 break;
Chris Lattner4b009652007-07-25 00:24:17 +0000862 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
863 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
864 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +0000865 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +0000866 }
867
Chris Lattner4c7802b2008-03-15 21:24:04 +0000868 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000869 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000870 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
871
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000872 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000873 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000874 // This is a C++ constructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000875 assert(DC->isCXXRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000876 "Constructors can only be declared in a member context");
877
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000878 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000879
880 // Create the new declaration
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000881 QualType ClassType = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
882 ClassType = Context.getCanonicalType(ClassType);
883 DeclarationName ConName
884 = Context.DeclarationNames.getCXXConstructorName(ClassType);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000885 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000886 cast<CXXRecordDecl>(DC),
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000887 D.getIdentifierLoc(), ConName, R,
Douglas Gregorf15ac4b2008-10-31 09:07:45 +0000888 isExplicit, isInline,
889 /*isImplicitlyDeclared=*/false);
890
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000891 if (isInvalidDecl)
892 NewFD->setInvalidDecl();
893 } else if (D.getKind() == Declarator::DK_Destructor) {
894 // This is a C++ destructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000895 if (DC->isCXXRecord()) {
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000896 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000897
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000898 QualType ClassType = Context.getTypeDeclType(cast<CXXRecordDecl>(DC));
899 ClassType = Context.getCanonicalType(ClassType);
900 DeclarationName DesName
901 = Context.DeclarationNames.getCXXDestructorName(ClassType);
902
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000903 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000904 cast<CXXRecordDecl>(DC),
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000905 D.getIdentifierLoc(), DesName, R,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000906 isInline,
907 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000908
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000909 if (isInvalidDecl)
910 NewFD->setInvalidDecl();
911 } else {
912 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
913 // Create a FunctionDecl to satisfy the function definition parsing
914 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000915 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000916 II, R, SC, isInline, LastDeclarator,
917 // FIXME: Move to DeclGroup...
918 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor8210a8e2008-11-05 20:51:48 +0000919 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +0000920 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000921 } else if (D.getKind() == Declarator::DK_Conversion) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000922 if (!DC->isCXXRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000923 Diag(D.getIdentifierLoc(),
924 diag::err_conv_function_not_member);
925 return 0;
926 } else {
927 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
928
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000929 QualType ConvType = R->getAsFunctionType()->getResultType();
930 ConvType = Context.getCanonicalType(ConvType);
931 DeclarationName ConvName
932 = Context.DeclarationNames.getCXXConversionFunctionName(ConvType);
933
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000934 NewFD = CXXConversionDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000935 cast<CXXRecordDecl>(DC),
Douglas Gregor24afd4a2008-11-17 14:58:09 +0000936 D.getIdentifierLoc(), ConvName, R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +0000937 isInline, isExplicit);
938
939 if (isInvalidDecl)
940 NewFD->setInvalidDecl();
941 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000942 } else if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000943 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000944 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000945 D.getIdentifierLoc(), II, R,
946 (SC == FunctionDecl::Static), isInline,
947 LastDeclarator);
948 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000949 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000950 D.getIdentifierLoc(),
Steve Naroff71cd7762008-10-03 00:02:03 +0000951 II, R, SC, isInline, LastDeclarator,
952 // FIXME: Move to DeclGroup...
953 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +0000954 }
Ted Kremenek117f1862008-02-27 22:18:07 +0000955 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +0000956 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000957
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000958 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +0000959 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +0000960 // The parser guarantees this is a string.
961 StringLiteral *SE = cast<StringLiteral>(E);
962 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
963 SE->getByteLength())));
964 }
965
Chris Lattner3e254fb2008-04-08 04:40:51 +0000966 // Copy the parameter declarations from the declarator D to
967 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +0000968 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000969 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
970
971 // Create Decl objects for each parameter, adding them to the
972 // FunctionDecl.
973 llvm::SmallVector<ParmVarDecl*, 16> Params;
974
975 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
976 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +0000977 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +0000978 // We let through "const void" here because Sema::GetTypeForDeclarator
979 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000980 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
981 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +0000982 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
983 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +0000984 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
985
Chris Lattnerda7b5f02008-04-10 02:26:16 +0000986 // In C++, the empty parameter-type-list must be spelled "void"; a
987 // typedef of void is not permitted.
988 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +0000989 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +0000990 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
991 }
Eli Friedman769e7302008-08-25 21:31:01 +0000992 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +0000993 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
994 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
995 }
996
997 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +0000998 } else if (R->getAsTypedefType()) {
999 // When we're declaring a function with a typedef, as in the
1000 // following example, we'll need to synthesize (unnamed)
1001 // parameters for use in the declaration.
1002 //
1003 // @code
1004 // typedef void fn(int);
1005 // fn f;
1006 // @endcode
1007 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1008 if (!FT) {
1009 // This is a typedef of a function with no prototype, so we
1010 // don't need to do anything.
1011 } else if ((FT->getNumArgs() == 0) ||
1012 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1013 FT->getArgType(0)->isVoidType())) {
1014 // This is a zero-argument function. We don't need to do anything.
1015 } else {
1016 // Synthesize a parameter for each argument type.
1017 llvm::SmallVector<ParmVarDecl*, 16> Params;
1018 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1019 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001020 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001021 SourceLocation(), 0,
1022 *ArgType, VarDecl::None,
1023 0, 0));
1024 }
1025
1026 NewFD->setParams(&Params[0], Params.size());
1027 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001028 }
1029
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001030 // C++ constructors and destructors are handled by separate
1031 // routines, since they don't require any declaration merging (C++
1032 // [class.mfct]p2) and they aren't ever pushed into scope, because
1033 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1034 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1035 return ActOnConstructorDeclarator(Constructor);
1036 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1037 return ActOnDestructorDeclarator(Destructor);
Douglas Gregorb0212bd2008-11-17 20:34:05 +00001038
1039 // Extra checking for conversion functions, including recording
1040 // the conversion function in its class.
1041 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1042 ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001043
Douglas Gregore60e5d32008-11-06 22:13:31 +00001044 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1045 if (NewFD->isOverloadedOperator() &&
1046 CheckOverloadedOperatorDeclaration(NewFD))
1047 NewFD->setInvalidDecl();
1048
Steve Narofff8a09432008-01-09 23:34:55 +00001049 // Merge the decl with the existing one if appropriate. Since C functions
1050 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001051 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001052 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001053 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001054
1055 // If C++, determine whether NewFD is an overload of PrevDecl or
1056 // a declaration that requires merging. If it's an overload,
1057 // there's no more work to do here; we'll just add the new
1058 // function to the scope.
1059 OverloadedFunctionDecl::function_iterator MatchedDecl;
1060 if (!getLangOptions().CPlusPlus ||
1061 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1062 Decl *OldDecl = PrevDecl;
1063
1064 // If PrevDecl was an overloaded function, extract the
1065 // FunctionDecl that matched.
1066 if (isa<OverloadedFunctionDecl>(PrevDecl))
1067 OldDecl = *MatchedDecl;
1068
1069 // NewFD and PrevDecl represent declarations that need to be
1070 // merged.
1071 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1072
1073 if (NewFD == 0) return 0;
1074 if (Redeclaration) {
1075 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1076
1077 if (OldDecl == PrevDecl) {
1078 // Remove the name binding for the previous
1079 // declaration. We'll add the binding back later, but then
1080 // it will refer to the new declaration (which will
1081 // contain more information).
1082 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1083 } else {
1084 // We need to update the OverloadedFunctionDecl with the
1085 // latest declaration of this function, so that name
1086 // lookup will always refer to the latest declaration of
1087 // this function.
1088 *MatchedDecl = NewFD;
1089
1090 // Add the redeclaration to the current scope, since we'll
1091 // be skipping PushOnScopeChains.
1092 S->AddDecl(NewFD);
1093
1094 return NewFD;
1095 }
1096 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001097 }
Chris Lattner4b009652007-07-25 00:24:17 +00001098 }
1099 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001100
1101 // In C++, check default arguments now that we have merged decls.
1102 if (getLangOptions().CPlusPlus)
1103 CheckCXXDefaultArguments(NewFD);
Chris Lattner4b009652007-07-25 00:24:17 +00001104 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001105 // Check that there are no default arguments (C++ only).
1106 if (getLangOptions().CPlusPlus)
1107 CheckExtraCXXDefaultArguments(D);
1108
Ted Kremenek42730c52008-01-07 19:49:32 +00001109 if (R.getTypePtr()->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001110 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object,
1111 D.getIdentifier()->getName());
1112 InvalidDecl = true;
1113 }
Chris Lattner4b009652007-07-25 00:24:17 +00001114
1115 VarDecl *NewVD;
1116 VarDecl::StorageClass SC;
1117 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001118 default: assert(0 && "Unknown storage class!");
1119 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1120 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1121 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1122 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1123 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1124 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001125 case DeclSpec::SCS_mutable:
1126 // mutable can only appear on non-static class members, so it's always
1127 // an error here
1128 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1129 InvalidDecl = true;
1130 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001131 if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001132 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1133 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001134 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001135 D.getIdentifierLoc(), II,
1136 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001137 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001138 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001139 if (S->getFnParent() == 0) {
1140 // C99 6.9p2: The storage-class specifiers auto and register shall not
1141 // appear in the declaration specifiers in an external declaration.
1142 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1143 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1144 R.getAsString());
1145 InvalidDecl = true;
1146 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001147 }
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001148 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1149 II, R, SC, LastDeclarator,
1150 // FIXME: Move to DeclGroup...
1151 D.getDeclSpec().getSourceRange().getBegin());
1152 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001153 }
Chris Lattner4b009652007-07-25 00:24:17 +00001154 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001155 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001156
Daniel Dunbarced89142008-08-06 00:03:29 +00001157 // Handle GNU asm-label extension (encoded as an attribute).
1158 if (Expr *E = (Expr*) D.getAsmLabel()) {
1159 // The parser guarantees this is a string.
1160 StringLiteral *SE = cast<StringLiteral>(E);
1161 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1162 SE->getByteLength())));
1163 }
1164
Nate Begemanea583262008-03-14 18:07:10 +00001165 // Emit an error if an address space was applied to decl with local storage.
1166 // This includes arrays of objects with address space qualifiers, but not
1167 // automatic variables that point to other address spaces.
1168 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001169 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1170 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1171 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001172 }
Steve Narofff8a09432008-01-09 23:34:55 +00001173 // Merge the decl with the existing one if appropriate. If the decl is
1174 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001175 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001176 NewVD = MergeVarDecl(NewVD, PrevDecl);
1177 if (NewVD == 0) return 0;
1178 }
Chris Lattner4b009652007-07-25 00:24:17 +00001179 New = NewVD;
1180 }
1181
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001182 // Set the lexical context. If the declarator has a C++ scope specifier, the
1183 // lexical context will be different from the semantic context.
1184 New->setLexicalDeclContext(CurContext);
1185
Chris Lattner4b009652007-07-25 00:24:17 +00001186 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001187 if (II)
1188 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001189 // If any semantic error occurred, mark the decl as invalid.
1190 if (D.getInvalidType() || InvalidDecl)
1191 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001192
1193 return New;
1194}
1195
Steve Narofffc08f5e2008-10-27 11:34:16 +00001196void Sema::InitializerElementNotConstant(const Expr *Init) {
1197 Diag(Init->getExprLoc(),
1198 diag::err_init_element_not_constant, Init->getSourceRange());
1199}
1200
Eli Friedman02c22ce2008-05-20 13:48:25 +00001201bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1202 switch (Init->getStmtClass()) {
1203 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001204 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001205 return true;
1206 case Expr::ParenExprClass: {
1207 const ParenExpr* PE = cast<ParenExpr>(Init);
1208 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1209 }
1210 case Expr::CompoundLiteralExprClass:
1211 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1212 case Expr::DeclRefExprClass: {
1213 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001214 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1215 if (VD->hasGlobalStorage())
1216 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001217 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001218 return true;
1219 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001220 if (isa<FunctionDecl>(D))
1221 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001222 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001223 return true;
1224 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001225 case Expr::MemberExprClass: {
1226 const MemberExpr *M = cast<MemberExpr>(Init);
1227 if (M->isArrow())
1228 return CheckAddressConstantExpression(M->getBase());
1229 return CheckAddressConstantExpressionLValue(M->getBase());
1230 }
1231 case Expr::ArraySubscriptExprClass: {
1232 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1233 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1234 return CheckAddressConstantExpression(ASE->getBase()) ||
1235 CheckArithmeticConstantExpression(ASE->getIdx());
1236 }
1237 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001238 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001239 return false;
1240 case Expr::UnaryOperatorClass: {
1241 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1242
1243 // C99 6.6p9
1244 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001245 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001246
Steve Narofffc08f5e2008-10-27 11:34:16 +00001247 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001248 return true;
1249 }
1250 }
1251}
1252
1253bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1254 switch (Init->getStmtClass()) {
1255 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001256 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001257 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001258 case Expr::ParenExprClass:
1259 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001260 case Expr::StringLiteralClass:
1261 case Expr::ObjCStringLiteralClass:
1262 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001263 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001264 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001265 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1266 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1267 Builtin::BI__builtin___CFStringMakeConstantString)
1268 return false;
1269
Steve Narofffc08f5e2008-10-27 11:34:16 +00001270 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001271 return true;
1272
Eli Friedman02c22ce2008-05-20 13:48:25 +00001273 case Expr::UnaryOperatorClass: {
1274 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1275
1276 // C99 6.6p9
1277 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1278 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1279
1280 if (Exp->getOpcode() == UnaryOperator::Extension)
1281 return CheckAddressConstantExpression(Exp->getSubExpr());
1282
Steve Narofffc08f5e2008-10-27 11:34:16 +00001283 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001284 return true;
1285 }
1286 case Expr::BinaryOperatorClass: {
1287 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1288 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1289
1290 Expr *PExp = Exp->getLHS();
1291 Expr *IExp = Exp->getRHS();
1292 if (IExp->getType()->isPointerType())
1293 std::swap(PExp, IExp);
1294
1295 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1296 return CheckAddressConstantExpression(PExp) ||
1297 CheckArithmeticConstantExpression(IExp);
1298 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001299 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001300 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001301 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001302 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1303 // Check for implicit promotion
1304 if (SubExpr->getType()->isFunctionType() ||
1305 SubExpr->getType()->isArrayType())
1306 return CheckAddressConstantExpressionLValue(SubExpr);
1307 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001308
1309 // Check for pointer->pointer cast
1310 if (SubExpr->getType()->isPointerType())
1311 return CheckAddressConstantExpression(SubExpr);
1312
Eli Friedman1fad3c62008-08-25 20:46:57 +00001313 if (SubExpr->getType()->isIntegralType()) {
1314 // Check for the special-case of a pointer->int->pointer cast;
1315 // this isn't standard, but some code requires it. See
1316 // PR2720 for an example.
1317 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1318 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1319 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1320 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1321 if (IntWidth >= PointerWidth) {
1322 return CheckAddressConstantExpression(SubCast->getSubExpr());
1323 }
1324 }
1325 }
1326 }
1327 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001328 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001329 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001330
Steve Narofffc08f5e2008-10-27 11:34:16 +00001331 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001332 return true;
1333 }
1334 case Expr::ConditionalOperatorClass: {
1335 // FIXME: Should we pedwarn here?
1336 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1337 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001338 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001339 return true;
1340 }
1341 if (CheckArithmeticConstantExpression(Exp->getCond()))
1342 return true;
1343 if (Exp->getLHS() &&
1344 CheckAddressConstantExpression(Exp->getLHS()))
1345 return true;
1346 return CheckAddressConstantExpression(Exp->getRHS());
1347 }
1348 case Expr::AddrLabelExprClass:
1349 return false;
1350 }
1351}
1352
Eli Friedman998dffb2008-06-09 05:05:07 +00001353static const Expr* FindExpressionBaseAddress(const Expr* E);
1354
1355static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1356 switch (E->getStmtClass()) {
1357 default:
1358 return E;
1359 case Expr::ParenExprClass: {
1360 const ParenExpr* PE = cast<ParenExpr>(E);
1361 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1362 }
1363 case Expr::MemberExprClass: {
1364 const MemberExpr *M = cast<MemberExpr>(E);
1365 if (M->isArrow())
1366 return FindExpressionBaseAddress(M->getBase());
1367 return FindExpressionBaseAddressLValue(M->getBase());
1368 }
1369 case Expr::ArraySubscriptExprClass: {
1370 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1371 return FindExpressionBaseAddress(ASE->getBase());
1372 }
1373 case Expr::UnaryOperatorClass: {
1374 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1375
1376 if (Exp->getOpcode() == UnaryOperator::Deref)
1377 return FindExpressionBaseAddress(Exp->getSubExpr());
1378
1379 return E;
1380 }
1381 }
1382}
1383
1384static const Expr* FindExpressionBaseAddress(const Expr* E) {
1385 switch (E->getStmtClass()) {
1386 default:
1387 return E;
1388 case Expr::ParenExprClass: {
1389 const ParenExpr* PE = cast<ParenExpr>(E);
1390 return FindExpressionBaseAddress(PE->getSubExpr());
1391 }
1392 case Expr::UnaryOperatorClass: {
1393 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1394
1395 // C99 6.6p9
1396 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1397 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1398
1399 if (Exp->getOpcode() == UnaryOperator::Extension)
1400 return FindExpressionBaseAddress(Exp->getSubExpr());
1401
1402 return E;
1403 }
1404 case Expr::BinaryOperatorClass: {
1405 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1406
1407 Expr *PExp = Exp->getLHS();
1408 Expr *IExp = Exp->getRHS();
1409 if (IExp->getType()->isPointerType())
1410 std::swap(PExp, IExp);
1411
1412 return FindExpressionBaseAddress(PExp);
1413 }
1414 case Expr::ImplicitCastExprClass: {
1415 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1416
1417 // Check for implicit promotion
1418 if (SubExpr->getType()->isFunctionType() ||
1419 SubExpr->getType()->isArrayType())
1420 return FindExpressionBaseAddressLValue(SubExpr);
1421
1422 // Check for pointer->pointer cast
1423 if (SubExpr->getType()->isPointerType())
1424 return FindExpressionBaseAddress(SubExpr);
1425
1426 // We assume that we have an arithmetic expression here;
1427 // if we don't, we'll figure it out later
1428 return 0;
1429 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001430 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001431 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1432
1433 // Check for pointer->pointer cast
1434 if (SubExpr->getType()->isPointerType())
1435 return FindExpressionBaseAddress(SubExpr);
1436
1437 // We assume that we have an arithmetic expression here;
1438 // if we don't, we'll figure it out later
1439 return 0;
1440 }
1441 }
1442}
1443
Eli Friedman02c22ce2008-05-20 13:48:25 +00001444bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1445 switch (Init->getStmtClass()) {
1446 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001447 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001448 return true;
1449 case Expr::ParenExprClass: {
1450 const ParenExpr* PE = cast<ParenExpr>(Init);
1451 return CheckArithmeticConstantExpression(PE->getSubExpr());
1452 }
1453 case Expr::FloatingLiteralClass:
1454 case Expr::IntegerLiteralClass:
1455 case Expr::CharacterLiteralClass:
1456 case Expr::ImaginaryLiteralClass:
1457 case Expr::TypesCompatibleExprClass:
1458 case Expr::CXXBoolLiteralExprClass:
1459 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001460 case Expr::CallExprClass:
1461 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001462 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001463
1464 // Allow any constant foldable calls to builtins.
1465 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001466 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001467
Steve Narofffc08f5e2008-10-27 11:34:16 +00001468 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001469 return true;
1470 }
1471 case Expr::DeclRefExprClass: {
1472 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1473 if (isa<EnumConstantDecl>(D))
1474 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001475 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001476 return true;
1477 }
1478 case Expr::CompoundLiteralExprClass:
1479 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1480 // but vectors are allowed to be magic.
1481 if (Init->getType()->isVectorType())
1482 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001483 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001484 return true;
1485 case Expr::UnaryOperatorClass: {
1486 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1487
1488 switch (Exp->getOpcode()) {
1489 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1490 // See C99 6.6p3.
1491 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001492 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001493 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001494 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001495 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1496 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001497 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001498 return true;
1499 case UnaryOperator::Extension:
1500 case UnaryOperator::LNot:
1501 case UnaryOperator::Plus:
1502 case UnaryOperator::Minus:
1503 case UnaryOperator::Not:
1504 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1505 }
1506 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001507 case Expr::SizeOfAlignOfExprClass: {
1508 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001509 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001510 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00001511 return false;
1512 // alignof always evaluates to a constant.
1513 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001514 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001515 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001516 return true;
1517 }
1518 return false;
1519 }
1520 case Expr::BinaryOperatorClass: {
1521 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1522
1523 if (Exp->getLHS()->getType()->isArithmeticType() &&
1524 Exp->getRHS()->getType()->isArithmeticType()) {
1525 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1526 CheckArithmeticConstantExpression(Exp->getRHS());
1527 }
1528
Eli Friedman998dffb2008-06-09 05:05:07 +00001529 if (Exp->getLHS()->getType()->isPointerType() &&
1530 Exp->getRHS()->getType()->isPointerType()) {
1531 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1532 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1533
1534 // Only allow a null (constant integer) base; we could
1535 // allow some additional cases if necessary, but this
1536 // is sufficient to cover offsetof-like constructs.
1537 if (!LHSBase && !RHSBase) {
1538 return CheckAddressConstantExpression(Exp->getLHS()) ||
1539 CheckAddressConstantExpression(Exp->getRHS());
1540 }
1541 }
1542
Steve Narofffc08f5e2008-10-27 11:34:16 +00001543 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001544 return true;
1545 }
1546 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001547 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001548 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001549 if (SubExpr->getType()->isArithmeticType())
1550 return CheckArithmeticConstantExpression(SubExpr);
1551
Eli Friedman266df142008-09-02 09:37:00 +00001552 if (SubExpr->getType()->isPointerType()) {
1553 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1554 // If the pointer has a null base, this is an offsetof-like construct
1555 if (!Base)
1556 return CheckAddressConstantExpression(SubExpr);
1557 }
1558
Steve Narofffc08f5e2008-10-27 11:34:16 +00001559 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001560 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001561 }
1562 case Expr::ConditionalOperatorClass: {
1563 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001564
1565 // If GNU extensions are disabled, we require all operands to be arithmetic
1566 // constant expressions.
1567 if (getLangOptions().NoExtensions) {
1568 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1569 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1570 CheckArithmeticConstantExpression(Exp->getRHS());
1571 }
1572
1573 // Otherwise, we have to emulate some of the behavior of fold here.
1574 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1575 // because it can constant fold things away. To retain compatibility with
1576 // GCC code, we see if we can fold the condition to a constant (which we
1577 // should always be able to do in theory). If so, we only require the
1578 // specified arm of the conditional to be a constant. This is a horrible
1579 // hack, but is require by real world code that uses __builtin_constant_p.
1580 APValue Val;
Chris Lattneref069662008-11-16 21:24:15 +00001581 if (!Exp->getCond()->Evaluate(Val, Context)) {
1582 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00001583 // won't be able to either. Use it to emit the diagnostic though.
1584 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00001585 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00001586 return Res;
1587 }
1588
1589 // Verify that the side following the condition is also a constant.
1590 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1591 if (Val.getInt() == 0)
1592 std::swap(TrueSide, FalseSide);
1593
1594 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001595 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001596
1597 // Okay, the evaluated side evaluates to a constant, so we accept this.
1598 // Check to see if the other side is obviously not a constant. If so,
1599 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001600 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001601 Diag(Init->getExprLoc(),
1602 diag::ext_typecheck_expression_not_constant_but_accepted,
1603 FalseSide->getSourceRange());
1604 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001605 }
1606 }
1607}
1608
1609bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopese7280452008-07-07 16:46:50 +00001610 Init = Init->IgnoreParens();
1611
Eli Friedman02c22ce2008-05-20 13:48:25 +00001612 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1613 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1614 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1615
Nuno Lopese7280452008-07-07 16:46:50 +00001616 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1617 return CheckForConstantInitializer(e->getInitializer(), DclT);
1618
Eli Friedman02c22ce2008-05-20 13:48:25 +00001619 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1620 unsigned numInits = Exp->getNumInits();
1621 for (unsigned i = 0; i < numInits; i++) {
1622 // FIXME: Need to get the type of the declaration for C++,
1623 // because it could be a reference?
1624 if (CheckForConstantInitializer(Exp->getInit(i),
1625 Exp->getInit(i)->getType()))
1626 return true;
1627 }
1628 return false;
1629 }
1630
1631 if (Init->isNullPointerConstant(Context))
1632 return false;
1633 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001634 QualType InitTy = Context.getCanonicalType(Init->getType())
1635 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001636 if (InitTy == Context.BoolTy) {
1637 // Special handling for pointers implicitly cast to bool;
1638 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1639 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1640 Expr* SubE = ICE->getSubExpr();
1641 if (SubE->getType()->isPointerType() ||
1642 SubE->getType()->isArrayType() ||
1643 SubE->getType()->isFunctionType()) {
1644 return CheckAddressConstantExpression(Init);
1645 }
1646 }
1647 } else if (InitTy->isIntegralType()) {
1648 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001649 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001650 SubE = CE->getSubExpr();
1651 // Special check for pointer cast to int; we allow as an extension
1652 // an address constant cast to an integer if the integer
1653 // is of an appropriate width (this sort of code is apparently used
1654 // in some places).
1655 // FIXME: Add pedwarn?
1656 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1657 if (SubE && (SubE->getType()->isPointerType() ||
1658 SubE->getType()->isArrayType() ||
1659 SubE->getType()->isFunctionType())) {
1660 unsigned IntWidth = Context.getTypeSize(Init->getType());
1661 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1662 if (IntWidth >= PointerWidth)
1663 return CheckAddressConstantExpression(Init);
1664 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001665 }
1666
1667 return CheckArithmeticConstantExpression(Init);
1668 }
1669
1670 if (Init->getType()->isPointerType())
1671 return CheckAddressConstantExpression(Init);
1672
Eli Friedman25086f02008-05-30 18:14:48 +00001673 // An array type at the top level that isn't an init-list must
1674 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001675 if (Init->getType()->isArrayType())
1676 return false;
1677
Nuno Lopes1dc26762008-09-01 18:42:41 +00001678 if (Init->getType()->isFunctionType())
1679 return false;
1680
Steve Naroffdff3fb22008-10-02 17:12:56 +00001681 // Allow block exprs at top level.
1682 if (Init->getType()->isBlockPointerType())
1683 return false;
1684
Steve Narofffc08f5e2008-10-27 11:34:16 +00001685 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001686 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00001687}
1688
Steve Naroff6a0e2092007-09-12 14:07:44 +00001689void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001690 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001691 Expr *Init = static_cast<Expr *>(init);
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001692 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00001693
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00001694 // If there is no declaration, there was an error parsing it. Just ignore
1695 // the initializer.
1696 if (RealDecl == 0) {
1697 delete Init;
1698 return;
1699 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001700
Steve Naroff420d0f52007-09-12 20:13:48 +00001701 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1702 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00001703 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1704 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00001705 RealDecl->setInvalidDecl();
1706 return;
1707 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001708 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00001709 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00001710 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001711 if (VDecl->isBlockVarDecl()) {
1712 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001713 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00001714 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001715 VDecl->setInvalidDecl();
1716 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001717 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1718 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001719 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00001720
1721 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1722 if (!getLangOptions().CPlusPlus) {
1723 if (SC == VarDecl::Static) // C99 6.7.8p4.
1724 CheckForConstantInitializer(Init, DclT);
1725 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001726 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001727 } else if (VDecl->isFileVarDecl()) {
1728 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00001729 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001730 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00001731 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1732 VDecl->getName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001733 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00001734
Anders Carlssonea7140a2008-08-22 05:00:02 +00001735 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1736 if (!getLangOptions().CPlusPlus) {
1737 // C99 6.7.8p4. All file scoped initializers need to be constant.
1738 CheckForConstantInitializer(Init, DclT);
1739 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001740 }
1741 // If the type changed, it means we had an incomplete type that was
1742 // completed by the initializer. For example:
1743 // int ary[] = { 1, 3, 5 };
1744 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00001745 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00001746 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00001747 Init->setType(DclT);
1748 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00001749
1750 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00001751 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00001752 return;
1753}
1754
Douglas Gregor81c29152008-10-29 00:13:59 +00001755void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1756 Decl *RealDecl = static_cast<Decl *>(dcl);
1757
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00001758 // If there is no declaration, there was an error parsing it. Just ignore it.
1759 if (RealDecl == 0)
1760 return;
1761
Douglas Gregor81c29152008-10-29 00:13:59 +00001762 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1763 QualType Type = Var->getType();
1764 // C++ [dcl.init.ref]p3:
1765 // The initializer can be omitted for a reference only in a
1766 // parameter declaration (8.3.5), in the declaration of a
1767 // function return type, in the declaration of a class member
1768 // within its class declaration (9.2), and where the extern
1769 // specifier is explicitly used.
Douglas Gregor5870a952008-11-03 20:45:27 +00001770 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Douglas Gregor81c29152008-10-29 00:13:59 +00001771 Diag(Var->getLocation(),
1772 diag::err_reference_var_requires_init,
1773 Var->getName(),
1774 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor5870a952008-11-03 20:45:27 +00001775 Var->setInvalidDecl();
1776 return;
1777 }
1778
1779 // C++ [dcl.init]p9:
1780 //
1781 // If no initializer is specified for an object, and the object
1782 // is of (possibly cv-qualified) non-POD class type (or array
1783 // thereof), the object shall be default-initialized; if the
1784 // object is of const-qualified type, the underlying class type
1785 // shall have a user-declared default constructor.
1786 if (getLangOptions().CPlusPlus) {
1787 QualType InitType = Type;
1788 if (const ArrayType *Array = Context.getAsArrayType(Type))
1789 InitType = Array->getElementType();
1790 if (InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00001791 const CXXConstructorDecl *Constructor
1792 = PerformInitializationByConstructor(InitType, 0, 0,
1793 Var->getLocation(),
1794 SourceRange(Var->getLocation(),
1795 Var->getLocation()),
1796 Var->getName(),
1797 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00001798 if (!Constructor)
1799 Var->setInvalidDecl();
1800 }
1801 }
Douglas Gregor81c29152008-10-29 00:13:59 +00001802
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001803#if 0
1804 // FIXME: Temporarily disabled because we are not properly parsing
1805 // linkage specifications on declarations, e.g.,
1806 //
1807 // extern "C" const CGPoint CGPointerZero;
1808 //
Douglas Gregor81c29152008-10-29 00:13:59 +00001809 // C++ [dcl.init]p9:
1810 //
1811 // If no initializer is specified for an object, and the
1812 // object is of (possibly cv-qualified) non-POD class type (or
1813 // array thereof), the object shall be default-initialized; if
1814 // the object is of const-qualified type, the underlying class
1815 // type shall have a user-declared default
1816 // constructor. Otherwise, if no initializer is specified for
1817 // an object, the object and its subobjects, if any, have an
1818 // indeterminate initial value; if the object or any of its
1819 // subobjects are of const-qualified type, the program is
1820 // ill-formed.
1821 //
1822 // This isn't technically an error in C, so we don't diagnose it.
1823 //
1824 // FIXME: Actually perform the POD/user-defined default
1825 // constructor check.
1826 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001827 Context.getCanonicalType(Type).isConstQualified() &&
1828 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor81c29152008-10-29 00:13:59 +00001829 Diag(Var->getLocation(),
1830 diag::err_const_var_requires_init,
1831 Var->getName(),
1832 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregorc0d11a82008-10-29 13:50:18 +00001833#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00001834 }
1835}
1836
Chris Lattner4b009652007-07-25 00:24:17 +00001837/// The declarators are chained together backwards, reverse the list.
1838Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1839 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001840 Decl *GroupDecl = static_cast<Decl*>(group);
1841 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00001842 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00001843
1844 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1845 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001846 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00001847 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001848 else { // reverse the list.
1849 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00001850 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001851 Group->setNextDeclarator(NewGroup);
1852 NewGroup = Group;
1853 Group = Next;
1854 }
1855 }
1856 // Perform semantic analysis that depends on having fully processed both
1857 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00001858 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00001859 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1860 if (!IDecl)
1861 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00001862 QualType T = IDecl->getType();
1863
1864 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1865 // static storage duration, it shall not have a variable length array.
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001866 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1867 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnera1923f62008-08-04 07:31:14 +00001868 if (T->isVariableArrayType()) {
Eli Friedman8ff07782008-02-15 18:16:39 +00001869 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1870 IDecl->setInvalidDecl();
Steve Naroff6a0e2092007-09-12 14:07:44 +00001871 }
1872 }
1873 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1874 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00001875 if (IDecl->isBlockVarDecl() &&
1876 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001877 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner2f72aa02007-12-02 07:50:03 +00001878 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1879 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001880 IDecl->setInvalidDecl();
1881 }
1882 }
1883 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1884 // object that has file scope without an initializer, and without a
1885 // storage-class specifier or with the storage-class specifier "static",
1886 // constitutes a tentative definition. Note: A tentative definition with
1887 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00001888 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00001889 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00001890 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1891 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00001892 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00001893 // C99 6.9.2p3: If the declaration of an identifier for an object is
1894 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1895 // declared type shall not be an incomplete type.
Chris Lattner2f72aa02007-12-02 07:50:03 +00001896 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1897 T.getAsString());
Steve Naroff6a0e2092007-09-12 14:07:44 +00001898 IDecl->setInvalidDecl();
1899 }
1900 }
Steve Naroffb5e78152008-08-08 17:50:35 +00001901 if (IDecl->isFileVarDecl())
1902 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00001903 }
1904 return NewGroup;
1905}
Steve Naroff91b03f72007-08-28 03:03:08 +00001906
Chris Lattner3e254fb2008-04-08 04:40:51 +00001907/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1908/// to introduce parameters into function prototype scope.
1909Sema::DeclTy *
1910Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001911 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner5e77ade2008-06-26 06:49:43 +00001912 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001913
1914 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001915 VarDecl::StorageClass StorageClass = VarDecl::None;
1916 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1917 StorageClass = VarDecl::Register;
1918 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001919 Diag(DS.getStorageClassSpecLoc(),
1920 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001921 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001922 }
1923 if (DS.isThreadSpecified()) {
1924 Diag(DS.getThreadSpecLoc(),
1925 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00001926 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00001927 }
1928
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001929 // Check that there are no default arguments inside the type of this
1930 // parameter (C++ only).
1931 if (getLangOptions().CPlusPlus)
1932 CheckExtraCXXDefaultArguments(D);
1933
Chris Lattner3e254fb2008-04-08 04:40:51 +00001934 // In this context, we *do not* check D.getInvalidType(). If the declarator
1935 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1936 // though it will not reflect the user specified type.
1937 QualType parmDeclType = GetTypeForDeclarator(D, S);
1938
1939 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1940
Chris Lattner4b009652007-07-25 00:24:17 +00001941 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1942 // Can this happen for params? We already checked that they don't conflict
1943 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001944 IdentifierInfo *II = D.getIdentifier();
1945 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1946 if (S->isDeclScope(PrevDecl)) {
1947 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1948 dyn_cast<NamedDecl>(PrevDecl)->getName());
1949
1950 // Recover by removing the name
1951 II = 0;
1952 D.SetIdentifier(0, D.getIdentifierLoc());
1953 }
Chris Lattner4b009652007-07-25 00:24:17 +00001954 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00001955
1956 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1957 // Doing the promotion here has a win and a loss. The win is the type for
1958 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1959 // code generator). The loss is the orginal type isn't preserved. For example:
1960 //
1961 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
1962 // int blockvardecl[5];
1963 // sizeof(parmvardecl); // size == 4
1964 // sizeof(blockvardecl); // size == 20
1965 // }
1966 //
1967 // For expressions, all implicit conversions are captured using the
1968 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
1969 //
1970 // FIXME: If a source translation tool needs to see the original type, then
1971 // we need to consider storing both types (in ParmVarDecl)...
1972 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00001973 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00001974 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00001975 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00001976 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00001977 parmDeclType = Context.getPointerType(parmDeclType);
1978
Chris Lattner3e254fb2008-04-08 04:40:51 +00001979 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
1980 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00001981 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00001982 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00001983
Chris Lattner3e254fb2008-04-08 04:40:51 +00001984 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00001985 New->setInvalidDecl();
1986
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001987 if (II)
1988 PushOnScopeChains(New, S);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00001989
Chris Lattner9b384ca2008-06-29 00:02:00 +00001990 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00001991 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001992
Chris Lattner4b009652007-07-25 00:24:17 +00001993}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00001994
Chris Lattnerea148702007-10-09 17:14:05 +00001995Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00001996 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00001997 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
1998 "Not a function declarator!");
1999 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002000
Chris Lattner4b009652007-07-25 00:24:17 +00002001 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2002 // for a K&R function.
2003 if (!FTI.hasPrototype) {
2004 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002005 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00002006 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared,
2007 FTI.ArgInfo[i].Ident->getName());
2008 // Implicitly declare the argument as type 'int' for lack of a better
2009 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002010 DeclSpec DS;
2011 const char* PrevSpec; // unused
2012 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2013 PrevSpec);
2014 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2015 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2016 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002017 }
2018 }
Chris Lattner4b009652007-07-25 00:24:17 +00002019 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002020 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002021 }
2022
2023 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002024
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002025 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002026 ActOnDeclarator(GlobalScope, D, 0));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002027}
2028
2029Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2030 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002031 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002032
2033 // See if this is a redefinition.
2034 const FunctionDecl *Definition;
2035 if (FD->getBody(Definition)) {
2036 Diag(FD->getLocation(), diag::err_redefinition,
2037 FD->getName());
2038 Diag(Definition->getLocation(), diag::err_previous_definition);
2039 }
2040
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002041 PushDeclContext(FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00002042
2043 // Check the validity of our function parameters
2044 CheckParmsForFunctionDef(FD);
2045
2046 // Introduce our parameters into the function scope
2047 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2048 ParmVarDecl *Param = FD->getParamDecl(p);
2049 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002050 if (Param->getIdentifier())
2051 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002052 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002053
Chris Lattner4b009652007-07-25 00:24:17 +00002054 return FD;
2055}
2056
Steve Naroff99ee4302007-11-11 23:20:51 +00002057Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2058 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002059 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002060 FD->setBody((Stmt*)Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002061 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002062 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002063 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002064 } else
2065 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002066 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002067 // Verify and clean out per-function state.
2068
2069 // Check goto/label use.
2070 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2071 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2072 // Verify that we have no forward references left. If so, there was a goto
2073 // or address of a label taken, but no definition of it. Label fwd
2074 // definitions are indicated with a null substmt.
2075 if (I->second->getSubStmt() == 0) {
2076 LabelStmt *L = I->second;
2077 // Emit error.
2078 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2079
2080 // At this point, we have gotos that use the bogus label. Stitch it into
2081 // the function body so that they aren't leaked and that the AST is well
2082 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002083 if (Body) {
2084 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2085 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2086 } else {
2087 // The whole function wasn't parsed correctly, just delete this.
2088 delete L;
2089 }
Chris Lattner4b009652007-07-25 00:24:17 +00002090 }
2091 }
2092 LabelMap.clear();
2093
Steve Naroff99ee4302007-11-11 23:20:51 +00002094 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002095}
2096
Chris Lattner4b009652007-07-25 00:24:17 +00002097/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2098/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002099ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2100 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002101 // Extension in C99. Legal in C90, but warn about it.
2102 if (getLangOptions().C99)
Chris Lattner4b009652007-07-25 00:24:17 +00002103 Diag(Loc, diag::ext_implicit_function_decl, II.getName());
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002104 else
Chris Lattner4b009652007-07-25 00:24:17 +00002105 Diag(Loc, diag::warn_implicit_function_decl, II.getName());
2106
2107 // FIXME: handle stuff like:
2108 // void foo() { extern float X(); }
2109 // void bar() { X(); } <-- implicit decl for X in another scope.
2110
2111 // Set a Declarator for the implicit definition: int foo();
2112 const char *Dummy;
2113 DeclSpec DS;
2114 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2115 Error = Error; // Silence warning.
2116 assert(!Error && "Error setting up implicit decl!");
2117 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002118 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002119 D.SetIdentifier(&II, Loc);
2120
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002121 // Insert this function into translation-unit scope.
2122
2123 DeclContext *PrevDC = CurContext;
2124 CurContext = Context.getTranslationUnitDecl();
2125
Steve Naroff9104f3c2008-04-04 14:32:09 +00002126 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002127 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002128 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002129
2130 CurContext = PrevDC;
2131
Steve Naroff9104f3c2008-04-04 14:32:09 +00002132 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002133}
2134
2135
Chris Lattner82bb4792007-11-14 06:34:38 +00002136TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002137 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002138 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002139 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002140
2141 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002142 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2143 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002144 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002145 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002146 if (D.getInvalidType())
2147 NewTD->setInvalidDecl();
2148 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002149}
2150
Steve Naroff0acc9c92007-09-15 18:49:24 +00002151/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002152/// former case, Name will be non-null. In the later case, Name will be null.
2153/// TagType indicates what kind of tag this is. TK indicates whether this is a
2154/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002155Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002156 SourceLocation KWLoc, const CXXScopeSpec &SS,
2157 IdentifierInfo *Name, SourceLocation NameLoc,
2158 AttributeList *Attr) {
Chris Lattner4b009652007-07-25 00:24:17 +00002159 // If this is a use of an existing tag, it must have a name.
2160 assert((Name != 0 || TK == TK_Definition) &&
2161 "Nameless record must be a definition!");
2162
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002163 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002164 switch (TagType) {
2165 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002166 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2167 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2168 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2169 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002170 }
2171
Ted Kremenek46a837c2008-09-05 17:16:31 +00002172 // Two code paths: a new one for structs/unions/classes where we create
2173 // separate decls for forward declarations, and an old (eventually to
2174 // be removed) code path for enums.
2175 if (Kind != TagDecl::TK_enum)
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002176 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002177
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002178 DeclContext *DC = CurContext;
2179 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002180
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002181 if (Name && SS.isNotEmpty()) {
2182 // We have a nested-name tag ('struct foo::bar').
2183
2184 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002185 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002186 Name = 0;
2187 goto CreateNewDecl;
2188 }
2189
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002190 DC = static_cast<DeclContext*>(SS.getScopeRep());
2191 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002192 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2193
2194 // A tag 'foo::bar' must already exist.
2195 if (PrevDecl == 0) {
2196 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2197 SS.getRange());
2198 Name = 0;
2199 goto CreateNewDecl;
2200 }
2201 } else {
2202 // If this is a named struct, check to see if there was a previous forward
2203 // declaration or definition.
2204 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2205 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2206 }
2207
Ted Kremenekd4434152008-09-02 21:26:19 +00002208 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002209 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2210 "unexpected Decl type");
2211 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002212 // If this is a use of a previous tag, or if the tag is already declared
2213 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002214 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002215 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002216 // Make sure that this wasn't declared as an enum and now used as a
2217 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002218 if (PrevTagDecl->getTagKind() != Kind) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002219 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2220 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002221 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002222 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002223 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002224 } else {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002225 // If this is a use or a forward declaration, we're good.
2226 if (TK != TK_Definition)
2227 return PrevDecl;
2228
2229 // Diagnose attempts to redefine a tag.
2230 if (PrevTagDecl->isDefinition()) {
2231 Diag(NameLoc, diag::err_redefinition, Name->getName());
2232 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2233 // If this is a redefinition, recover by making this struct be
2234 // anonymous, which will make any later references get the previous
2235 // definition.
2236 Name = 0;
2237 } else {
2238 // Okay, this is definition of a previously declared or referenced
2239 // tag. Move the location of the decl to be the definition site.
2240 PrevDecl->setLocation(NameLoc);
2241 return PrevDecl;
2242 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002243 }
Chris Lattner4b009652007-07-25 00:24:17 +00002244 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002245 // If we get here, this is a definition of a new struct type in a nested
2246 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2247 // type.
2248 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002249 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002250 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002251 // The tag name clashes with a namespace name, issue an error and
2252 // recover by making this tag be anonymous.
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002253 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2254 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2255 Name = 0;
2256 }
Chris Lattner4b009652007-07-25 00:24:17 +00002257 }
Chris Lattner4b009652007-07-25 00:24:17 +00002258 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002259
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002260 CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002261
2262 // If there is an identifier, use the location of the identifier as the
2263 // location of the decl, otherwise use the location of the struct/union
2264 // keyword.
2265 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2266
2267 // Otherwise, if this is the first time we've seen this tag, create the decl.
2268 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002269 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002270 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2271 // enum X { A, B, C } D; D should chain to X.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002272 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Chris Lattner4b009652007-07-25 00:24:17 +00002273 // If this is an undefined enum, warn.
2274 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002275 } else {
2276 // struct/union/class
2277
Chris Lattner4b009652007-07-25 00:24:17 +00002278 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2279 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002280 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002281 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002282 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002283 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002284 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002285 }
Chris Lattner4b009652007-07-25 00:24:17 +00002286
2287 // If this has an identifier, add it to the scope stack.
2288 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002289 // The scope passed in may not be a decl scope. Zip up the scope tree until
2290 // we find one that is.
2291 while ((S->getFlags() & Scope::DeclScope) == 0)
2292 S = S->getParent();
2293
2294 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002295 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002296 }
Chris Lattner33aad6e2008-02-06 00:51:33 +00002297
Chris Lattnerd7e83d82008-06-28 23:58:55 +00002298 if (Attr)
2299 ProcessDeclAttributeList(New, Attr);
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002300
2301 // Set the lexical context. If the tag has a C++ scope specifier, the
2302 // lexical context will be different from the semantic context.
2303 New->setLexicalDeclContext(CurContext);
2304
Chris Lattner4b009652007-07-25 00:24:17 +00002305 return New;
2306}
2307
Ted Kremenek46a837c2008-09-05 17:16:31 +00002308/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2309/// the logic for enums, we create separate decls for forward declarations.
2310/// This is called by ActOnTag, but eventually will replace its logic.
2311Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002312 SourceLocation KWLoc, const CXXScopeSpec &SS,
2313 IdentifierInfo *Name, SourceLocation NameLoc,
2314 AttributeList *Attr) {
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002315 DeclContext *DC = CurContext;
2316 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002317
2318 if (Name && SS.isNotEmpty()) {
2319 // We have a nested-name tag ('struct foo::bar').
2320
2321 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002322 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002323 Name = 0;
2324 goto CreateNewDecl;
2325 }
2326
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002327 DC = static_cast<DeclContext*>(SS.getScopeRep());
2328 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002329 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2330
2331 // A tag 'foo::bar' must already exist.
2332 if (PrevDecl == 0) {
2333 Diag(NameLoc, diag::err_not_tag_in_scope, Name->getName(),
2334 SS.getRange());
2335 Name = 0;
2336 goto CreateNewDecl;
2337 }
2338 } else {
2339 // If this is a named struct, check to see if there was a previous forward
2340 // declaration or definition.
2341 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2342 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2343 }
Ted Kremenek46a837c2008-09-05 17:16:31 +00002344
2345 if (PrevDecl) {
2346 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2347 "unexpected Decl type");
2348
2349 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2350 // If this is a use of a previous tag, or if the tag is already declared
2351 // in the same scope (so that the definition/declaration completes or
2352 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002353 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002354 // Make sure that this wasn't declared as an enum and now used as a
2355 // struct or something similar.
2356 if (PrevTagDecl->getTagKind() != Kind) {
2357 Diag(KWLoc, diag::err_use_with_wrong_tag, Name->getName());
2358 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2359 // Recover by making this an anonymous redefinition.
2360 Name = 0;
2361 PrevDecl = 0;
2362 } else {
2363 // If this is a use, return the original decl.
2364
2365 // FIXME: In the future, return a variant or some other clue
2366 // for the consumer of this Decl to know it doesn't own it.
2367 // For our current ASTs this shouldn't be a problem, but will
2368 // need to be changed with DeclGroups.
2369 if (TK == TK_Reference)
2370 return PrevDecl;
2371
2372 // The new decl is a definition?
2373 if (TK == TK_Definition) {
2374 // Diagnose attempts to redefine a tag.
2375 if (RecordDecl* DefRecord =
2376 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
2377 Diag(NameLoc, diag::err_redefinition, Name->getName());
2378 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2379 // If this is a redefinition, recover by making this struct be
2380 // anonymous, which will make any later references get the previous
2381 // definition.
2382 Name = 0;
2383 PrevDecl = 0;
2384 }
2385 // Okay, this is definition of a previously declared or referenced
2386 // tag. We're going to create a new Decl.
2387 }
2388 }
2389 // If we get here we have (another) forward declaration. Just create
2390 // a new decl.
2391 }
2392 else {
2393 // If we get here, this is a definition of a new struct type in a nested
2394 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2395 // new decl/type. We set PrevDecl to NULL so that the Records
2396 // have distinct types.
2397 PrevDecl = 0;
2398 }
2399 } else {
2400 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002401 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002402 // The tag name clashes with a namespace name, issue an error and
2403 // recover by making this tag be anonymous.
2404 Diag(NameLoc, diag::err_redefinition_different_kind, Name->getName());
2405 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2406 Name = 0;
2407 }
2408 }
2409 }
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002410
2411 CreateNewDecl:
2412
Ted Kremenek46a837c2008-09-05 17:16:31 +00002413 // If there is an identifier, use the location of the identifier as the
2414 // location of the decl, otherwise use the location of the struct/union
2415 // keyword.
2416 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2417
2418 // Otherwise, if this is the first time we've seen this tag, create the decl.
2419 TagDecl *New;
2420
2421 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2422 // struct X { int A; } D; D should chain to X.
2423 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002424 // FIXME: Look for a way to use RecordDecl for simple structs.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002425 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002426 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2427 else
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002428 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek46a837c2008-09-05 17:16:31 +00002429 dyn_cast_or_null<RecordDecl>(PrevDecl));
2430
2431 // If this has an identifier, add it to the scope stack.
2432 if ((TK == TK_Definition || !PrevDecl) && Name) {
2433 // The scope passed in may not be a decl scope. Zip up the scope tree until
2434 // we find one that is.
2435 while ((S->getFlags() & Scope::DeclScope) == 0)
2436 S = S->getParent();
2437
2438 // Add it to the decl chain.
2439 PushOnScopeChains(New, S);
2440 }
Daniel Dunbar2cb762f2008-10-16 02:34:03 +00002441
2442 // Handle #pragma pack: if the #pragma pack stack has non-default
2443 // alignment, make up a packed attribute for this decl. These
2444 // attributes are checked when the ASTContext lays out the
2445 // structure.
2446 //
2447 // It is important for implementing the correct semantics that this
2448 // happen here (in act on tag decl). The #pragma pack stack is
2449 // maintained as a result of parser callbacks which can occur at
2450 // many points during the parsing of a struct declaration (because
2451 // the #pragma tokens are effectively skipped over during the
2452 // parsing of the struct).
2453 if (unsigned Alignment = PackContext.getAlignment())
2454 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek46a837c2008-09-05 17:16:31 +00002455
2456 if (Attr)
2457 ProcessDeclAttributeList(New, Attr);
2458
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002459 // Set the lexical context. If the tag has a C++ scope specifier, the
2460 // lexical context will be different from the semantic context.
2461 New->setLexicalDeclContext(CurContext);
2462
Ted Kremenek46a837c2008-09-05 17:16:31 +00002463 return New;
2464}
2465
2466
Chris Lattner1bf58f62008-06-21 19:39:06 +00002467/// Collect the instance variables declared in an Objective-C object. Used in
2468/// the creation of structures from objects using the @defs directive.
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002469static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002470 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002471 if (Class->getSuperClass())
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002472 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2473
2474 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremenek40e70e72008-09-03 18:03:35 +00002475 for (ObjCInterfaceDecl::ivar_iterator
2476 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2477
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002478 ObjCIvarDecl* ID = *I;
2479 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2480 ID->getIdentifier(),
2481 ID->getType(),
2482 ID->getBitWidth()));
2483 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002484}
2485
2486/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2487/// instance variables of ClassName into Decls.
2488void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2489 IdentifierInfo *ClassName,
Chris Lattnere705e5e2008-07-21 22:17:28 +00002490 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner1bf58f62008-06-21 19:39:06 +00002491 // Check that ClassName is a valid class
2492 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2493 if (!Class) {
2494 Diag(DeclStart, diag::err_undef_interface, ClassName->getName());
2495 return;
2496 }
Chris Lattner1bf58f62008-06-21 19:39:06 +00002497 // Collect the instance variables
Ted Kremeneke5bedfe2008-08-20 03:26:33 +00002498 CollectIvars(Class, Context, Decls);
Chris Lattner1bf58f62008-06-21 19:39:06 +00002499}
2500
Chris Lattnera73e2202008-11-12 21:17:48 +00002501/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2502/// types into constant array types in certain situations which would otherwise
2503/// be errors (for GCC compatibility).
2504static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2505 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002506 // This method tries to turn a variable array into a constant
2507 // array even when the size isn't an ICE. This is necessary
2508 // for compatibility with code that depends on gcc's buggy
2509 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002510 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2511 if (!VLATy) return QualType();
2512
2513 APValue Result;
2514 if (!VLATy->getSizeExpr() ||
Chris Lattneref069662008-11-16 21:24:15 +00002515 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002516 return QualType();
2517
2518 assert(Result.isInt() && "Size expressions must be integers!");
2519 llvm::APSInt &Res = Result.getInt();
2520 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2521 return Context.getConstantArrayType(VLATy->getElementType(),
2522 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002523 return QualType();
2524}
2525
Steve Naroff0acc9c92007-09-15 18:49:24 +00002526/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002527/// to create a FieldDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002528Sema::DeclTy *Sema::ActOnField(Scope *S,
Chris Lattner4b009652007-07-25 00:24:17 +00002529 SourceLocation DeclStart,
2530 Declarator &D, ExprTy *BitfieldWidth) {
2531 IdentifierInfo *II = D.getIdentifier();
2532 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002533 SourceLocation Loc = DeclStart;
2534 if (II) Loc = D.getIdentifierLoc();
2535
2536 // FIXME: Unnamed fields can be handled in various different ways, for
2537 // example, unnamed unions inject all members into the struct namespace!
Ted Kremenek40e70e72008-09-03 18:03:35 +00002538
Chris Lattner4b009652007-07-25 00:24:17 +00002539 if (BitWidth) {
2540 // TODO: Validate.
2541 //printf("WARNING: BITFIELDS IGNORED!\n");
2542
2543 // 6.7.2.1p3
2544 // 6.7.2.1p4
2545
2546 } else {
2547 // Not a bitfield.
2548
2549 // validate II.
2550
2551 }
2552
2553 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002554 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2555 bool InvalidDecl = false;
Steve Naroff5eb879b2007-08-31 17:20:07 +00002556
Chris Lattner4b009652007-07-25 00:24:17 +00002557 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2558 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002559 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00002560 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002561 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00002562 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002563 T = FixedTy;
2564 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00002565 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00002566 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002567 InvalidDecl = true;
2568 }
Chris Lattner4b009652007-07-25 00:24:17 +00002569 }
Chris Lattner4b009652007-07-25 00:24:17 +00002570 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002571 FieldDecl *NewFD;
2572
2573 if (getLangOptions().CPlusPlus) {
2574 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2575 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
2576 Loc, II, T, BitWidth);
2577 if (II)
2578 PushOnScopeChains(NewFD, S);
2579 }
2580 else
2581 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff75494892007-09-11 21:17:26 +00002582
Chris Lattner9b384ca2008-06-29 00:02:00 +00002583 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002584
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002585 if (D.getInvalidType() || InvalidDecl)
2586 NewFD->setInvalidDecl();
2587 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002588}
2589
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002590/// TranslateIvarVisibility - Translate visibility from a token ID to an
2591/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002592static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002593TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002594 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002595 default: assert(0 && "Unknown visitibility kind");
2596 case tok::objc_private: return ObjCIvarDecl::Private;
2597 case tok::objc_public: return ObjCIvarDecl::Public;
2598 case tok::objc_protected: return ObjCIvarDecl::Protected;
2599 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002600 }
2601}
2602
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002603/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2604/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002605Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002606 SourceLocation DeclStart,
2607 Declarator &D, ExprTy *BitfieldWidth,
2608 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002609 IdentifierInfo *II = D.getIdentifier();
2610 Expr *BitWidth = (Expr*)BitfieldWidth;
2611 SourceLocation Loc = DeclStart;
2612 if (II) Loc = D.getIdentifierLoc();
2613
2614 // FIXME: Unnamed fields can be handled in various different ways, for
2615 // example, unnamed unions inject all members into the struct namespace!
2616
2617
2618 if (BitWidth) {
2619 // TODO: Validate.
2620 //printf("WARNING: BITFIELDS IGNORED!\n");
2621
2622 // 6.7.2.1p3
2623 // 6.7.2.1p4
2624
2625 } else {
2626 // Not a bitfield.
2627
2628 // validate II.
2629
2630 }
2631
2632 QualType T = GetTypeForDeclarator(D, S);
2633 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2634 bool InvalidDecl = false;
2635
2636 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2637 // than a variably modified type.
2638 if (T->isVariablyModifiedType()) {
2639 // FIXME: This diagnostic needs work
2640 Diag(Loc, diag::err_typecheck_illegal_vla, Loc);
2641 InvalidDecl = true;
2642 }
2643
Ted Kremenek173dd312008-07-23 18:04:17 +00002644 // Get the visibility (access control) for this ivar.
2645 ObjCIvarDecl::AccessControl ac =
2646 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2647 : ObjCIvarDecl::None;
2648
2649 // Construct the decl.
2650 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002651 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002652
Ted Kremenek173dd312008-07-23 18:04:17 +00002653 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002654 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002655
2656 if (D.getInvalidType() || InvalidDecl)
2657 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002658
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002659 return NewID;
2660}
2661
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002662void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002663 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002664 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002665 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002666 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002667 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2668 assert(EnclosingDecl && "missing record or interface decl");
2669 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2670
Ted Kremenek46a837c2008-09-05 17:16:31 +00002671 if (Record)
2672 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2673 // Diagnose code like:
2674 // struct S { struct S {} X; };
2675 // We discover this when we complete the outer S. Reject and ignore the
2676 // outer S.
2677 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2678 DefRecord->getKindName());
2679 Diag(RecLoc, diag::err_previous_definition);
2680 Record->setInvalidDecl();
2681 return;
2682 }
2683
Chris Lattner4b009652007-07-25 00:24:17 +00002684 // Verify that all the fields are okay.
2685 unsigned NumNamedMembers = 0;
2686 llvm::SmallVector<FieldDecl*, 32> RecFields;
2687 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002688
Chris Lattner4b009652007-07-25 00:24:17 +00002689 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002690
Steve Naroff9bb759f2007-09-14 22:20:54 +00002691 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2692 assert(FD && "missing field decl");
2693
2694 // Remember all fields.
2695 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002696
2697 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002698 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002699
Chris Lattner4b009652007-07-25 00:24:17 +00002700 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002701 if (FDTy->isFunctionType()) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002702 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Chris Lattner4b009652007-07-25 00:24:17 +00002703 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002704 FD->setInvalidDecl();
2705 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002706 continue;
2707 }
Chris Lattner4b009652007-07-25 00:24:17 +00002708 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2709 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002710 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002711 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002712 FD->setInvalidDecl();
2713 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002714 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002715 }
Chris Lattner4b009652007-07-25 00:24:17 +00002716 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002717 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002718 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner4b009652007-07-25 00:24:17 +00002719 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002720 FD->setInvalidDecl();
2721 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002722 continue;
2723 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002724 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner4b009652007-07-25 00:24:17 +00002725 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2726 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002727 FD->setInvalidDecl();
2728 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002729 continue;
2730 }
Chris Lattner4b009652007-07-25 00:24:17 +00002731 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002732 if (Record)
2733 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002734 }
Chris Lattner4b009652007-07-25 00:24:17 +00002735 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2736 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002737 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002738 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2739 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002740 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002741 Record->setHasFlexibleArrayMember(true);
2742 } else {
2743 // If this is a struct/class and this is not the last element, reject
2744 // it. Note that GCC supports variable sized arrays in the middle of
2745 // structures.
2746 if (i != NumFields-1) {
2747 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2748 FD->getName());
Steve Naroff9bb759f2007-09-14 22:20:54 +00002749 FD->setInvalidDecl();
2750 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002751 continue;
2752 }
Chris Lattner4b009652007-07-25 00:24:17 +00002753 // We support flexible arrays at the end of structs in other structs
2754 // as an extension.
2755 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2756 FD->getName());
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002757 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002758 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002759 }
2760 }
2761 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002762 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002763 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002764 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2765 FD->getName());
2766 FD->setInvalidDecl();
2767 EnclosingDecl->setInvalidDecl();
2768 continue;
2769 }
Chris Lattner4b009652007-07-25 00:24:17 +00002770 // Keep track of the number of named members.
2771 if (IdentifierInfo *II = FD->getIdentifier()) {
2772 // Detect duplicate member names.
2773 if (!FieldIDs.insert(II)) {
2774 Diag(FD->getLocation(), diag::err_duplicate_member, II->getName());
2775 // Find the previous decl.
2776 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00002777 for (unsigned i = 0; ; ++i) {
2778 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00002779 if (RecFields[i]->getIdentifier() == II) {
2780 PrevLoc = RecFields[i]->getLocation();
2781 break;
2782 }
2783 }
2784 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00002785 FD->setInvalidDecl();
2786 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002787 continue;
2788 }
2789 ++NumNamedMembers;
2790 }
Chris Lattner4b009652007-07-25 00:24:17 +00002791 }
2792
Chris Lattner4b009652007-07-25 00:24:17 +00002793 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00002794 if (Record) {
Ted Kremenek46a837c2008-09-05 17:16:31 +00002795 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00002796 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2797 // Sema::ActOnFinishCXXClassDef.
2798 if (!isa<CXXRecordDecl>(Record))
2799 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00002800 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00002801 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2802 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2803 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2804 else if (ObjCImplementationDecl *IMPDecl =
2805 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00002806 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2807 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00002808 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00002809 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00002810 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00002811
2812 if (Attr)
2813 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00002814}
2815
Steve Naroff0acc9c92007-09-15 18:49:24 +00002816Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00002817 DeclTy *lastEnumConst,
2818 SourceLocation IdLoc, IdentifierInfo *Id,
2819 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00002820 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002821 EnumConstantDecl *LastEnumConst =
2822 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2823 Expr *Val = static_cast<Expr*>(val);
2824
Chris Lattnera7549902007-08-26 06:24:45 +00002825 // The scope passed in may not be a decl scope. Zip up the scope tree until
2826 // we find one that is.
2827 while ((S->getFlags() & Scope::DeclScope) == 0)
2828 S = S->getParent();
2829
Chris Lattner4b009652007-07-25 00:24:17 +00002830 // Verify that there isn't already something declared with this name in this
2831 // scope.
Steve Naroff6384a012008-04-02 14:35:35 +00002832 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00002833 // When in C++, we may get a TagDecl with the same name; in this case the
2834 // enum constant will 'hide' the tag.
2835 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2836 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00002837 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00002838 if (isa<EnumConstantDecl>(PrevDecl))
2839 Diag(IdLoc, diag::err_redefinition_of_enumerator, Id->getName());
2840 else
2841 Diag(IdLoc, diag::err_redefinition, Id->getName());
2842 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002843 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00002844 return 0;
2845 }
2846 }
2847
2848 llvm::APSInt EnumVal(32);
2849 QualType EltTy;
2850 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00002851 // Make sure to promote the operand type to int.
2852 UsualUnaryConversions(Val);
2853
Chris Lattner4b009652007-07-25 00:24:17 +00002854 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2855 SourceLocation ExpLoc;
2856 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
2857 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr,
2858 Id->getName());
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002859 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00002860 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00002861 } else {
2862 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00002863 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00002864 }
2865
2866 if (!Val) {
2867 if (LastEnumConst) {
2868 // Assign the last value + 1.
2869 EnumVal = LastEnumConst->getInitVal();
2870 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00002871
2872 // Check for overflow on increment.
2873 if (EnumVal < LastEnumConst->getInitVal())
2874 Diag(IdLoc, diag::warn_enum_value_overflow);
2875
Chris Lattnere7f53a42007-08-27 17:37:24 +00002876 EltTy = LastEnumConst->getType();
2877 } else {
2878 // First value, set to zero.
2879 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002880 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00002881 }
Chris Lattner4b009652007-07-25 00:24:17 +00002882 }
2883
Chris Lattnere4650482008-03-15 06:12:44 +00002884 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00002885 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2886 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00002887 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00002888
2889 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002890 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002891 return New;
2892}
2893
Steve Naroffb0726b82008-08-07 14:08:16 +00002894// FIXME: For consistency with ActOnFields(), we should have the parser
2895// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002896void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00002897 DeclTy **Elements, unsigned NumElements) {
2898 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00002899
Steve Naroffb0726b82008-08-07 14:08:16 +00002900 if (Enum && Enum->isDefinition()) {
2901 // Diagnose code like:
2902 // enum e0 {
2903 // E0 = sizeof(enum e0 { E1 })
2904 // };
2905 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2906 Enum->getName());
2907 Diag(EnumLoc, diag::err_previous_definition);
2908 Enum->setInvalidDecl();
2909 return;
2910 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00002911 // TODO: If the result value doesn't fit in an int, it must be a long or long
2912 // long value. ISO C does not support this, but GCC does as an extension,
2913 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00002914 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00002915
Chris Lattner206754a2007-08-28 06:15:15 +00002916 // Verify that all the values are okay, compute the size of the values, and
2917 // reverse the list.
2918 unsigned NumNegativeBits = 0;
2919 unsigned NumPositiveBits = 0;
2920
2921 // Keep track of whether all elements have type int.
2922 bool AllElementsInt = true;
2923
Chris Lattner4b009652007-07-25 00:24:17 +00002924 EnumConstantDecl *EltList = 0;
2925 for (unsigned i = 0; i != NumElements; ++i) {
2926 EnumConstantDecl *ECD =
2927 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2928 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002929
2930 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00002931 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002932 assert(InitVal.getBitWidth() >= IntWidth &&
2933 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00002934 if (InitVal.getBitWidth() > IntWidth) {
2935 llvm::APSInt V(InitVal);
2936 V.trunc(IntWidth);
2937 V.extend(InitVal.getBitWidth());
2938 if (V != InitVal)
2939 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattneread053a2008-08-17 07:19:51 +00002940 InitVal.toString(10));
Chris Lattnercb33ae12007-08-28 05:27:00 +00002941 }
Chris Lattner206754a2007-08-28 06:15:15 +00002942
2943 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00002944 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00002945 NumPositiveBits = std::max(NumPositiveBits,
2946 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00002947 else
Chris Lattneraff63f02008-01-14 21:47:29 +00002948 NumNegativeBits = std::max(NumNegativeBits,
2949 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00002950
Chris Lattner206754a2007-08-28 06:15:15 +00002951 // Keep track of whether every enum element has type int (very commmon).
2952 if (AllElementsInt)
2953 AllElementsInt = ECD->getType() == Context.IntTy;
2954
Chris Lattner4b009652007-07-25 00:24:17 +00002955 ECD->setNextDeclarator(EltList);
2956 EltList = ECD;
2957 }
2958
Chris Lattner206754a2007-08-28 06:15:15 +00002959 // Figure out the type that should be used for this enum.
2960 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2961 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002962 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00002963
2964 if (NumNegativeBits) {
2965 // If there is a negative value, figure out the smallest integer type (of
2966 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002967 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002968 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002969 BestWidth = IntWidth;
2970 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002971 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002972
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002973 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002974 BestType = Context.LongTy;
2975 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00002976 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00002977
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002978 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00002979 Diag(Enum->getLocation(), diag::warn_enum_too_large);
2980 BestType = Context.LongLongTy;
2981 }
2982 }
2983 } else {
2984 // If there is no negative value, figure out which of uint, ulong, ulonglong
2985 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002986 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00002987 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002988 BestWidth = IntWidth;
2989 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00002990 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00002991 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00002992 } else {
2993 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00002994 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00002995 "How could an initializer get larger than ULL?");
2996 BestType = Context.UnsignedLongLongTy;
2997 }
2998 }
2999
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003000 // Loop over all of the enumerator constants, changing their types to match
3001 // the type of the enum if needed.
3002 for (unsigned i = 0; i != NumElements; ++i) {
3003 EnumConstantDecl *ECD =
3004 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3005 if (!ECD) continue; // Already issued a diagnostic.
3006
3007 // Standard C says the enumerators have int type, but we allow, as an
3008 // extension, the enumerators to be larger than int size. If each
3009 // enumerator value fits in an int, type it as an int, otherwise type it the
3010 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3011 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003012 if (ECD->getType() == Context.IntTy) {
3013 // Make sure the init value is signed.
3014 llvm::APSInt IV = ECD->getInitVal();
3015 IV.setIsSigned(true);
3016 ECD->setInitVal(IV);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003017 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003018 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003019
3020 // Determine whether the value fits into an int.
3021 llvm::APSInt InitVal = ECD->getInitVal();
3022 bool FitsInInt;
3023 if (InitVal.isUnsigned() || !InitVal.isNegative())
3024 FitsInInt = InitVal.getActiveBits() < IntWidth;
3025 else
3026 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3027
3028 // If it fits into an integer type, force it. Otherwise force it to match
3029 // the enum decl type.
3030 QualType NewTy;
3031 unsigned NewWidth;
3032 bool NewSign;
3033 if (FitsInInt) {
3034 NewTy = Context.IntTy;
3035 NewWidth = IntWidth;
3036 NewSign = true;
3037 } else if (ECD->getType() == BestType) {
3038 // Already the right type!
3039 continue;
3040 } else {
3041 NewTy = BestType;
3042 NewWidth = BestWidth;
3043 NewSign = BestType->isSignedIntegerType();
3044 }
3045
3046 // Adjust the APSInt value.
3047 InitVal.extOrTrunc(NewWidth);
3048 InitVal.setIsSigned(NewSign);
3049 ECD->setInitVal(InitVal);
3050
3051 // Adjust the Expr initializer and type.
Douglas Gregor70d26122008-11-12 17:17:38 +00003052 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3053 /*isLvalue=*/false));
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003054 ECD->setType(NewTy);
3055 }
Chris Lattner206754a2007-08-28 06:15:15 +00003056
Chris Lattner90a018d2007-08-28 18:24:31 +00003057 Enum->defineElements(EltList, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003058 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003059}
3060
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003061Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3062 ExprTy *expr) {
3063 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3064
Chris Lattner81db64a2008-03-16 00:16:02 +00003065 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003066}
3067
Chris Lattner806a5f52008-01-12 07:05:38 +00003068Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattner43b885f2008-02-25 21:04:36 +00003069 SourceLocation LBrace,
3070 SourceLocation RBrace,
3071 const char *Lang,
3072 unsigned StrSize,
3073 DeclTy *D) {
Chris Lattner806a5f52008-01-12 07:05:38 +00003074 LinkageSpecDecl::LanguageIDs Language;
3075 Decl *dcl = static_cast<Decl *>(D);
3076 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3077 Language = LinkageSpecDecl::lang_c;
3078 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3079 Language = LinkageSpecDecl::lang_cxx;
3080 else {
3081 Diag(Loc, diag::err_bad_language);
3082 return 0;
3083 }
3084
3085 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner81db64a2008-03-16 00:16:02 +00003086 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattner806a5f52008-01-12 07:05:38 +00003087}
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003088
3089void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3090 ExprTy *alignment, SourceLocation PragmaLoc,
3091 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3092 Expr *Alignment = static_cast<Expr *>(alignment);
3093
3094 // If specified then alignment must be a "small" power of two.
3095 unsigned AlignmentVal = 0;
3096 if (Alignment) {
3097 llvm::APSInt Val;
3098 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3099 !Val.isPowerOf2() ||
3100 Val.getZExtValue() > 16) {
3101 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3102 delete Alignment;
3103 return; // Ignore
3104 }
3105
3106 AlignmentVal = (unsigned) Val.getZExtValue();
3107 }
3108
3109 switch (Kind) {
3110 case Action::PPK_Default: // pack([n])
3111 PackContext.setAlignment(AlignmentVal);
3112 break;
3113
3114 case Action::PPK_Show: // pack(show)
3115 // Show the current alignment, making sure to show the right value
3116 // for the default.
3117 AlignmentVal = PackContext.getAlignment();
3118 // FIXME: This should come from the target.
3119 if (AlignmentVal == 0)
3120 AlignmentVal = 8;
3121 Diag(PragmaLoc, diag::warn_pragma_pack_show, llvm::utostr(AlignmentVal));
3122 break;
3123
3124 case Action::PPK_Push: // pack(push [, id] [, [n])
3125 PackContext.push(Name);
3126 // Set the new alignment if specified.
3127 if (Alignment)
3128 PackContext.setAlignment(AlignmentVal);
3129 break;
3130
3131 case Action::PPK_Pop: // pack(pop [, id] [, n])
3132 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3133 // "#pragma pack(pop, identifier, n) is undefined"
3134 if (Alignment && Name)
3135 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3136
3137 // Do the pop.
3138 if (!PackContext.pop(Name)) {
3139 // If a name was specified then failure indicates the name
3140 // wasn't found. Otherwise failure indicates the stack was
3141 // empty.
3142 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3143 Name ? "no record matching name" : "stack empty");
3144
3145 // FIXME: Warn about popping named records as MSVC does.
3146 } else {
3147 // Pop succeeded, set the new alignment if specified.
3148 if (Alignment)
3149 PackContext.setAlignment(AlignmentVal);
3150 }
3151 break;
3152
3153 default:
3154 assert(0 && "Invalid #pragma pack kind.");
3155 }
3156}
3157
3158bool PragmaPackStack::pop(IdentifierInfo *Name) {
3159 if (Stack.empty())
3160 return false;
3161
3162 // If name is empty just pop top.
3163 if (!Name) {
3164 Alignment = Stack.back().first;
3165 Stack.pop_back();
3166 return true;
3167 }
3168
3169 // Otherwise, find the named record.
3170 for (unsigned i = Stack.size(); i != 0; ) {
3171 --i;
3172 if (strcmp(Stack[i].second.c_str(), Name->getName()) == 0) {
3173 // Found it, pop up to and including this record.
3174 Alignment = Stack[i].first;
3175 Stack.erase(Stack.begin() + i, Stack.end());
3176 return true;
3177 }
3178 }
3179
3180 return false;
3181}