blob: 9126e5c02466eece9206047fbbb7514697682611 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc44eec62008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattnere1e79852008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbarc4a1dea2008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6b6b5372008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbare4858a62008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattnere1e79852008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroff4c49a6c2008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000027#include "llvm/ADT/SmallSet.h"
28using namespace clang;
29
Douglas Gregor2def4832008-11-17 20:34:05 +000030Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000031 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000032 DeclContext *DC = 0;
33 if (SS) {
34 if (SS->isInvalid())
35 return 0;
36 DC = static_cast<DeclContext*>(SS->getScopeRep());
37 }
38 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000039
Douglas Gregor2ce52f32008-04-13 21:07:44 +000040 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
41 isa<ObjCInterfaceDecl>(IIDecl) ||
42 isa<TagDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000043 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000044 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000045}
46
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000047DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000048 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000049 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000050 if (MD->isOutOfLineDefinition())
51 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052
53 // A C++ inline method is parsed *after* the topmost class it was declared in
54 // is fully parsed (it's "complete").
55 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000056 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000057 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
58 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000059 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000060 DC = RD;
61
62 // Return the declaration context of the topmost class the inline method is
63 // declared in.
64 return DC;
65 }
66
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000067 if (isa<ObjCMethodDecl>(DC))
68 return Context.getTranslationUnitDecl();
69
70 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
71 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000072
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000073 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000074}
75
Chris Lattner9fdf9c62008-04-22 18:39:57 +000076void Sema::PushDeclContext(DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000077 assert(getContainingDC(DC) == CurContext &&
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000078 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000079 CurContext = DC;
Chris Lattner0ed844b2008-04-04 06:12:32 +000080}
81
Chris Lattnerb048c982008-04-06 04:47:34 +000082void Sema::PopDeclContext() {
83 assert(CurContext && "DeclContext imbalance!");
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000084 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000085}
86
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000087/// Add this decl to the scope shadowed decl chains.
88void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000089 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000090
91 // C++ [basic.scope]p4:
92 // -- exactly one declaration shall declare a class name or
93 // enumeration name that is not a typedef name and the other
94 // declarations shall all refer to the same object or
95 // enumerator, or all refer to functions and function templates;
96 // in this case the class name or enumeration name is hidden.
97 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
98 // We are pushing the name of a tag (enum or class).
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +000099 IdentifierResolver::iterator
100 I = IdResolver.begin(TD->getIdentifier(),
101 TD->getDeclContext(), false/*LookInParentCtx*/);
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000102 if (I != IdResolver.end() && isDeclInScope(*I, TD->getDeclContext(), S)) {
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000103 // There is already a declaration with the same name in the same
104 // scope. It must be found before we find the new declaration,
105 // so swap the order on the shadowed declaration chain.
106
Argyrios Kyrtzidis90eb5392008-07-17 17:49:50 +0000107 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000108 return;
109 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000110 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
111 FunctionDecl *FD = cast<FunctionDecl>(D);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000112 // We are pushing the name of a function, which might be an
113 // overloaded name.
114 IdentifierResolver::iterator
Douglas Gregor2def4832008-11-17 20:34:05 +0000115 I = IdResolver.begin(FD->getDeclName(),
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000116 FD->getDeclContext(), false/*LookInParentCtx*/);
117 if (I != IdResolver.end() &&
118 IdResolver.isDeclInScope(*I, FD->getDeclContext(), S) &&
119 (isa<OverloadedFunctionDecl>(*I) || isa<FunctionDecl>(*I))) {
120 // There is already a declaration with the same name in the same
121 // scope. It must be a function or an overloaded function.
122 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(*I);
123 if (!Ovl) {
124 // We haven't yet overloaded this function. Take the existing
125 // FunctionDecl and put it into an OverloadedFunctionDecl.
126 Ovl = OverloadedFunctionDecl::Create(Context,
127 FD->getDeclContext(),
Douglas Gregor2def4832008-11-17 20:34:05 +0000128 FD->getDeclName());
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000129 Ovl->addOverload(dyn_cast<FunctionDecl>(*I));
130
131 // Remove the name binding to the existing FunctionDecl...
132 IdResolver.RemoveDecl(*I);
133
134 // ... and put the OverloadedFunctionDecl in its place.
135 IdResolver.AddDecl(Ovl);
136 }
137
138 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
139 // to its list of overloads.
140 Ovl->addOverload(FD);
141
142 return;
143 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000144 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000145
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000146 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000147}
148
Steve Naroffb216c882007-10-09 22:01:59 +0000149void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000150 if (S->decl_empty()) return;
151 assert((S->getFlags() & Scope::DeclScope) &&"Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000152
Reid Spencer5f016e22007-07-11 17:01:13 +0000153 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
154 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000155 Decl *TmpD = static_cast<Decl*>(*I);
156 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000157
158 if (isa<CXXFieldDecl>(TmpD)) continue;
159
160 assert(isa<ScopedDecl>(TmpD) && "Decl isn't ScopedDecl?");
161 ScopedDecl *D = cast<ScopedDecl>(TmpD);
Steve Naroffc752d042007-09-13 18:10:37 +0000162
Reid Spencer5f016e22007-07-11 17:01:13 +0000163 IdentifierInfo *II = D->getIdentifier();
164 if (!II) continue;
165
Ted Kremeneka89d1972008-09-03 18:03:35 +0000166 // We only want to remove the decls from the identifier decl chains for
167 // local scopes, when inside a function/method.
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000168 if (S->getFnParent() != 0)
169 IdResolver.RemoveDecl(D);
Chris Lattner7f925cc2008-04-11 07:00:53 +0000170
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000171 // Chain this decl to the containing DeclContext.
172 D->setNext(CurContext->getDeclChain());
173 CurContext->setDeclChain(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 }
175}
176
Steve Naroffe8043c32008-04-01 23:04:06 +0000177/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
178/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000179ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000180 // The third "scope" argument is 0 since we aren't enabling lazy built-in
181 // creation from this context.
182 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000183
Steve Naroffb327ce02008-04-02 14:35:35 +0000184 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000185}
186
Steve Naroffe8043c32008-04-01 23:04:06 +0000187/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000188/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000189Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000190 const DeclContext *LookupCtx,
191 bool enableLazyBuiltinCreation) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000192 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000193 unsigned NS = NSI;
194 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
195 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000196
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000197 IdentifierResolver::iterator
Douglas Gregor2def4832008-11-17 20:34:05 +0000198 I = LookupCtx ? IdResolver.begin(Name, LookupCtx, false/*LookInParentCtx*/)
199 : IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/);
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 // Scan up the scope chain looking for a decl that matches this identifier
201 // that is in the appropriate namespace. This search should not take long, as
202 // shadowing of names is uncommon, and deep shadowing is extremely uncommon.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000203 for (; I != IdResolver.end(); ++I)
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000204 if ((*I)->getIdentifierNamespace() & NS)
205 return *I;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000206
Reid Spencer5f016e22007-07-11 17:01:13 +0000207 // If we didn't find a use of this identifier, and if the identifier
208 // corresponds to a compiler builtin, create the decl object for the builtin
209 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000210 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000211 IdentifierInfo *II = Name.getAsIdentifierInfo();
212 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000213 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000214 // If this is a builtin on this (or all) targets, create the decl.
215 if (unsigned BuiltinID = II->getBuiltinID())
216 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
217 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000218 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000219 // @interface and @compatibility_alias introduce typedef-like names.
220 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000221 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000222 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000223 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
224 if (IDI != ObjCInterfaceDecls.end())
225 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000226 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
227 if (I != ObjCAliasDecls.end())
228 return I->second->getClassInterface();
229 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000230 }
231 return 0;
232}
233
Chris Lattner95e2c712008-05-05 22:18:14 +0000234void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000235 if (!Context.getBuiltinVaListType().isNull())
236 return;
237
238 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000239 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000240 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000241 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
242}
243
Reid Spencer5f016e22007-07-11 17:01:13 +0000244/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
245/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000246ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
247 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000248 Builtin::ID BID = (Builtin::ID)bid;
249
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000250 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000251 InitBuiltinVaListType();
252
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000253 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000254 FunctionDecl *New = FunctionDecl::Create(Context,
255 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000256 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000257 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000258
Chris Lattner95e2c712008-05-05 22:18:14 +0000259 // Create Decl objects for each parameter, adding them to the
260 // FunctionDecl.
261 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
262 llvm::SmallVector<ParmVarDecl*, 16> Params;
263 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
264 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
265 FT->getArgType(i), VarDecl::None, 0,
266 0));
267 New->setParams(&Params[0], Params.size());
268 }
269
270
271
Chris Lattner7f925cc2008-04-11 07:00:53 +0000272 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000273 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000274 return New;
275}
276
Sebastian Redlc42e1182008-11-11 11:37:55 +0000277/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
278/// everything from the standard library is defined.
279NamespaceDecl *Sema::GetStdNamespace() {
280 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000281 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000282 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000283 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000284 0, Global, /*enableLazyBuiltinCreation=*/false);
285 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
286 }
287 return StdNamespace;
288}
289
Reid Spencer5f016e22007-07-11 17:01:13 +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 Naroffe8043c32008-04-01 23:04:06 +0000294TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-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) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000298 const IdentifierInfo *TypeID = New->getIdentifier();
299 switch (TypeID->getLength()) {
300 default: break;
301 case 2:
302 if (!TypeID->isStr("id"))
303 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000304 Context.setObjCIdType(New);
305 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000306 case 5:
307 if (!TypeID->isStr("Class"))
308 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000309 Context.setObjCClassType(New);
310 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000311 case 3:
312 if (!TypeID->isStr("SEL"))
313 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000314 Context.setObjCSelType(New);
315 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000316 case 8:
317 if (!TypeID->isStr("Protocol"))
318 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000319 Context.setObjCProtoType(New->getUnderlyingType());
320 return New;
321 }
322 // Fall through - the typedef name was not a builtin type.
323 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000324 // Verify the old decl was also a typedef.
325 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
326 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000327 Diag(New->getLocation(), diag::err_redefinition_different_kind)
328 << New->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000329 Diag(OldD->getLocation(), diag::err_previous_definition);
330 return New;
331 }
332
Chris Lattner99cb9972008-07-25 18:44:27 +0000333 // If the typedef types are not identical, reject them in all languages and
334 // with any extensions enabled.
335 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
336 Context.getCanonicalType(Old->getUnderlyingType()) !=
337 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000338 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
339 << New->getUnderlyingType().getAsString()
340 << Old->getUnderlyingType().getAsString();
Chris Lattner99cb9972008-07-25 18:44:27 +0000341 Diag(Old->getLocation(), diag::err_previous_definition);
342 return Old;
343 }
344
Eli Friedman54ecfce2008-06-11 06:20:39 +0000345 if (getLangOptions().Microsoft) return New;
346
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000347 // Redeclaration of a type is a constraint violation (6.7.2.3p1).
348 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
349 // *either* declaration is in a system header. The code below implements
350 // this adhoc compatibility rule. FIXME: The following code will not
351 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000352 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
353 SourceManager &SrcMgr = Context.getSourceManager();
354 if (SrcMgr.isInSystemHeader(Old->getLocation()))
355 return New;
356 if (SrcMgr.isInSystemHeader(New->getLocation()))
357 return New;
358 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000359
Chris Lattner5dc266a2008-11-20 06:13:02 +0000360 Diag(New->getLocation(), diag::err_redefinition) << New->getName();
Ted Kremenek2d05c082008-05-23 21:28:18 +0000361 Diag(Old->getLocation(), diag::err_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000362 return New;
363}
364
Chris Lattner6b6b5372008-06-26 18:38:35 +0000365/// DeclhasAttr - returns true if decl Declaration already has the target
366/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000367static bool DeclHasAttr(const Decl *decl, const Attr *target) {
368 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
369 if (attr->getKind() == target->getKind())
370 return true;
371
372 return false;
373}
374
375/// MergeAttributes - append attributes from the Old decl to the New one.
376static void MergeAttributes(Decl *New, Decl *Old) {
377 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
378
Chris Lattnerddee4232008-03-03 03:28:21 +0000379 while (attr) {
380 tmp = attr;
381 attr = attr->getNext();
382
383 if (!DeclHasAttr(New, tmp)) {
384 New->addAttr(tmp);
385 } else {
386 tmp->setNext(0);
387 delete(tmp);
388 }
389 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000390
391 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000392}
393
Chris Lattner04421082008-04-08 04:40:51 +0000394/// MergeFunctionDecl - We just parsed a function 'New' from
395/// declarator D which has the same name and scope as a previous
396/// declaration 'Old'. Figure out how to resolve this situation,
397/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000398/// Redeclaration will be set true if this New is a redeclaration OldD.
399///
400/// In C++, New and Old must be declarations that are not
401/// overloaded. Use IsOverload to determine whether New and Old are
402/// overloaded, and to select the Old declaration that New should be
403/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000404FunctionDecl *
405Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000406 assert(!isa<OverloadedFunctionDecl>(OldD) &&
407 "Cannot merge with an overloaded function declaration");
408
Douglas Gregorf0097952008-04-21 02:02:58 +0000409 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 // Verify the old decl was also a function.
411 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
412 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000413 Diag(New->getLocation(), diag::err_redefinition_different_kind)
414 << New->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 Diag(OldD->getLocation(), diag::err_previous_definition);
416 return New;
417 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000418
419 // Determine whether the previous declaration was a definition,
420 // implicit declaration, or a declaration.
421 diag::kind PrevDiag;
422 if (Old->isThisDeclarationADefinition())
423 PrevDiag = diag::err_previous_definition;
424 else if (Old->isImplicit())
425 PrevDiag = diag::err_previous_implicit_declaration;
426 else
427 PrevDiag = diag::err_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000428
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000429 QualType OldQType = Context.getCanonicalType(Old->getType());
430 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000431
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000432 if (getLangOptions().CPlusPlus) {
433 // (C++98 13.1p2):
434 // Certain function declarations cannot be overloaded:
435 // -- Function declarations that differ only in the return type
436 // cannot be overloaded.
437 QualType OldReturnType
438 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
439 QualType NewReturnType
440 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
441 if (OldReturnType != NewReturnType) {
442 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
443 Diag(Old->getLocation(), PrevDiag);
444 return New;
445 }
446
447 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
448 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
449 if (OldMethod && NewMethod) {
450 // -- Member function declarations with the same name and the
451 // same parameter types cannot be overloaded if any of them
452 // is a static member function declaration.
453 if (OldMethod->isStatic() || NewMethod->isStatic()) {
454 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
455 Diag(Old->getLocation(), PrevDiag);
456 return New;
457 }
458 }
459
460 // (C++98 8.3.5p3):
461 // All declarations for a function shall agree exactly in both the
462 // return type and the parameter-type-list.
463 if (OldQType == NewQType) {
464 // We have a redeclaration.
465 MergeAttributes(New, Old);
466 Redeclaration = true;
467 return MergeCXXFunctionDecl(New, Old);
468 }
469
470 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000471 }
Chris Lattner04421082008-04-08 04:40:51 +0000472
473 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000474 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000475 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000476 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000477 MergeAttributes(New, Old);
478 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000479 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000480 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000481
Steve Naroff837618c2008-01-16 15:01:34 +0000482 // A function that has already been declared has been redeclared or defined
483 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000484
Reid Spencer5f016e22007-07-11 17:01:13 +0000485 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
486 // TODO: This is totally simplistic. It should handle merging functions
487 // together etc, merging extern int X; int X; ...
Chris Lattner5dc266a2008-11-20 06:13:02 +0000488 Diag(New->getLocation(), diag::err_conflicting_types) << New->getName();
Steve Naroff837618c2008-01-16 15:01:34 +0000489 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 return New;
491}
492
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000493/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000494static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000495 if (VD->isFileVarDecl())
496 return (!VD->getInit() &&
497 (VD->getStorageClass() == VarDecl::None ||
498 VD->getStorageClass() == VarDecl::Static));
499 return false;
500}
501
502/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
503/// when dealing with C "tentative" external object definitions (C99 6.9.2).
504void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
505 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000506 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000507
508 for (IdentifierResolver::iterator
509 I = IdResolver.begin(VD->getIdentifier(),
510 VD->getDeclContext(), false/*LookInParentCtx*/),
511 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000512 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000513 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
514
Steve Narofff855e6f2008-08-10 15:20:13 +0000515 // Handle the following case:
516 // int a[10];
517 // int a[]; - the code below makes sure we set the correct type.
518 // int a[11]; - this is an error, size isn't 10.
519 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
520 OldDecl->getType()->isConstantArrayType())
521 VD->setType(OldDecl->getType());
522
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000523 // Check for "tentative" definitions. We can't accomplish this in
524 // MergeVarDecl since the initializer hasn't been attached.
525 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
526 continue;
527
528 // Handle __private_extern__ just like extern.
529 if (OldDecl->getStorageClass() != VarDecl::Extern &&
530 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
531 VD->getStorageClass() != VarDecl::Extern &&
532 VD->getStorageClass() != VarDecl::PrivateExtern) {
533 Diag(VD->getLocation(), diag::err_redefinition, VD->getName());
534 Diag(OldDecl->getLocation(), diag::err_previous_definition);
535 }
536 }
537 }
538}
539
Reid Spencer5f016e22007-07-11 17:01:13 +0000540/// MergeVarDecl - We just parsed a variable 'New' which has the same name
541/// and scope as a previous declaration 'Old'. Figure out how to resolve this
542/// situation, merging decls or emitting diagnostics as appropriate.
543///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000544/// Tentative definition rules (C99 6.9.2p2) are checked by
545/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
546/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000547///
Steve Naroffe8043c32008-04-01 23:04:06 +0000548VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 // Verify the old decl was also a variable.
550 VarDecl *Old = dyn_cast<VarDecl>(OldD);
551 if (!Old) {
552 Diag(New->getLocation(), diag::err_redefinition_different_kind,
553 New->getName());
554 Diag(OldD->getLocation(), diag::err_previous_definition);
555 return New;
556 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000557
558 MergeAttributes(New, Old);
559
Reid Spencer5f016e22007-07-11 17:01:13 +0000560 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000561 QualType OldCType = Context.getCanonicalType(Old->getType());
562 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000563 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000564 Diag(New->getLocation(), diag::err_redefinition, New->getName());
565 Diag(Old->getLocation(), diag::err_previous_definition);
566 return New;
567 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000568 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
569 if (New->getStorageClass() == VarDecl::Static &&
570 (Old->getStorageClass() == VarDecl::None ||
571 Old->getStorageClass() == VarDecl::Extern)) {
572 Diag(New->getLocation(), diag::err_static_non_static, New->getName());
573 Diag(Old->getLocation(), diag::err_previous_definition);
574 return New;
575 }
576 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
577 if (New->getStorageClass() != VarDecl::Static &&
578 Old->getStorageClass() == VarDecl::Static) {
579 Diag(New->getLocation(), diag::err_non_static_static, New->getName());
580 Diag(Old->getLocation(), diag::err_previous_definition);
581 return New;
582 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000583 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
584 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000585 Diag(New->getLocation(), diag::err_redefinition, New->getName());
586 Diag(Old->getLocation(), diag::err_previous_definition);
587 }
588 return New;
589}
590
Chris Lattner04421082008-04-08 04:40:51 +0000591/// CheckParmsForFunctionDef - Check that the parameters of the given
592/// function are appropriate for the definition of a function. This
593/// takes care of any checks that cannot be performed on the
594/// declaration itself, e.g., that the types of each of the function
595/// parameters are complete.
596bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
597 bool HasInvalidParm = false;
598 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
599 ParmVarDecl *Param = FD->getParamDecl(p);
600
601 // C99 6.7.5.3p4: the parameters in a parameter type list in a
602 // function declarator that is part of a function definition of
603 // that function shall not have incomplete type.
604 if (Param->getType()->isIncompleteType() &&
605 !Param->isInvalidDecl()) {
606 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type,
607 Param->getType().getAsString());
608 Param->setInvalidDecl();
609 HasInvalidParm = true;
610 }
611 }
612
613 return HasInvalidParm;
614}
615
Reid Spencer5f016e22007-07-11 17:01:13 +0000616/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
617/// no declarator (e.g. "struct foo;") is parsed.
618Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
619 // TODO: emit error on 'int;' or 'const enum foo;'.
620 // TODO: emit error on 'typedef int;'
621 // if (!DS.isMissingDeclaratorOk()) Diag(...);
622
Steve Naroff92199282007-11-17 21:37:36 +0000623 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000624}
625
Steve Naroffd0091aa2008-01-10 22:15:12 +0000626bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000627 // Get the type before calling CheckSingleAssignmentConstraints(), since
628 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000629 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000630
Chris Lattner5cf216b2008-01-04 18:04:52 +0000631 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
632 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
633 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000634}
635
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000636bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000637 const ArrayType *AT = Context.getAsArrayType(DeclT);
638
639 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000640 // C99 6.7.8p14. We have an array of character type with unknown size
641 // being initialized to a string literal.
642 llvm::APSInt ConstVal(32);
643 ConstVal = strLiteral->getByteLength() + 1;
644 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000645 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000646 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000647 } else {
648 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000649 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000650 // FIXME: Avoid truncation for 64-bit length strings.
651 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000652 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000653 diag::warn_initializer_string_for_char_array_too_long)
654 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000655 }
656 // Set type from "char *" to "constant array of char".
657 strLiteral->setType(DeclT);
658 // For now, we always return false (meaning success).
659 return false;
660}
661
662StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000663 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000664 if (AT && AT->getElementType()->isCharType()) {
665 return dyn_cast<StringLiteral>(Init);
666 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000667 return 0;
668}
669
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000670bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
671 SourceLocation InitLoc,
672 std::string InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000673 // C++ [dcl.init.ref]p1:
674 // A variable declared to be a T&, that is “reference to type T”
675 // (8.3.2), shall be initialized by an object, or function, of
676 // type T or by an object that can be converted into a T.
677 if (DeclType->isReferenceType())
678 return CheckReferenceInit(Init, DeclType);
679
Steve Naroffca107302008-01-21 23:53:58 +0000680 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
681 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000682 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000683 return Diag(InitLoc, diag::err_variable_object_no_init)
684 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000685
Steve Naroff2fdc3742007-12-10 22:44:33 +0000686 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
687 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000688 // FIXME: Handle wide strings
689 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
690 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000691
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000692 // C++ [dcl.init]p14:
693 // -- If the destination type is a (possibly cv-qualified) class
694 // type:
695 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
696 QualType DeclTypeC = Context.getCanonicalType(DeclType);
697 QualType InitTypeC = Context.getCanonicalType(Init->getType());
698
699 // -- If the initialization is direct-initialization, or if it is
700 // copy-initialization where the cv-unqualified version of the
701 // source type is the same class as, or a derived class of, the
702 // class of the destination, constructors are considered.
703 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
704 IsDerivedFrom(InitTypeC, DeclTypeC)) {
705 CXXConstructorDecl *Constructor
706 = PerformInitializationByConstructor(DeclType, &Init, 1,
707 InitLoc, Init->getSourceRange(),
708 InitEntity, IK_Copy);
709 return Constructor == 0;
710 }
711
712 // -- Otherwise (i.e., for the remaining copy-initialization
713 // cases), user-defined conversion sequences that can
714 // convert from the source type to the destination type or
715 // (when a conversion function is used) to a derived class
716 // thereof are enumerated as described in 13.3.1.4, and the
717 // best one is chosen through overload resolution
718 // (13.3). If the conversion cannot be done or is
719 // ambiguous, the initialization is ill-formed. The
720 // function selected is called with the initializer
721 // expression as its argument; if the function is a
722 // constructor, the call initializes a temporary of the
723 // destination type.
724 // FIXME: We're pretending to do copy elision here; return to
725 // this when we have ASTs for such things.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000726 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000727 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000728
729 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
730 << DeclType.getAsString() << InitEntity << "initializing"
731 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000732 }
733
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000734 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000735 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000736 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
737 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000738
Steve Naroffd0091aa2008-01-10 22:15:12 +0000739 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000740 } else if (getLangOptions().CPlusPlus) {
741 // C++ [dcl.init]p14:
742 // [...] If the class is an aggregate (8.5.1), and the initializer
743 // is a brace-enclosed list, see 8.5.1.
744 //
745 // Note: 8.5.1 is handled below; here, we diagnose the case where
746 // we have an initializer list and a destination type that is not
747 // an aggregate.
748 // FIXME: In C++0x, this is yet another form of initialization.
749 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
750 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
751 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000752 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
753 << DeclType.getAsString() << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000754 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000755 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000756
Steve Naroff0cca7492008-05-01 22:18:59 +0000757 InitListChecker CheckInitList(this, InitList, DeclType);
758 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000759}
760
Douglas Gregor10bd3682008-11-17 22:58:34 +0000761/// GetNameForDeclarator - Determine the full declaration name for the
762/// given Declarator.
763DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
764 switch (D.getKind()) {
765 case Declarator::DK_Abstract:
766 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
767 return DeclarationName();
768
769 case Declarator::DK_Normal:
770 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
771 return DeclarationName(D.getIdentifier());
772
773 case Declarator::DK_Constructor: {
774 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
775 Ty = Context.getCanonicalType(Ty);
776 return Context.DeclarationNames.getCXXConstructorName(Ty);
777 }
778
779 case Declarator::DK_Destructor: {
780 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
781 Ty = Context.getCanonicalType(Ty);
782 return Context.DeclarationNames.getCXXDestructorName(Ty);
783 }
784
785 case Declarator::DK_Conversion: {
786 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
787 Ty = Context.getCanonicalType(Ty);
788 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
789 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000790
791 case Declarator::DK_Operator:
792 assert(D.getIdentifier() == 0 && "operator names have no identifier");
793 return Context.DeclarationNames.getCXXOperatorName(
794 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000795 }
796
797 assert(false && "Unknown name kind");
798 return DeclarationName();
799}
800
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000801Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000802Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000803 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000804 DeclarationName Name = GetNameForDeclarator(D);
805
Chris Lattnere80a59c2007-07-25 00:24:17 +0000806 // All of these full declarators require an identifier. If it doesn't have
807 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000808 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000809 if (!D.getInvalidType()) // Reject this if we think it is valid.
810 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000811 diag::err_declarator_need_ident)
812 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000813 return 0;
814 }
815
Chris Lattner31e05722007-08-26 06:24:45 +0000816 // The scope passed in may not be a decl scope. Zip up the scope tree until
817 // we find one that is.
818 while ((S->getFlags() & Scope::DeclScope) == 0)
819 S = S->getParent();
820
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000821 DeclContext *DC;
822 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000823 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000824 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000825
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000826 // See if this is a redefinition of a variable in the same scope.
827 if (!D.getCXXScopeSpec().isSet()) {
828 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +0000829 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000830 } else { // Something like "int foo::x;"
831 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000832 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000833
834 // C++ 7.3.1.2p2:
835 // Members (including explicit specializations of templates) of a named
836 // namespace can also be defined outside that namespace by explicit
837 // qualification of the name being defined, provided that the entity being
838 // defined was already declared in the namespace and the definition appears
839 // after the point of declaration in a namespace that encloses the
840 // declarations namespace.
841 //
842 if (PrevDecl == 0) {
843 // No previous declaration in the qualifying scope.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000844 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
845 << Name.getAsString() << D.getCXXScopeSpec().getRange();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000846 } else if (!CurContext->Encloses(DC)) {
847 // The qualifying scope doesn't enclose the original declaration.
848 // Emit diagnostic based on current scope.
849 SourceLocation L = D.getIdentifierLoc();
850 SourceRange R = D.getCXXScopeSpec().getRange();
851 if (isa<FunctionDecl>(CurContext)) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000852 Diag(L, diag::err_invalid_declarator_in_function)
853 << Name.getAsString() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000854 } else {
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000855 Diag(L, diag::err_invalid_declarator_scope)
856 << Name.getAsString() << cast<NamedDecl>(DC)->getName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000857 }
858 }
859 }
860
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000861 // In C++, the previous declaration we find might be a tag type
862 // (class or enum). In this case, the new declaration will hide the
863 // tag type.
864 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
865 PrevDecl = 0;
866
Chris Lattner41af0932007-11-14 06:34:38 +0000867 QualType R = GetTypeForDeclarator(D, S);
868 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
869
Reid Spencer5f016e22007-07-11 17:01:13 +0000870 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000871 // Check that there are no default arguments (C++ only).
872 if (getLangOptions().CPlusPlus)
873 CheckExtraCXXDefaultArguments(D);
874
Chris Lattner41af0932007-11-14 06:34:38 +0000875 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000876 if (!NewTD) return 0;
877
878 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000879 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000880 // Merge the decl with the existing one if appropriate. If the decl is
881 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000882 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000883 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
884 if (NewTD == 0) return 0;
885 }
886 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000887 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000888 // C99 6.7.7p2: If a typedef name specifies a variably modified type
889 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000890 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
891 // FIXME: Diagnostic needs to be fixed.
892 Diag(D.getIdentifierLoc(), diag::err_typecheck_illegal_vla);
Steve Naroffd7444aa2007-08-31 17:20:07 +0000893 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000894 }
895 }
Chris Lattner41af0932007-11-14 06:34:38 +0000896 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +0000897 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +0000898 switch (D.getDeclSpec().getStorageClassSpec()) {
899 default: assert(0 && "Unknown storage class!");
900 case DeclSpec::SCS_auto:
901 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +0000902 case DeclSpec::SCS_mutable:
Reid Spencer5f016e22007-07-11 17:01:13 +0000903 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func,
904 R.getAsString());
Steve Naroff5912a352007-08-28 20:14:24 +0000905 InvalidDecl = true;
906 break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000907 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
908 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
909 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +0000910 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +0000911 }
912
Chris Lattnera98e58d2008-03-15 21:24:04 +0000913 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +0000914 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +0000915 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
916
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000917 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +0000918 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +0000919 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000920 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +0000921 "Constructors can only be declared in a member context");
922
Douglas Gregor42a552f2008-11-05 20:51:48 +0000923 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +0000924
925 // Create the new declaration
926 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000927 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000928 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +0000929 isExplicit, isInline,
930 /*isImplicitlyDeclared=*/false);
931
Douglas Gregor42a552f2008-11-05 20:51:48 +0000932 if (isInvalidDecl)
933 NewFD->setInvalidDecl();
934 } else if (D.getKind() == Declarator::DK_Destructor) {
935 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000936 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000937 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000938
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000939 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000940 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000941 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000942 isInline,
943 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +0000944
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000945 if (isInvalidDecl)
946 NewFD->setInvalidDecl();
947 } else {
948 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
949 // Create a FunctionDecl to satisfy the function definition parsing
950 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000951 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000952 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000953 // FIXME: Move to DeclGroup...
954 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +0000955 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +0000956 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000957 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000958 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000959 Diag(D.getIdentifierLoc(),
960 diag::err_conv_function_not_member);
961 return 0;
962 } else {
963 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
964
965 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000966 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000967 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +0000968 isInline, isExplicit);
969
970 if (isInvalidDecl)
971 NewFD->setInvalidDecl();
972 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000973 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000974 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000975 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000976 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000977 (SC == FunctionDecl::Static), isInline,
978 LastDeclarator);
979 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000980 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000981 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +0000982 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +0000983 // FIXME: Move to DeclGroup...
984 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +0000985 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +0000986 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +0000987 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +0000988
Daniel Dunbara80f8742008-08-05 01:35:17 +0000989 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +0000990 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +0000991 // The parser guarantees this is a string.
992 StringLiteral *SE = cast<StringLiteral>(E);
993 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
994 SE->getByteLength())));
995 }
996
Chris Lattner04421082008-04-08 04:40:51 +0000997 // Copy the parameter declarations from the declarator D to
998 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +0000999 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001000 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1001
1002 // Create Decl objects for each parameter, adding them to the
1003 // FunctionDecl.
1004 llvm::SmallVector<ParmVarDecl*, 16> Params;
1005
1006 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1007 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001008 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001009 // We let through "const void" here because Sema::GetTypeForDeclarator
1010 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001011 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1012 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001013 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1014 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001015 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1016
Chris Lattnerdef026a2008-04-10 02:26:16 +00001017 // In C++, the empty parameter-type-list must be spelled "void"; a
1018 // typedef of void is not permitted.
1019 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001020 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001021 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1022 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001023 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001024 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1025 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1026 }
1027
1028 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001029 } else if (R->getAsTypedefType()) {
1030 // When we're declaring a function with a typedef, as in the
1031 // following example, we'll need to synthesize (unnamed)
1032 // parameters for use in the declaration.
1033 //
1034 // @code
1035 // typedef void fn(int);
1036 // fn f;
1037 // @endcode
1038 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1039 if (!FT) {
1040 // This is a typedef of a function with no prototype, so we
1041 // don't need to do anything.
1042 } else if ((FT->getNumArgs() == 0) ||
1043 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1044 FT->getArgType(0)->isVoidType())) {
1045 // This is a zero-argument function. We don't need to do anything.
1046 } else {
1047 // Synthesize a parameter for each argument type.
1048 llvm::SmallVector<ParmVarDecl*, 16> Params;
1049 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1050 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001051 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001052 SourceLocation(), 0,
1053 *ArgType, VarDecl::None,
1054 0, 0));
1055 }
1056
1057 NewFD->setParams(&Params[0], Params.size());
1058 }
Chris Lattner04421082008-04-08 04:40:51 +00001059 }
1060
Douglas Gregor42a552f2008-11-05 20:51:48 +00001061 // C++ constructors and destructors are handled by separate
1062 // routines, since they don't require any declaration merging (C++
1063 // [class.mfct]p2) and they aren't ever pushed into scope, because
1064 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1065 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1066 return ActOnConstructorDeclarator(Constructor);
1067 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1068 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2def4832008-11-17 20:34:05 +00001069
1070 // Extra checking for conversion functions, including recording
1071 // the conversion function in its class.
1072 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1073 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001074
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001075 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1076 if (NewFD->isOverloadedOperator() &&
1077 CheckOverloadedOperatorDeclaration(NewFD))
1078 NewFD->setInvalidDecl();
1079
Steve Naroffffce4d52008-01-09 23:34:55 +00001080 // Merge the decl with the existing one if appropriate. Since C functions
1081 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001082 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001083 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001084 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001085
1086 // If C++, determine whether NewFD is an overload of PrevDecl or
1087 // a declaration that requires merging. If it's an overload,
1088 // there's no more work to do here; we'll just add the new
1089 // function to the scope.
1090 OverloadedFunctionDecl::function_iterator MatchedDecl;
1091 if (!getLangOptions().CPlusPlus ||
1092 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1093 Decl *OldDecl = PrevDecl;
1094
1095 // If PrevDecl was an overloaded function, extract the
1096 // FunctionDecl that matched.
1097 if (isa<OverloadedFunctionDecl>(PrevDecl))
1098 OldDecl = *MatchedDecl;
1099
1100 // NewFD and PrevDecl represent declarations that need to be
1101 // merged.
1102 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1103
1104 if (NewFD == 0) return 0;
1105 if (Redeclaration) {
1106 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1107
1108 if (OldDecl == PrevDecl) {
1109 // Remove the name binding for the previous
1110 // declaration. We'll add the binding back later, but then
1111 // it will refer to the new declaration (which will
1112 // contain more information).
1113 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1114 } else {
1115 // We need to update the OverloadedFunctionDecl with the
1116 // latest declaration of this function, so that name
1117 // lookup will always refer to the latest declaration of
1118 // this function.
1119 *MatchedDecl = NewFD;
1120
1121 // Add the redeclaration to the current scope, since we'll
1122 // be skipping PushOnScopeChains.
1123 S->AddDecl(NewFD);
1124
1125 return NewFD;
1126 }
1127 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001128 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001129 }
1130 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001131
1132 // In C++, check default arguments now that we have merged decls.
1133 if (getLangOptions().CPlusPlus)
1134 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001135 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001136 // Check that there are no default arguments (C++ only).
1137 if (getLangOptions().CPlusPlus)
1138 CheckExtraCXXDefaultArguments(D);
1139
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001140 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001141 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1142 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001143 InvalidDecl = true;
1144 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001145
1146 VarDecl *NewVD;
1147 VarDecl::StorageClass SC;
1148 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001149 default: assert(0 && "Unknown storage class!");
1150 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1151 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1152 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1153 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1154 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1155 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001156 case DeclSpec::SCS_mutable:
1157 // mutable can only appear on non-static class members, so it's always
1158 // an error here
1159 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1160 InvalidDecl = true;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001161 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001162 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001163
1164 IdentifierInfo *II = Name.getAsIdentifierInfo();
1165 if (!II) {
1166 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name,
1167 Name.getAsString());
1168 return 0;
1169 }
1170
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001171 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001172 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1173 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001174 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001175 D.getIdentifierLoc(), II,
1176 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001177 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001178 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001179 if (S->getFnParent() == 0) {
1180 // C99 6.9p2: The storage-class specifiers auto and register shall not
1181 // appear in the declaration specifiers in an external declaration.
1182 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
1183 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope,
1184 R.getAsString());
1185 InvalidDecl = true;
1186 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001187 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001188 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1189 II, R, SC, LastDeclarator,
1190 // FIXME: Move to DeclGroup...
1191 D.getDeclSpec().getSourceRange().getBegin());
1192 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001193 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001194 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001195 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001196
Daniel Dunbara735ad82008-08-06 00:03:29 +00001197 // Handle GNU asm-label extension (encoded as an attribute).
1198 if (Expr *E = (Expr*) D.getAsmLabel()) {
1199 // The parser guarantees this is a string.
1200 StringLiteral *SE = cast<StringLiteral>(E);
1201 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1202 SE->getByteLength())));
1203 }
1204
Nate Begemanc8e89a82008-03-14 18:07:10 +00001205 // Emit an error if an address space was applied to decl with local storage.
1206 // This includes arrays of objects with address space qualifiers, but not
1207 // automatic variables that point to other address spaces.
1208 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001209 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1210 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1211 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001212 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001213 // Merge the decl with the existing one if appropriate. If the decl is
1214 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001215 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001216 NewVD = MergeVarDecl(NewVD, PrevDecl);
1217 if (NewVD == 0) return 0;
1218 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001219 New = NewVD;
1220 }
1221
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001222 // Set the lexical context. If the declarator has a C++ scope specifier, the
1223 // lexical context will be different from the semantic context.
1224 New->setLexicalDeclContext(CurContext);
1225
Reid Spencer5f016e22007-07-11 17:01:13 +00001226 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001227 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001228 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001229 // If any semantic error occurred, mark the decl as invalid.
1230 if (D.getInvalidType() || InvalidDecl)
1231 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001232
1233 return New;
1234}
1235
Steve Naroff6594a702008-10-27 11:34:16 +00001236void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001237 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1238 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001239}
1240
Eli Friedmanc594b322008-05-20 13:48:25 +00001241bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1242 switch (Init->getStmtClass()) {
1243 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001244 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001245 return true;
1246 case Expr::ParenExprClass: {
1247 const ParenExpr* PE = cast<ParenExpr>(Init);
1248 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1249 }
1250 case Expr::CompoundLiteralExprClass:
1251 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1252 case Expr::DeclRefExprClass: {
1253 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001254 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1255 if (VD->hasGlobalStorage())
1256 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001257 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001258 return true;
1259 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001260 if (isa<FunctionDecl>(D))
1261 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001262 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001263 return true;
1264 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001265 case Expr::MemberExprClass: {
1266 const MemberExpr *M = cast<MemberExpr>(Init);
1267 if (M->isArrow())
1268 return CheckAddressConstantExpression(M->getBase());
1269 return CheckAddressConstantExpressionLValue(M->getBase());
1270 }
1271 case Expr::ArraySubscriptExprClass: {
1272 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1273 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1274 return CheckAddressConstantExpression(ASE->getBase()) ||
1275 CheckArithmeticConstantExpression(ASE->getIdx());
1276 }
1277 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001278 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001279 return false;
1280 case Expr::UnaryOperatorClass: {
1281 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1282
1283 // C99 6.6p9
1284 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001285 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001286
Steve Naroff6594a702008-10-27 11:34:16 +00001287 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001288 return true;
1289 }
1290 }
1291}
1292
1293bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1294 switch (Init->getStmtClass()) {
1295 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001296 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001297 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001298 case Expr::ParenExprClass:
1299 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001300 case Expr::StringLiteralClass:
1301 case Expr::ObjCStringLiteralClass:
1302 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001303 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001304 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001305 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1306 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1307 Builtin::BI__builtin___CFStringMakeConstantString)
1308 return false;
1309
Steve Naroff6594a702008-10-27 11:34:16 +00001310 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001311 return true;
1312
Eli Friedmanc594b322008-05-20 13:48:25 +00001313 case Expr::UnaryOperatorClass: {
1314 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1315
1316 // C99 6.6p9
1317 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1318 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1319
1320 if (Exp->getOpcode() == UnaryOperator::Extension)
1321 return CheckAddressConstantExpression(Exp->getSubExpr());
1322
Steve Naroff6594a702008-10-27 11:34:16 +00001323 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001324 return true;
1325 }
1326 case Expr::BinaryOperatorClass: {
1327 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1328 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1329
1330 Expr *PExp = Exp->getLHS();
1331 Expr *IExp = Exp->getRHS();
1332 if (IExp->getType()->isPointerType())
1333 std::swap(PExp, IExp);
1334
1335 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1336 return CheckAddressConstantExpression(PExp) ||
1337 CheckArithmeticConstantExpression(IExp);
1338 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001339 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001340 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001341 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001342 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1343 // Check for implicit promotion
1344 if (SubExpr->getType()->isFunctionType() ||
1345 SubExpr->getType()->isArrayType())
1346 return CheckAddressConstantExpressionLValue(SubExpr);
1347 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001348
1349 // Check for pointer->pointer cast
1350 if (SubExpr->getType()->isPointerType())
1351 return CheckAddressConstantExpression(SubExpr);
1352
Eli Friedmanc3f07642008-08-25 20:46:57 +00001353 if (SubExpr->getType()->isIntegralType()) {
1354 // Check for the special-case of a pointer->int->pointer cast;
1355 // this isn't standard, but some code requires it. See
1356 // PR2720 for an example.
1357 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1358 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1359 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1360 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1361 if (IntWidth >= PointerWidth) {
1362 return CheckAddressConstantExpression(SubCast->getSubExpr());
1363 }
1364 }
1365 }
1366 }
1367 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001368 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001369 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001370
Steve Naroff6594a702008-10-27 11:34:16 +00001371 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001372 return true;
1373 }
1374 case Expr::ConditionalOperatorClass: {
1375 // FIXME: Should we pedwarn here?
1376 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1377 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001378 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001379 return true;
1380 }
1381 if (CheckArithmeticConstantExpression(Exp->getCond()))
1382 return true;
1383 if (Exp->getLHS() &&
1384 CheckAddressConstantExpression(Exp->getLHS()))
1385 return true;
1386 return CheckAddressConstantExpression(Exp->getRHS());
1387 }
1388 case Expr::AddrLabelExprClass:
1389 return false;
1390 }
1391}
1392
Eli Friedman4caf0552008-06-09 05:05:07 +00001393static const Expr* FindExpressionBaseAddress(const Expr* E);
1394
1395static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1396 switch (E->getStmtClass()) {
1397 default:
1398 return E;
1399 case Expr::ParenExprClass: {
1400 const ParenExpr* PE = cast<ParenExpr>(E);
1401 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1402 }
1403 case Expr::MemberExprClass: {
1404 const MemberExpr *M = cast<MemberExpr>(E);
1405 if (M->isArrow())
1406 return FindExpressionBaseAddress(M->getBase());
1407 return FindExpressionBaseAddressLValue(M->getBase());
1408 }
1409 case Expr::ArraySubscriptExprClass: {
1410 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1411 return FindExpressionBaseAddress(ASE->getBase());
1412 }
1413 case Expr::UnaryOperatorClass: {
1414 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1415
1416 if (Exp->getOpcode() == UnaryOperator::Deref)
1417 return FindExpressionBaseAddress(Exp->getSubExpr());
1418
1419 return E;
1420 }
1421 }
1422}
1423
1424static const Expr* FindExpressionBaseAddress(const Expr* E) {
1425 switch (E->getStmtClass()) {
1426 default:
1427 return E;
1428 case Expr::ParenExprClass: {
1429 const ParenExpr* PE = cast<ParenExpr>(E);
1430 return FindExpressionBaseAddress(PE->getSubExpr());
1431 }
1432 case Expr::UnaryOperatorClass: {
1433 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1434
1435 // C99 6.6p9
1436 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1437 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1438
1439 if (Exp->getOpcode() == UnaryOperator::Extension)
1440 return FindExpressionBaseAddress(Exp->getSubExpr());
1441
1442 return E;
1443 }
1444 case Expr::BinaryOperatorClass: {
1445 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1446
1447 Expr *PExp = Exp->getLHS();
1448 Expr *IExp = Exp->getRHS();
1449 if (IExp->getType()->isPointerType())
1450 std::swap(PExp, IExp);
1451
1452 return FindExpressionBaseAddress(PExp);
1453 }
1454 case Expr::ImplicitCastExprClass: {
1455 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1456
1457 // Check for implicit promotion
1458 if (SubExpr->getType()->isFunctionType() ||
1459 SubExpr->getType()->isArrayType())
1460 return FindExpressionBaseAddressLValue(SubExpr);
1461
1462 // Check for pointer->pointer cast
1463 if (SubExpr->getType()->isPointerType())
1464 return FindExpressionBaseAddress(SubExpr);
1465
1466 // We assume that we have an arithmetic expression here;
1467 // if we don't, we'll figure it out later
1468 return 0;
1469 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001470 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001471 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1472
1473 // Check for pointer->pointer cast
1474 if (SubExpr->getType()->isPointerType())
1475 return FindExpressionBaseAddress(SubExpr);
1476
1477 // We assume that we have an arithmetic expression here;
1478 // if we don't, we'll figure it out later
1479 return 0;
1480 }
1481 }
1482}
1483
Eli Friedmanc594b322008-05-20 13:48:25 +00001484bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
1485 switch (Init->getStmtClass()) {
1486 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001487 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001488 return true;
1489 case Expr::ParenExprClass: {
1490 const ParenExpr* PE = cast<ParenExpr>(Init);
1491 return CheckArithmeticConstantExpression(PE->getSubExpr());
1492 }
1493 case Expr::FloatingLiteralClass:
1494 case Expr::IntegerLiteralClass:
1495 case Expr::CharacterLiteralClass:
1496 case Expr::ImaginaryLiteralClass:
1497 case Expr::TypesCompatibleExprClass:
1498 case Expr::CXXBoolLiteralExprClass:
1499 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001500 case Expr::CallExprClass:
1501 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001502 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001503
1504 // Allow any constant foldable calls to builtins.
1505 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001506 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001507
Steve Naroff6594a702008-10-27 11:34:16 +00001508 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001509 return true;
1510 }
1511 case Expr::DeclRefExprClass: {
1512 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1513 if (isa<EnumConstantDecl>(D))
1514 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001515 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001516 return true;
1517 }
1518 case Expr::CompoundLiteralExprClass:
1519 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1520 // but vectors are allowed to be magic.
1521 if (Init->getType()->isVectorType())
1522 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001523 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001524 return true;
1525 case Expr::UnaryOperatorClass: {
1526 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1527
1528 switch (Exp->getOpcode()) {
1529 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1530 // See C99 6.6p3.
1531 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001532 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001533 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001534 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001535 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1536 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001537 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001538 return true;
1539 case UnaryOperator::Extension:
1540 case UnaryOperator::LNot:
1541 case UnaryOperator::Plus:
1542 case UnaryOperator::Minus:
1543 case UnaryOperator::Not:
1544 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1545 }
1546 }
Sebastian Redl05189992008-11-11 17:56:53 +00001547 case Expr::SizeOfAlignOfExprClass: {
1548 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001549 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001550 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001551 return false;
1552 // alignof always evaluates to a constant.
1553 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001554 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001555 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001556 return true;
1557 }
1558 return false;
1559 }
1560 case Expr::BinaryOperatorClass: {
1561 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1562
1563 if (Exp->getLHS()->getType()->isArithmeticType() &&
1564 Exp->getRHS()->getType()->isArithmeticType()) {
1565 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1566 CheckArithmeticConstantExpression(Exp->getRHS());
1567 }
1568
Eli Friedman4caf0552008-06-09 05:05:07 +00001569 if (Exp->getLHS()->getType()->isPointerType() &&
1570 Exp->getRHS()->getType()->isPointerType()) {
1571 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1572 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1573
1574 // Only allow a null (constant integer) base; we could
1575 // allow some additional cases if necessary, but this
1576 // is sufficient to cover offsetof-like constructs.
1577 if (!LHSBase && !RHSBase) {
1578 return CheckAddressConstantExpression(Exp->getLHS()) ||
1579 CheckAddressConstantExpression(Exp->getRHS());
1580 }
1581 }
1582
Steve Naroff6594a702008-10-27 11:34:16 +00001583 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001584 return true;
1585 }
1586 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001587 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001588 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001589 if (SubExpr->getType()->isArithmeticType())
1590 return CheckArithmeticConstantExpression(SubExpr);
1591
Eli Friedmanb529d832008-09-02 09:37:00 +00001592 if (SubExpr->getType()->isPointerType()) {
1593 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1594 // If the pointer has a null base, this is an offsetof-like construct
1595 if (!Base)
1596 return CheckAddressConstantExpression(SubExpr);
1597 }
1598
Steve Naroff6594a702008-10-27 11:34:16 +00001599 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001600 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001601 }
1602 case Expr::ConditionalOperatorClass: {
1603 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001604
1605 // If GNU extensions are disabled, we require all operands to be arithmetic
1606 // constant expressions.
1607 if (getLangOptions().NoExtensions) {
1608 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1609 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1610 CheckArithmeticConstantExpression(Exp->getRHS());
1611 }
1612
1613 // Otherwise, we have to emulate some of the behavior of fold here.
1614 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1615 // because it can constant fold things away. To retain compatibility with
1616 // GCC code, we see if we can fold the condition to a constant (which we
1617 // should always be able to do in theory). If so, we only require the
1618 // specified arm of the conditional to be a constant. This is a horrible
1619 // hack, but is require by real world code that uses __builtin_constant_p.
1620 APValue Val;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001621 if (!Exp->getCond()->Evaluate(Val, Context)) {
1622 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001623 // won't be able to either. Use it to emit the diagnostic though.
1624 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001625 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001626 return Res;
1627 }
1628
1629 // Verify that the side following the condition is also a constant.
1630 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1631 if (Val.getInt() == 0)
1632 std::swap(TrueSide, FalseSide);
1633
1634 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001635 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001636
1637 // Okay, the evaluated side evaluates to a constant, so we accept this.
1638 // Check to see if the other side is obviously not a constant. If so,
1639 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001640 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001641 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001642 diag::ext_typecheck_expression_not_constant_but_accepted)
1643 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001644 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001645 }
1646 }
1647}
1648
1649bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Nuno Lopes9a979c32008-07-07 16:46:50 +00001650 Init = Init->IgnoreParens();
1651
Eli Friedmanc594b322008-05-20 13:48:25 +00001652 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1653 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1654 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1655
Nuno Lopes9a979c32008-07-07 16:46:50 +00001656 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1657 return CheckForConstantInitializer(e->getInitializer(), DclT);
1658
Eli Friedmanc594b322008-05-20 13:48:25 +00001659 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1660 unsigned numInits = Exp->getNumInits();
1661 for (unsigned i = 0; i < numInits; i++) {
1662 // FIXME: Need to get the type of the declaration for C++,
1663 // because it could be a reference?
1664 if (CheckForConstantInitializer(Exp->getInit(i),
1665 Exp->getInit(i)->getType()))
1666 return true;
1667 }
1668 return false;
1669 }
1670
1671 if (Init->isNullPointerConstant(Context))
1672 return false;
1673 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001674 QualType InitTy = Context.getCanonicalType(Init->getType())
1675 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001676 if (InitTy == Context.BoolTy) {
1677 // Special handling for pointers implicitly cast to bool;
1678 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1679 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1680 Expr* SubE = ICE->getSubExpr();
1681 if (SubE->getType()->isPointerType() ||
1682 SubE->getType()->isArrayType() ||
1683 SubE->getType()->isFunctionType()) {
1684 return CheckAddressConstantExpression(Init);
1685 }
1686 }
1687 } else if (InitTy->isIntegralType()) {
1688 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001689 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001690 SubE = CE->getSubExpr();
1691 // Special check for pointer cast to int; we allow as an extension
1692 // an address constant cast to an integer if the integer
1693 // is of an appropriate width (this sort of code is apparently used
1694 // in some places).
1695 // FIXME: Add pedwarn?
1696 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1697 if (SubE && (SubE->getType()->isPointerType() ||
1698 SubE->getType()->isArrayType() ||
1699 SubE->getType()->isFunctionType())) {
1700 unsigned IntWidth = Context.getTypeSize(Init->getType());
1701 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1702 if (IntWidth >= PointerWidth)
1703 return CheckAddressConstantExpression(Init);
1704 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001705 }
1706
1707 return CheckArithmeticConstantExpression(Init);
1708 }
1709
1710 if (Init->getType()->isPointerType())
1711 return CheckAddressConstantExpression(Init);
1712
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001713 // An array type at the top level that isn't an init-list must
1714 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001715 if (Init->getType()->isArrayType())
1716 return false;
1717
Nuno Lopes73419bf2008-09-01 18:42:41 +00001718 if (Init->getType()->isFunctionType())
1719 return false;
1720
Steve Naroff8af6a452008-10-02 17:12:56 +00001721 // Allow block exprs at top level.
1722 if (Init->getType()->isBlockPointerType())
1723 return false;
1724
Steve Naroff6594a702008-10-27 11:34:16 +00001725 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001726 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001727}
1728
Steve Naroffbb204692007-09-12 14:07:44 +00001729void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001730 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001731 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001732 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001733
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001734 // If there is no declaration, there was an error parsing it. Just ignore
1735 // the initializer.
1736 if (RealDecl == 0) {
1737 delete Init;
1738 return;
1739 }
Steve Naroffbb204692007-09-12 14:07:44 +00001740
Steve Naroff410e3e22007-09-12 20:13:48 +00001741 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1742 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001743 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1744 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001745 RealDecl->setInvalidDecl();
1746 return;
1747 }
Steve Naroffbb204692007-09-12 14:07:44 +00001748 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001749 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001750 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001751 if (VDecl->isBlockVarDecl()) {
1752 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001753 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001754 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001755 VDecl->setInvalidDecl();
1756 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001757 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1758 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001759 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001760
1761 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1762 if (!getLangOptions().CPlusPlus) {
1763 if (SC == VarDecl::Static) // C99 6.7.8p4.
1764 CheckForConstantInitializer(Init, DclT);
1765 }
Steve Naroffbb204692007-09-12 14:07:44 +00001766 }
Steve Naroff248a7532008-04-15 22:42:06 +00001767 } else if (VDecl->isFileVarDecl()) {
1768 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001769 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001770 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001771 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
1772 VDecl->getName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001773 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001774
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001775 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1776 if (!getLangOptions().CPlusPlus) {
1777 // C99 6.7.8p4. All file scoped initializers need to be constant.
1778 CheckForConstantInitializer(Init, DclT);
1779 }
Steve Naroffbb204692007-09-12 14:07:44 +00001780 }
1781 // If the type changed, it means we had an incomplete type that was
1782 // completed by the initializer. For example:
1783 // int ary[] = { 1, 3, 5 };
1784 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001785 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001786 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001787 Init->setType(DclT);
1788 }
Steve Naroffbb204692007-09-12 14:07:44 +00001789
1790 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001791 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001792 return;
1793}
1794
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001795void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1796 Decl *RealDecl = static_cast<Decl *>(dcl);
1797
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001798 // If there is no declaration, there was an error parsing it. Just ignore it.
1799 if (RealDecl == 0)
1800 return;
1801
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001802 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1803 QualType Type = Var->getType();
1804 // C++ [dcl.init.ref]p3:
1805 // The initializer can be omitted for a reference only in a
1806 // parameter declaration (8.3.5), in the declaration of a
1807 // function return type, in the declaration of a class member
1808 // within its class declaration (9.2), and where the extern
1809 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001810 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001811 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
1812 << Var->getName() << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00001813 Var->setInvalidDecl();
1814 return;
1815 }
1816
1817 // C++ [dcl.init]p9:
1818 //
1819 // If no initializer is specified for an object, and the object
1820 // is of (possibly cv-qualified) non-POD class type (or array
1821 // thereof), the object shall be default-initialized; if the
1822 // object is of const-qualified type, the underlying class type
1823 // shall have a user-declared default constructor.
1824 if (getLangOptions().CPlusPlus) {
1825 QualType InitType = Type;
1826 if (const ArrayType *Array = Context.getAsArrayType(Type))
1827 InitType = Array->getElementType();
1828 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001829 const CXXConstructorDecl *Constructor
1830 = PerformInitializationByConstructor(InitType, 0, 0,
1831 Var->getLocation(),
1832 SourceRange(Var->getLocation(),
1833 Var->getLocation()),
1834 Var->getName(),
1835 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001836 if (!Constructor)
1837 Var->setInvalidDecl();
1838 }
1839 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001840
Douglas Gregor818ce482008-10-29 13:50:18 +00001841#if 0
1842 // FIXME: Temporarily disabled because we are not properly parsing
1843 // linkage specifications on declarations, e.g.,
1844 //
1845 // extern "C" const CGPoint CGPointerZero;
1846 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001847 // C++ [dcl.init]p9:
1848 //
1849 // If no initializer is specified for an object, and the
1850 // object is of (possibly cv-qualified) non-POD class type (or
1851 // array thereof), the object shall be default-initialized; if
1852 // the object is of const-qualified type, the underlying class
1853 // type shall have a user-declared default
1854 // constructor. Otherwise, if no initializer is specified for
1855 // an object, the object and its subobjects, if any, have an
1856 // indeterminate initial value; if the object or any of its
1857 // subobjects are of const-qualified type, the program is
1858 // ill-formed.
1859 //
1860 // This isn't technically an error in C, so we don't diagnose it.
1861 //
1862 // FIXME: Actually perform the POD/user-defined default
1863 // constructor check.
1864 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001865 Context.getCanonicalType(Type).isConstQualified() &&
1866 Var->getStorageClass() != VarDecl::Extern)
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001867 Diag(Var->getLocation(),
1868 diag::err_const_var_requires_init,
1869 Var->getName(),
1870 SourceRange(Var->getLocation(), Var->getLocation()));
Douglas Gregor818ce482008-10-29 13:50:18 +00001871#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001872 }
1873}
1874
Reid Spencer5f016e22007-07-11 17:01:13 +00001875/// The declarators are chained together backwards, reverse the list.
1876Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
1877 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00001878 Decl *GroupDecl = static_cast<Decl*>(group);
1879 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00001880 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00001881
1882 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
1883 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00001884 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00001885 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00001886 else { // reverse the list.
1887 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00001888 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00001889 Group->setNextDeclarator(NewGroup);
1890 NewGroup = Group;
1891 Group = Next;
1892 }
1893 }
1894 // Perform semantic analysis that depends on having fully processed both
1895 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00001896 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00001897 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
1898 if (!IDecl)
1899 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00001900 QualType T = IDecl->getType();
1901
1902 // C99 6.7.5.2p2: If an identifier is declared to be an object with
1903 // static storage duration, it shall not have a variable length array.
Steve Naroff248a7532008-04-15 22:42:06 +00001904 if ((IDecl->isFileVarDecl() || IDecl->isBlockVarDecl()) &&
1905 IDecl->getStorageClass() == VarDecl::Static) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +00001906 if (T->isVariableArrayType()) {
Eli Friedmanc5773c42008-02-15 18:16:39 +00001907 Diag(IDecl->getLocation(), diag::err_typecheck_illegal_vla);
1908 IDecl->setInvalidDecl();
Steve Naroffbb204692007-09-12 14:07:44 +00001909 }
1910 }
1911 // Block scope. C99 6.7p7: If an identifier for an object is declared with
1912 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00001913 if (IDecl->isBlockVarDecl() &&
1914 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001915 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner8b1be772007-12-02 07:50:03 +00001916 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1917 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001918 IDecl->setInvalidDecl();
1919 }
1920 }
1921 // File scope. C99 6.9.2p2: A declaration of an identifier for and
1922 // object that has file scope without an initializer, and without a
1923 // storage-class specifier or with the storage-class specifier "static",
1924 // constitutes a tentative definition. Note: A tentative definition with
1925 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001926 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00001927 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001928 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
1929 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00001930 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00001931 // C99 6.9.2p3: If the declaration of an identifier for an object is
1932 // a tentative definition and has internal linkage (C99 6.2.2p3), the
1933 // declared type shall not be an incomplete type.
Chris Lattner8b1be772007-12-02 07:50:03 +00001934 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type,
1935 T.getAsString());
Steve Naroffbb204692007-09-12 14:07:44 +00001936 IDecl->setInvalidDecl();
1937 }
1938 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00001939 if (IDecl->isFileVarDecl())
1940 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00001941 }
1942 return NewGroup;
1943}
Steve Naroffe1223f72007-08-28 03:03:08 +00001944
Chris Lattner04421082008-04-08 04:40:51 +00001945/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
1946/// to introduce parameters into function prototype scope.
1947Sema::DeclTy *
1948Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001949 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00001950 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00001951
1952 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00001953 VarDecl::StorageClass StorageClass = VarDecl::None;
1954 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
1955 StorageClass = VarDecl::Register;
1956 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00001957 Diag(DS.getStorageClassSpecLoc(),
1958 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001959 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001960 }
1961 if (DS.isThreadSpecified()) {
1962 Diag(DS.getThreadSpecLoc(),
1963 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00001964 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00001965 }
1966
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001967 // Check that there are no default arguments inside the type of this
1968 // parameter (C++ only).
1969 if (getLangOptions().CPlusPlus)
1970 CheckExtraCXXDefaultArguments(D);
1971
Chris Lattner04421082008-04-08 04:40:51 +00001972 // In this context, we *do not* check D.getInvalidType(). If the declarator
1973 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
1974 // though it will not reflect the user specified type.
1975 QualType parmDeclType = GetTypeForDeclarator(D, S);
1976
1977 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
1978
Reid Spencer5f016e22007-07-11 17:01:13 +00001979 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
1980 // Can this happen for params? We already checked that they don't conflict
1981 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00001982 IdentifierInfo *II = D.getIdentifier();
1983 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
1984 if (S->isDeclScope(PrevDecl)) {
1985 Diag(D.getIdentifierLoc(), diag::err_param_redefinition,
1986 dyn_cast<NamedDecl>(PrevDecl)->getName());
1987
1988 // Recover by removing the name
1989 II = 0;
1990 D.SetIdentifier(0, D.getIdentifierLoc());
1991 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001992 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00001993
1994 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
1995 // Doing the promotion here has a win and a loss. The win is the type for
1996 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
1997 // code generator). The loss is the orginal type isn't preserved. For example:
1998 //
1999 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2000 // int blockvardecl[5];
2001 // sizeof(parmvardecl); // size == 4
2002 // sizeof(blockvardecl); // size == 20
2003 // }
2004 //
2005 // For expressions, all implicit conversions are captured using the
2006 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2007 //
2008 // FIXME: If a source translation tool needs to see the original type, then
2009 // we need to consider storing both types (in ParmVarDecl)...
2010 //
Chris Lattnere6327742008-04-02 05:18:44 +00002011 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002012 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002013 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002014 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002015 parmDeclType = Context.getPointerType(parmDeclType);
2016
Chris Lattner04421082008-04-08 04:40:51 +00002017 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2018 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002019 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002020 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002021
Chris Lattner04421082008-04-08 04:40:51 +00002022 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002023 New->setInvalidDecl();
2024
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002025 if (II)
2026 PushOnScopeChains(New, S);
Nate Begemanb7894b52008-02-17 21:20:31 +00002027
Chris Lattner3ff30c82008-06-29 00:02:00 +00002028 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002029 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002030
Reid Spencer5f016e22007-07-11 17:01:13 +00002031}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002032
Chris Lattnerb652cea2007-10-09 17:14:05 +00002033Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002034 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002035 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2036 "Not a function declarator!");
2037 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002038
Reid Spencer5f016e22007-07-11 17:01:13 +00002039 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2040 // for a K&R function.
2041 if (!FTI.hasPrototype) {
2042 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002043 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002044 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2045 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002046 // Implicitly declare the argument as type 'int' for lack of a better
2047 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002048 DeclSpec DS;
2049 const char* PrevSpec; // unused
2050 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2051 PrevSpec);
2052 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2053 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2054 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002055 }
2056 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002057 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002058 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002059 }
2060
2061 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002062
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002063 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00002064 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002065}
2066
2067Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2068 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002069 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002070
2071 // See if this is a redefinition.
2072 const FunctionDecl *Definition;
2073 if (FD->getBody(Definition)) {
2074 Diag(FD->getLocation(), diag::err_redefinition,
2075 FD->getName());
2076 Diag(Definition->getLocation(), diag::err_previous_definition);
2077 }
2078
Chris Lattnerb048c982008-04-06 04:47:34 +00002079 PushDeclContext(FD);
Chris Lattner04421082008-04-08 04:40:51 +00002080
2081 // Check the validity of our function parameters
2082 CheckParmsForFunctionDef(FD);
2083
2084 // Introduce our parameters into the function scope
2085 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2086 ParmVarDecl *Param = FD->getParamDecl(p);
2087 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002088 if (Param->getIdentifier())
2089 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002090 }
Chris Lattner04421082008-04-08 04:40:51 +00002091
Reid Spencer5f016e22007-07-11 17:01:13 +00002092 return FD;
2093}
2094
Steve Naroffd6d054d2007-11-11 23:20:51 +00002095Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2096 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002097 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002098 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002099 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002100 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002101 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002102 } else
2103 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002104 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002105 // Verify and clean out per-function state.
2106
2107 // Check goto/label use.
2108 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2109 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2110 // Verify that we have no forward references left. If so, there was a goto
2111 // or address of a label taken, but no definition of it. Label fwd
2112 // definitions are indicated with a null substmt.
2113 if (I->second->getSubStmt() == 0) {
2114 LabelStmt *L = I->second;
2115 // Emit error.
2116 Diag(L->getIdentLoc(), diag::err_undeclared_label_use, L->getName());
2117
2118 // At this point, we have gotos that use the bogus label. Stitch it into
2119 // the function body so that they aren't leaked and that the AST is well
2120 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002121 if (Body) {
2122 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2123 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2124 } else {
2125 // The whole function wasn't parsed correctly, just delete this.
2126 delete L;
2127 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002128 }
2129 }
2130 LabelMap.clear();
2131
Steve Naroffd6d054d2007-11-11 23:20:51 +00002132 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002133}
2134
Reid Spencer5f016e22007-07-11 17:01:13 +00002135/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2136/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002137ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2138 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002139 // Extension in C99. Legal in C90, but warn about it.
2140 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002141 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002142 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002143 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002144
2145 // FIXME: handle stuff like:
2146 // void foo() { extern float X(); }
2147 // void bar() { X(); } <-- implicit decl for X in another scope.
2148
2149 // Set a Declarator for the implicit definition: int foo();
2150 const char *Dummy;
2151 DeclSpec DS;
2152 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2153 Error = Error; // Silence warning.
2154 assert(!Error && "Error setting up implicit decl!");
2155 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002156 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002157 D.SetIdentifier(&II, Loc);
2158
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002159 // Insert this function into translation-unit scope.
2160
2161 DeclContext *PrevDC = CurContext;
2162 CurContext = Context.getTranslationUnitDecl();
2163
Steve Naroffe2ef8152008-04-04 14:32:09 +00002164 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002165 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002166 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002167
2168 CurContext = PrevDC;
2169
Steve Naroffe2ef8152008-04-04 14:32:09 +00002170 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002171}
2172
2173
Chris Lattner41af0932007-11-14 06:34:38 +00002174TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002175 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002176 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002177 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002178
2179 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002180 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2181 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002182 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002183 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002184 if (D.getInvalidType())
2185 NewTD->setInvalidDecl();
2186 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002187}
2188
Steve Naroff08d92e42007-09-15 18:49:24 +00002189/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002190/// former case, Name will be non-null. In the later case, Name will be null.
2191/// TagType indicates what kind of tag this is. TK indicates whether this is a
2192/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002193Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002194 SourceLocation KWLoc, const CXXScopeSpec &SS,
2195 IdentifierInfo *Name, SourceLocation NameLoc,
2196 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002197 // If this is a use of an existing tag, it must have a name.
2198 assert((Name != 0 || TK == TK_Definition) &&
2199 "Nameless record must be a definition!");
2200
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002201 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 switch (TagType) {
2203 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002204 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2205 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2206 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2207 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002208 }
2209
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002210 // Two code paths: a new one for structs/unions/classes where we create
2211 // separate decls for forward declarations, and an old (eventually to
2212 // be removed) code path for enums.
2213 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002214 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002215
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002216 DeclContext *DC = CurContext;
2217 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002218
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002219 if (Name && SS.isNotEmpty()) {
2220 // We have a nested-name tag ('struct foo::bar').
2221
2222 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002223 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002224 Name = 0;
2225 goto CreateNewDecl;
2226 }
2227
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002228 DC = static_cast<DeclContext*>(SS.getScopeRep());
2229 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002230 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2231
2232 // A tag 'foo::bar' must already exist.
2233 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002234 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002235 Name = 0;
2236 goto CreateNewDecl;
2237 }
2238 } else {
2239 // If this is a named struct, check to see if there was a previous forward
2240 // declaration or definition.
2241 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2242 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2243 }
2244
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002245 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002246 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2247 "unexpected Decl type");
2248 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002249 // If this is a use of a previous tag, or if the tag is already declared
2250 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002251 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002252 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002253 // Make sure that this wasn't declared as an enum and now used as a
2254 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002255 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002256 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002257 Diag(PrevDecl->getLocation(), diag::err_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002258 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002259 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002260 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002261 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002262 // If this is a use or a forward declaration, we're good.
2263 if (TK != TK_Definition)
2264 return PrevDecl;
2265
2266 // Diagnose attempts to redefine a tag.
2267 if (PrevTagDecl->isDefinition()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002268 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner14943b92008-07-03 03:30:58 +00002269 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2270 // If this is a redefinition, recover by making this struct be
2271 // anonymous, which will make any later references get the previous
2272 // definition.
2273 Name = 0;
2274 } else {
2275 // Okay, this is definition of a previously declared or referenced
2276 // tag. Move the location of the decl to be the definition site.
2277 PrevDecl->setLocation(NameLoc);
2278 return PrevDecl;
2279 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002280 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002281 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002282 // If we get here, this is a definition of a new struct type in a nested
2283 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2284 // type.
2285 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002286 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002287 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002288 // The tag name clashes with a namespace name, issue an error and
2289 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002290 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002291 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2292 Name = 0;
2293 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002294 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002295 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002296
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002297 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002298
2299 // If there is an identifier, use the location of the identifier as the
2300 // location of the decl, otherwise use the location of the struct/union
2301 // keyword.
2302 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2303
2304 // Otherwise, if this is the first time we've seen this tag, create the decl.
2305 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002306 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002307 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2308 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002309 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002310 // If this is an undefined enum, warn.
2311 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002312 } else {
2313 // struct/union/class
2314
Reid Spencer5f016e22007-07-11 17:01:13 +00002315 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2316 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002317 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002318 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002319 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002320 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002321 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002322 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002323
2324 // If this has an identifier, add it to the scope stack.
2325 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002326 // The scope passed in may not be a decl scope. Zip up the scope tree until
2327 // we find one that is.
2328 while ((S->getFlags() & Scope::DeclScope) == 0)
2329 S = S->getParent();
2330
2331 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002332 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002333 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002334
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002335 if (Attr)
2336 ProcessDeclAttributeList(New, Attr);
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002337
2338 // Set the lexical context. If the tag has a C++ scope specifier, the
2339 // lexical context will be different from the semantic context.
2340 New->setLexicalDeclContext(CurContext);
2341
Reid Spencer5f016e22007-07-11 17:01:13 +00002342 return New;
2343}
2344
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002345/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2346/// the logic for enums, we create separate decls for forward declarations.
2347/// This is called by ActOnTag, but eventually will replace its logic.
2348Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002349 SourceLocation KWLoc, const CXXScopeSpec &SS,
2350 IdentifierInfo *Name, SourceLocation NameLoc,
2351 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002352 DeclContext *DC = CurContext;
2353 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002354
2355 if (Name && SS.isNotEmpty()) {
2356 // We have a nested-name tag ('struct foo::bar').
2357
2358 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002359 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002360 Name = 0;
2361 goto CreateNewDecl;
2362 }
2363
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002364 DC = static_cast<DeclContext*>(SS.getScopeRep());
2365 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002366 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2367
2368 // A tag 'foo::bar' must already exist.
2369 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002370 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002371 Name = 0;
2372 goto CreateNewDecl;
2373 }
2374 } else {
2375 // If this is a named struct, check to see if there was a previous forward
2376 // declaration or definition.
2377 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2378 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2379 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002380
2381 if (PrevDecl) {
2382 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2383 "unexpected Decl type");
2384
2385 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2386 // If this is a use of a previous tag, or if the tag is already declared
2387 // in the same scope (so that the definition/declaration completes or
2388 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002389 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002390 // Make sure that this wasn't declared as an enum and now used as a
2391 // struct or something similar.
2392 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002393 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002394 Diag(PrevDecl->getLocation(), diag::err_previous_use);
2395 // Recover by making this an anonymous redefinition.
2396 Name = 0;
2397 PrevDecl = 0;
2398 } else {
2399 // If this is a use, return the original decl.
2400
2401 // FIXME: In the future, return a variant or some other clue
2402 // for the consumer of this Decl to know it doesn't own it.
2403 // For our current ASTs this shouldn't be a problem, but will
2404 // need to be changed with DeclGroups.
2405 if (TK == TK_Reference)
2406 return PrevDecl;
2407
2408 // The new decl is a definition?
2409 if (TK == TK_Definition) {
2410 // Diagnose attempts to redefine a tag.
2411 if (RecordDecl* DefRecord =
2412 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002413 Diag(NameLoc, diag::err_redefinition) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002414 Diag(DefRecord->getLocation(), diag::err_previous_definition);
2415 // If this is a redefinition, recover by making this struct be
2416 // anonymous, which will make any later references get the previous
2417 // definition.
2418 Name = 0;
2419 PrevDecl = 0;
2420 }
2421 // Okay, this is definition of a previously declared or referenced
2422 // tag. We're going to create a new Decl.
2423 }
2424 }
2425 // If we get here we have (another) forward declaration. Just create
2426 // a new decl.
2427 }
2428 else {
2429 // If we get here, this is a definition of a new struct type in a nested
2430 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2431 // new decl/type. We set PrevDecl to NULL so that the Records
2432 // have distinct types.
2433 PrevDecl = 0;
2434 }
2435 } else {
2436 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002437 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002438 // The tag name clashes with a namespace name, issue an error and
2439 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002440 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002441 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
2442 Name = 0;
2443 }
2444 }
2445 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002446
2447 CreateNewDecl:
2448
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002449 // If there is an identifier, use the location of the identifier as the
2450 // location of the decl, otherwise use the location of the struct/union
2451 // keyword.
2452 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2453
2454 // Otherwise, if this is the first time we've seen this tag, create the decl.
2455 TagDecl *New;
2456
2457 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2458 // struct X { int A; } D; D should chain to X.
2459 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002460 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002461 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002462 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2463 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002464 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002465 dyn_cast_or_null<RecordDecl>(PrevDecl));
2466
2467 // If this has an identifier, add it to the scope stack.
2468 if ((TK == TK_Definition || !PrevDecl) && Name) {
2469 // The scope passed in may not be a decl scope. Zip up the scope tree until
2470 // we find one that is.
2471 while ((S->getFlags() & Scope::DeclScope) == 0)
2472 S = S->getParent();
2473
2474 // Add it to the decl chain.
2475 PushOnScopeChains(New, S);
2476 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002477
2478 // Handle #pragma pack: if the #pragma pack stack has non-default
2479 // alignment, make up a packed attribute for this decl. These
2480 // attributes are checked when the ASTContext lays out the
2481 // structure.
2482 //
2483 // It is important for implementing the correct semantics that this
2484 // happen here (in act on tag decl). The #pragma pack stack is
2485 // maintained as a result of parser callbacks which can occur at
2486 // many points during the parsing of a struct declaration (because
2487 // the #pragma tokens are effectively skipped over during the
2488 // parsing of the struct).
2489 if (unsigned Alignment = PackContext.getAlignment())
2490 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002491
2492 if (Attr)
2493 ProcessDeclAttributeList(New, Attr);
2494
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002495 // Set the lexical context. If the tag has a C++ scope specifier, the
2496 // lexical context will be different from the semantic context.
2497 New->setLexicalDeclContext(CurContext);
2498
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002499 return New;
2500}
2501
2502
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002503/// Collect the instance variables declared in an Objective-C object. Used in
2504/// the creation of structures from objects using the @defs directive.
Ted Kremenek01e67792008-08-20 03:26:33 +00002505static void CollectIvars(ObjCInterfaceDecl *Class, ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002506 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002507 if (Class->getSuperClass())
Ted Kremenek01e67792008-08-20 03:26:33 +00002508 CollectIvars(Class->getSuperClass(), Ctx, ivars);
2509
2510 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002511 for (ObjCInterfaceDecl::ivar_iterator
2512 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2513
Ted Kremenek01e67792008-08-20 03:26:33 +00002514 ObjCIvarDecl* ID = *I;
2515 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, ID->getLocation(),
2516 ID->getIdentifier(),
2517 ID->getType(),
2518 ID->getBitWidth()));
2519 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002520}
2521
2522/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2523/// instance variables of ClassName into Decls.
2524void Sema::ActOnDefs(Scope *S, SourceLocation DeclStart,
2525 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002526 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002527 // Check that ClassName is a valid class
2528 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2529 if (!Class) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002530 Diag(DeclStart, diag::err_undef_interface) << ClassName;
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002531 return;
2532 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002533 // Collect the instance variables
Ted Kremenek01e67792008-08-20 03:26:33 +00002534 CollectIvars(Class, Context, Decls);
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002535}
2536
Chris Lattner1d353ba2008-11-12 21:17:48 +00002537/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2538/// types into constant array types in certain situations which would otherwise
2539/// be errors (for GCC compatibility).
2540static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2541 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002542 // This method tries to turn a variable array into a constant
2543 // array even when the size isn't an ICE. This is necessary
2544 // for compatibility with code that depends on gcc's buggy
2545 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002546 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2547 if (!VLATy) return QualType();
2548
2549 APValue Result;
2550 if (!VLATy->getSizeExpr() ||
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002551 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002552 return QualType();
2553
2554 assert(Result.isInt() && "Size expressions must be integers!");
2555 llvm::APSInt &Res = Result.getInt();
2556 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2557 return Context.getConstantArrayType(VLATy->getElementType(),
2558 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002559 return QualType();
2560}
2561
Steve Naroff08d92e42007-09-15 18:49:24 +00002562/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002563/// to create a FieldDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002564Sema::DeclTy *Sema::ActOnField(Scope *S,
Reid Spencer5f016e22007-07-11 17:01:13 +00002565 SourceLocation DeclStart,
2566 Declarator &D, ExprTy *BitfieldWidth) {
2567 IdentifierInfo *II = D.getIdentifier();
2568 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002569 SourceLocation Loc = DeclStart;
2570 if (II) Loc = D.getIdentifierLoc();
2571
2572 // FIXME: Unnamed fields can be handled in various different ways, for
2573 // example, unnamed unions inject all members into the struct namespace!
Ted Kremeneka89d1972008-09-03 18:03:35 +00002574
Reid Spencer5f016e22007-07-11 17:01:13 +00002575 if (BitWidth) {
2576 // TODO: Validate.
2577 //printf("WARNING: BITFIELDS IGNORED!\n");
2578
2579 // 6.7.2.1p3
2580 // 6.7.2.1p4
2581
2582 } else {
2583 // Not a bitfield.
2584
2585 // validate II.
2586
2587 }
2588
2589 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002590 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2591 bool InvalidDecl = false;
Steve Naroffd7444aa2007-08-31 17:20:07 +00002592
Reid Spencer5f016e22007-07-11 17:01:13 +00002593 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2594 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002595 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002596 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002597 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002598 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002599 T = FixedTy;
2600 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002601 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002602 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002603 InvalidDecl = true;
2604 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002605 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002606 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002607 FieldDecl *NewFD;
2608
2609 if (getLangOptions().CPlusPlus) {
2610 // FIXME: Replace CXXFieldDecls with FieldDecls for simple structs.
2611 NewFD = CXXFieldDecl::Create(Context, cast<CXXRecordDecl>(CurContext),
Sebastian Redla11f42f2008-11-17 23:24:37 +00002612 Loc, II, T,
2613 D.getDeclSpec().getStorageClassSpec() ==
2614 DeclSpec::SCS_mutable, BitWidth);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002615 if (II)
2616 PushOnScopeChains(NewFD, S);
2617 }
2618 else
2619 NewFD = FieldDecl::Create(Context, Loc, II, T, BitWidth);
Steve Naroff44739212007-09-11 21:17:26 +00002620
Chris Lattner3ff30c82008-06-29 00:02:00 +00002621 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002622
Steve Naroff5912a352007-08-28 20:14:24 +00002623 if (D.getInvalidType() || InvalidDecl)
2624 NewFD->setInvalidDecl();
2625 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002626}
2627
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002628/// TranslateIvarVisibility - Translate visibility from a token ID to an
2629/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002630static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002631TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002632 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002633 default: assert(0 && "Unknown visitibility kind");
2634 case tok::objc_private: return ObjCIvarDecl::Private;
2635 case tok::objc_public: return ObjCIvarDecl::Public;
2636 case tok::objc_protected: return ObjCIvarDecl::Protected;
2637 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002638 }
2639}
2640
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002641/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2642/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002643Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002644 SourceLocation DeclStart,
2645 Declarator &D, ExprTy *BitfieldWidth,
2646 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002647 IdentifierInfo *II = D.getIdentifier();
2648 Expr *BitWidth = (Expr*)BitfieldWidth;
2649 SourceLocation Loc = DeclStart;
2650 if (II) Loc = D.getIdentifierLoc();
2651
2652 // FIXME: Unnamed fields can be handled in various different ways, for
2653 // example, unnamed unions inject all members into the struct namespace!
2654
2655
2656 if (BitWidth) {
2657 // TODO: Validate.
2658 //printf("WARNING: BITFIELDS IGNORED!\n");
2659
2660 // 6.7.2.1p3
2661 // 6.7.2.1p4
2662
2663 } else {
2664 // Not a bitfield.
2665
2666 // validate II.
2667
2668 }
2669
2670 QualType T = GetTypeForDeclarator(D, S);
2671 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2672 bool InvalidDecl = false;
2673
2674 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2675 // than a variably modified type.
2676 if (T->isVariablyModifiedType()) {
2677 // FIXME: This diagnostic needs work
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00002678 Diag(Loc, diag::err_typecheck_illegal_vla) << SourceRange(Loc);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002679 InvalidDecl = true;
2680 }
2681
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002682 // Get the visibility (access control) for this ivar.
2683 ObjCIvarDecl::AccessControl ac =
2684 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2685 : ObjCIvarDecl::None;
2686
2687 // Construct the decl.
2688 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002689 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002690
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002691 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002692 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002693
2694 if (D.getInvalidType() || InvalidDecl)
2695 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002696
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002697 return NewID;
2698}
2699
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002700void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002701 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002702 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002703 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002704 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002705 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2706 assert(EnclosingDecl && "missing record or interface decl");
2707 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2708
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002709 if (Record)
2710 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2711 // Diagnose code like:
2712 // struct S { struct S {} X; };
2713 // We discover this when we complete the outer S. Reject and ignore the
2714 // outer S.
2715 Diag(DefRecord->getLocation(), diag::err_nested_redefinition,
2716 DefRecord->getKindName());
2717 Diag(RecLoc, diag::err_previous_definition);
2718 Record->setInvalidDecl();
2719 return;
2720 }
2721
Reid Spencer5f016e22007-07-11 17:01:13 +00002722 // Verify that all the fields are okay.
2723 unsigned NumNamedMembers = 0;
2724 llvm::SmallVector<FieldDecl*, 32> RecFields;
2725 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002726
Reid Spencer5f016e22007-07-11 17:01:13 +00002727 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002728
Steve Naroff74216642007-09-14 22:20:54 +00002729 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2730 assert(FD && "missing field decl");
2731
2732 // Remember all fields.
2733 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002734
2735 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002736 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002737
Reid Spencer5f016e22007-07-11 17:01:13 +00002738 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002739 if (FDTy->isFunctionType()) {
Steve Naroff74216642007-09-14 22:20:54 +00002740 Diag(FD->getLocation(), diag::err_field_declared_as_function,
Reid Spencer5f016e22007-07-11 17:01:13 +00002741 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002742 FD->setInvalidDecl();
2743 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002744 continue;
2745 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002746 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2747 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002748 if (!Record) { // Incomplete ivar type is always an error.
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002749 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002750 FD->setInvalidDecl();
2751 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002752 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002753 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002754 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002755 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002756 !FDTy->isArrayType()) { //... may have incomplete array type.
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 Diag(FD->getLocation(), diag::err_field_incomplete, FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002758 FD->setInvalidDecl();
2759 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 continue;
2761 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002762 if (NumNamedMembers < 1) { //... must have more than named member ...
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct,
2764 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002765 FD->setInvalidDecl();
2766 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002767 continue;
2768 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002769 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002770 if (Record)
2771 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002773 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2774 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002775 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002776 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2777 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002778 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002779 Record->setHasFlexibleArrayMember(true);
2780 } else {
2781 // If this is a struct/class and this is not the last element, reject
2782 // it. Note that GCC supports variable sized arrays in the middle of
2783 // structures.
2784 if (i != NumFields-1) {
2785 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct,
2786 FD->getName());
Steve Naroff74216642007-09-14 22:20:54 +00002787 FD->setInvalidDecl();
2788 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002789 continue;
2790 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002791 // We support flexible arrays at the end of structs in other structs
2792 // as an extension.
2793 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct,
2794 FD->getName());
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002795 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002796 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002797 }
2798 }
2799 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002800 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002801 if (FDTy->isObjCInterfaceType()) {
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002802 Diag(FD->getLocation(), diag::err_statically_allocated_object,
2803 FD->getName());
2804 FD->setInvalidDecl();
2805 EnclosingDecl->setInvalidDecl();
2806 continue;
2807 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002808 // Keep track of the number of named members.
2809 if (IdentifierInfo *II = FD->getIdentifier()) {
2810 // Detect duplicate member names.
2811 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002812 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002813 // Find the previous decl.
2814 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00002815 for (unsigned i = 0; ; ++i) {
2816 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00002817 if (RecFields[i]->getIdentifier() == II) {
2818 PrevLoc = RecFields[i]->getLocation();
2819 break;
2820 }
2821 }
2822 Diag(PrevLoc, diag::err_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00002823 FD->setInvalidDecl();
2824 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002825 continue;
2826 }
2827 ++NumNamedMembers;
2828 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002829 }
2830
Reid Spencer5f016e22007-07-11 17:01:13 +00002831 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00002832 if (Record) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002833 Record->defineBody(Context, &RecFields[0], RecFields.size());
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00002834 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
2835 // Sema::ActOnFinishCXXClassDef.
2836 if (!isa<CXXRecordDecl>(Record))
2837 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00002838 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00002839 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
2840 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
2841 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
2842 else if (ObjCImplementationDecl *IMPDecl =
2843 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002844 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
2845 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00002846 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00002847 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00002848 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00002849
2850 if (Attr)
2851 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00002852}
2853
Steve Naroff08d92e42007-09-15 18:49:24 +00002854Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00002855 DeclTy *lastEnumConst,
2856 SourceLocation IdLoc, IdentifierInfo *Id,
2857 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00002858 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002859 EnumConstantDecl *LastEnumConst =
2860 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
2861 Expr *Val = static_cast<Expr*>(val);
2862
Chris Lattner31e05722007-08-26 06:24:45 +00002863 // The scope passed in may not be a decl scope. Zip up the scope tree until
2864 // we find one that is.
2865 while ((S->getFlags() & Scope::DeclScope) == 0)
2866 S = S->getParent();
2867
Reid Spencer5f016e22007-07-11 17:01:13 +00002868 // Verify that there isn't already something declared with this name in this
2869 // scope.
Steve Naroffb327ce02008-04-02 14:35:35 +00002870 if (Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S)) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00002871 // When in C++, we may get a TagDecl with the same name; in this case the
2872 // enum constant will 'hide' the tag.
2873 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
2874 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00002875 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002876 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00002877 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00002878 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002879 Diag(IdLoc, diag::err_redefinition) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00002880 Diag(PrevDecl->getLocation(), diag::err_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00002881 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00002882 return 0;
2883 }
2884 }
2885
2886 llvm::APSInt EnumVal(32);
2887 QualType EltTy;
2888 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00002889 // Make sure to promote the operand type to int.
2890 UsualUnaryConversions(Val);
2891
Reid Spencer5f016e22007-07-11 17:01:13 +00002892 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
2893 SourceLocation ExpLoc;
Chris Lattner590b6642007-07-15 23:26:56 +00002894 if (!Val->isIntegerConstantExpr(EnumVal, Context, &ExpLoc)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002895 Diag(ExpLoc, diag::err_enum_value_not_integer_constant_expr) << Id;
Chris Lattnera73349d2008-02-26 00:33:57 +00002896 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00002897 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00002898 } else {
2899 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00002900 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00002901 }
2902
2903 if (!Val) {
2904 if (LastEnumConst) {
2905 // Assign the last value + 1.
2906 EnumVal = LastEnumConst->getInitVal();
2907 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00002908
2909 // Check for overflow on increment.
2910 if (EnumVal < LastEnumConst->getInitVal())
2911 Diag(IdLoc, diag::warn_enum_value_overflow);
2912
Chris Lattnerb7416f92007-08-27 17:37:24 +00002913 EltTy = LastEnumConst->getType();
2914 } else {
2915 // First value, set to zero.
2916 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00002917 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00002918 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002919 }
2920
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002921 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00002922 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
2923 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00002924 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00002925
2926 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002927 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002928 return New;
2929}
2930
Steve Naroff02408c62008-08-07 14:08:16 +00002931// FIXME: For consistency with ActOnFields(), we should have the parser
2932// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00002933void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 DeclTy **Elements, unsigned NumElements) {
2935 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00002936
Steve Naroff02408c62008-08-07 14:08:16 +00002937 if (Enum && Enum->isDefinition()) {
2938 // Diagnose code like:
2939 // enum e0 {
2940 // E0 = sizeof(enum e0 { E1 })
2941 // };
2942 Diag(Enum->getLocation(), diag::err_nested_redefinition,
2943 Enum->getName());
2944 Diag(EnumLoc, diag::err_previous_definition);
2945 Enum->setInvalidDecl();
2946 return;
2947 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00002948 // TODO: If the result value doesn't fit in an int, it must be a long or long
2949 // long value. ISO C does not support this, but GCC does as an extension,
2950 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00002951 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00002952
Chris Lattnerac609682007-08-28 06:15:15 +00002953 // Verify that all the values are okay, compute the size of the values, and
2954 // reverse the list.
2955 unsigned NumNegativeBits = 0;
2956 unsigned NumPositiveBits = 0;
2957
2958 // Keep track of whether all elements have type int.
2959 bool AllElementsInt = true;
2960
Reid Spencer5f016e22007-07-11 17:01:13 +00002961 EnumConstantDecl *EltList = 0;
2962 for (unsigned i = 0; i != NumElements; ++i) {
2963 EnumConstantDecl *ECD =
2964 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
2965 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00002966
2967 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00002968 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00002969 assert(InitVal.getBitWidth() >= IntWidth &&
2970 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00002971 if (InitVal.getBitWidth() > IntWidth) {
2972 llvm::APSInt V(InitVal);
2973 V.trunc(IntWidth);
2974 V.extend(InitVal.getBitWidth());
2975 if (V != InitVal)
2976 Diag(ECD->getLocation(), diag::ext_enum_value_not_int,
Chris Lattner9aa77f12008-08-17 07:19:51 +00002977 InitVal.toString(10));
Chris Lattner211a30e2007-08-28 05:27:00 +00002978 }
Chris Lattnerac609682007-08-28 06:15:15 +00002979
2980 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00002981 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00002982 NumPositiveBits = std::max(NumPositiveBits,
2983 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00002984 else
Chris Lattner21dd8212008-01-14 21:47:29 +00002985 NumNegativeBits = std::max(NumNegativeBits,
2986 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00002987
Chris Lattnerac609682007-08-28 06:15:15 +00002988 // Keep track of whether every enum element has type int (very commmon).
2989 if (AllElementsInt)
2990 AllElementsInt = ECD->getType() == Context.IntTy;
2991
Reid Spencer5f016e22007-07-11 17:01:13 +00002992 ECD->setNextDeclarator(EltList);
2993 EltList = ECD;
2994 }
2995
Chris Lattnerac609682007-08-28 06:15:15 +00002996 // Figure out the type that should be used for this enum.
2997 // FIXME: Support attribute(packed) on enums and -fshort-enums.
2998 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00002999 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003000
3001 if (NumNegativeBits) {
3002 // If there is a negative value, figure out the smallest integer type (of
3003 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003004 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003005 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003006 BestWidth = IntWidth;
3007 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003008 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003009
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003010 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003011 BestType = Context.LongTy;
3012 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003013 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003014
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003015 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003016 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3017 BestType = Context.LongLongTy;
3018 }
3019 }
3020 } else {
3021 // If there is no negative value, figure out which of uint, ulong, ulonglong
3022 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003023 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003024 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003025 BestWidth = IntWidth;
3026 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003027 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003028 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003029 } else {
3030 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003031 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003032 "How could an initializer get larger than ULL?");
3033 BestType = Context.UnsignedLongLongTy;
3034 }
3035 }
3036
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003037 // Loop over all of the enumerator constants, changing their types to match
3038 // the type of the enum if needed.
3039 for (unsigned i = 0; i != NumElements; ++i) {
3040 EnumConstantDecl *ECD =
3041 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3042 if (!ECD) continue; // Already issued a diagnostic.
3043
3044 // Standard C says the enumerators have int type, but we allow, as an
3045 // extension, the enumerators to be larger than int size. If each
3046 // enumerator value fits in an int, type it as an int, otherwise type it the
3047 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3048 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003049 if (ECD->getType() == Context.IntTy) {
3050 // Make sure the init value is signed.
3051 llvm::APSInt IV = ECD->getInitVal();
3052 IV.setIsSigned(true);
3053 ECD->setInitVal(IV);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003054 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003055 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003056
3057 // Determine whether the value fits into an int.
3058 llvm::APSInt InitVal = ECD->getInitVal();
3059 bool FitsInInt;
3060 if (InitVal.isUnsigned() || !InitVal.isNegative())
3061 FitsInInt = InitVal.getActiveBits() < IntWidth;
3062 else
3063 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3064
3065 // If it fits into an integer type, force it. Otherwise force it to match
3066 // the enum decl type.
3067 QualType NewTy;
3068 unsigned NewWidth;
3069 bool NewSign;
3070 if (FitsInInt) {
3071 NewTy = Context.IntTy;
3072 NewWidth = IntWidth;
3073 NewSign = true;
3074 } else if (ECD->getType() == BestType) {
3075 // Already the right type!
3076 continue;
3077 } else {
3078 NewTy = BestType;
3079 NewWidth = BestWidth;
3080 NewSign = BestType->isSignedIntegerType();
3081 }
3082
3083 // Adjust the APSInt value.
3084 InitVal.extOrTrunc(NewWidth);
3085 InitVal.setIsSigned(NewSign);
3086 ECD->setInitVal(InitVal);
3087
3088 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003089 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3090 /*isLvalue=*/false));
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003091 ECD->setType(NewTy);
3092 }
Chris Lattnerac609682007-08-28 06:15:15 +00003093
Chris Lattnere00b18c2007-08-28 18:24:31 +00003094 Enum->defineElements(EltList, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003095 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003096}
3097
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003098Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3099 ExprTy *expr) {
3100 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3101
Chris Lattner8e25d862008-03-16 00:16:02 +00003102 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003103}
3104
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003105Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003106 SourceLocation LBrace,
3107 SourceLocation RBrace,
3108 const char *Lang,
3109 unsigned StrSize,
3110 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003111 LinkageSpecDecl::LanguageIDs Language;
3112 Decl *dcl = static_cast<Decl *>(D);
3113 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3114 Language = LinkageSpecDecl::lang_c;
3115 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3116 Language = LinkageSpecDecl::lang_cxx;
3117 else {
3118 Diag(Loc, diag::err_bad_language);
3119 return 0;
3120 }
3121
3122 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003123 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003124}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003125
3126void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3127 ExprTy *alignment, SourceLocation PragmaLoc,
3128 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3129 Expr *Alignment = static_cast<Expr *>(alignment);
3130
3131 // If specified then alignment must be a "small" power of two.
3132 unsigned AlignmentVal = 0;
3133 if (Alignment) {
3134 llvm::APSInt Val;
3135 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3136 !Val.isPowerOf2() ||
3137 Val.getZExtValue() > 16) {
3138 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3139 delete Alignment;
3140 return; // Ignore
3141 }
3142
3143 AlignmentVal = (unsigned) Val.getZExtValue();
3144 }
3145
3146 switch (Kind) {
3147 case Action::PPK_Default: // pack([n])
3148 PackContext.setAlignment(AlignmentVal);
3149 break;
3150
3151 case Action::PPK_Show: // pack(show)
3152 // Show the current alignment, making sure to show the right value
3153 // for the default.
3154 AlignmentVal = PackContext.getAlignment();
3155 // FIXME: This should come from the target.
3156 if (AlignmentVal == 0)
3157 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003158 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003159 break;
3160
3161 case Action::PPK_Push: // pack(push [, id] [, [n])
3162 PackContext.push(Name);
3163 // Set the new alignment if specified.
3164 if (Alignment)
3165 PackContext.setAlignment(AlignmentVal);
3166 break;
3167
3168 case Action::PPK_Pop: // pack(pop [, id] [, n])
3169 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3170 // "#pragma pack(pop, identifier, n) is undefined"
3171 if (Alignment && Name)
3172 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3173
3174 // Do the pop.
3175 if (!PackContext.pop(Name)) {
3176 // If a name was specified then failure indicates the name
3177 // wasn't found. Otherwise failure indicates the stack was
3178 // empty.
3179 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed,
3180 Name ? "no record matching name" : "stack empty");
3181
3182 // FIXME: Warn about popping named records as MSVC does.
3183 } else {
3184 // Pop succeeded, set the new alignment if specified.
3185 if (Alignment)
3186 PackContext.setAlignment(AlignmentVal);
3187 }
3188 break;
3189
3190 default:
3191 assert(0 && "Invalid #pragma pack kind.");
3192 }
3193}
3194
3195bool PragmaPackStack::pop(IdentifierInfo *Name) {
3196 if (Stack.empty())
3197 return false;
3198
3199 // If name is empty just pop top.
3200 if (!Name) {
3201 Alignment = Stack.back().first;
3202 Stack.pop_back();
3203 return true;
3204 }
3205
3206 // Otherwise, find the named record.
3207 for (unsigned i = Stack.size(); i != 0; ) {
3208 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003209 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003210 // Found it, pop up to and including this record.
3211 Alignment = Stack[i].first;
3212 Stack.erase(Stack.begin() + i, Stack.end());
3213 return true;
3214 }
3215 }
3216
3217 return false;
3218}