blob: 024ca8138a6a9c9b7e0fadffb1fddfee8e266c63 [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"
Douglas Gregore267ff32008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
29
Reid Spencer5f016e22007-07-11 17:01:13 +000030using namespace clang;
31
Douglas Gregor2def4832008-11-17 20:34:05 +000032Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +000033 const CXXScopeSpec *SS) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000034 DeclContext *DC = 0;
35 if (SS) {
36 if (SS->isInvalid())
37 return 0;
38 DC = static_cast<DeclContext*>(SS->getScopeRep());
39 }
40 Decl *IIDecl = LookupDecl(&II, Decl::IDNS_Ordinary, S, DC, false);
Steve Naroffb327ce02008-04-02 14:35:35 +000041
Douglas Gregor2ce52f32008-04-13 21:07:44 +000042 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
43 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregor72c3f312008-12-05 18:15:24 +000044 isa<TagDecl>(IIDecl) ||
45 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanianbece4ac2007-10-12 16:34:10 +000046 return IIDecl;
Steve Naroff3536b442007-09-06 21:24:23 +000047 return 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000048}
49
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000050DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000052 // A C++ out-of-line method will return to the file declaration context.
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000053 if (MD->isOutOfLineDefinition())
54 return MD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000055
56 // A C++ inline method is parsed *after* the topmost class it was declared in
57 // is fully parsed (it's "complete").
58 // The parsing of a C++ inline method happens at the declaration context of
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000059 // the topmost (non-nested) class it is lexically declared in.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000060 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
61 DC = MD->getParent();
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000062 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000063 DC = RD;
64
65 // Return the declaration context of the topmost class the inline method is
66 // declared in.
67 return DC;
68 }
69
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +000070 if (isa<ObjCMethodDecl>(DC))
71 return Context.getTranslationUnitDecl();
72
73 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(DC))
74 return SD->getLexicalDeclContext();
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000075
Argyrios Kyrtzidis77407b82008-11-19 18:01:13 +000076 return DC->getLexicalParent();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +000077}
78
Douglas Gregor44b43212008-12-11 16:49:14 +000079void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000080 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xue50897a2008-12-08 07:14:51 +000081 "The next DeclContext should be lexically contained in the current one.");
Chris Lattner9fdf9c62008-04-22 18:39:57 +000082 CurContext = DC;
Douglas Gregor44b43212008-12-11 16:49:14 +000083 S->setEntity(DC);
Chris Lattner0ed844b2008-04-04 06:12:32 +000084}
85
Chris Lattnerb048c982008-04-06 04:47:34 +000086void Sema::PopDeclContext() {
87 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor44b43212008-12-11 16:49:14 +000088
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +000089 CurContext = getContainingDC(CurContext);
Chris Lattner0ed844b2008-04-04 06:12:32 +000090}
91
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000092/// Add this decl to the scope shadowed decl chains.
93void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +000094 S->AddDecl(D);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +000095
96 // C++ [basic.scope]p4:
97 // -- exactly one declaration shall declare a class name or
98 // enumeration name that is not a typedef name and the other
99 // declarations shall all refer to the same object or
100 // enumerator, or all refer to functions and function templates;
101 // in this case the class name or enumeration name is hidden.
102 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
103 // We are pushing the name of a tag (enum or class).
Douglas Gregor44b43212008-12-11 16:49:14 +0000104 if (CurContext == TD->getDeclContext()) {
105 // We're pushing the tag into the current context, which might
106 // require some reshuffling in the identifier resolver.
107 IdentifierResolver::iterator
108 I = IdResolver.begin(TD->getIdentifier(), CurContext,
109 false/*LookInParentCtx*/);
110 if (I != IdResolver.end()) {
111 // There is already a declaration with the same name in the same
112 // scope. It must be found before we find the new declaration,
113 // so swap the order on the shadowed declaration chain.
114 IdResolver.AddShadowedDecl(TD, *I);
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000115
Douglas Gregor44b43212008-12-11 16:49:14 +0000116 // Add this declaration to the current context.
117 CurContext->addDecl(Context, TD);
118
119 return;
120 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000121 }
Argyrios Kyrtzidisf1af6a72008-10-22 23:08:24 +0000122 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000123 // We are pushing the name of a function, which might be an
124 // overloaded name.
Douglas Gregor44b43212008-12-11 16:49:14 +0000125 FunctionDecl *FD = cast<FunctionDecl>(D);
126 Decl *Prev = LookupDecl(FD->getDeclName(), Decl::IDNS_Ordinary, S,
127 FD->getDeclContext(), false, false);
128 if (Prev && (isa<OverloadedFunctionDecl>(Prev) || isa<FunctionDecl>(Prev))) {
129 // There is already a declaration with the same name in
130 // the same scope. It must be a function or an overloaded
131 // function.
132 OverloadedFunctionDecl* Ovl = dyn_cast<OverloadedFunctionDecl>(Prev);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000133 if (!Ovl) {
134 // We haven't yet overloaded this function. Take the existing
135 // FunctionDecl and put it into an OverloadedFunctionDecl.
136 Ovl = OverloadedFunctionDecl::Create(Context,
137 FD->getDeclContext(),
Douglas Gregor2def4832008-11-17 20:34:05 +0000138 FD->getDeclName());
Douglas Gregore267ff32008-12-11 20:41:00 +0000139 Ovl->addOverload(cast<FunctionDecl>(Prev));
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000140
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000141 // If there is a name binding for the existing FunctionDecl,
142 // remove it.
143 for (IdentifierResolver::iterator I
144 = IdResolver.begin(FD->getDeclName(), FD->getDeclContext(),
145 false/*LookInParentCtx*/),
146 E = IdResolver.end(); I != E; ++I) {
147 if (*I == Prev) {
148 IdResolver.RemoveDecl(*I);
149 S->RemoveDecl(*I);
150 break;
151 }
152 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000153
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000154 // Add the name binding for the OverloadedFunctionDecl.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000155 IdResolver.AddDecl(Ovl);
Douglas Gregor44b43212008-12-11 16:49:14 +0000156
157 // Update the context with the newly-created overloaded
158 // function set.
159 FD->getDeclContext()->insert(Context, Ovl);
160
161 S->AddDecl(Ovl);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000162 }
163
Douglas Gregor44b43212008-12-11 16:49:14 +0000164 // We added this function declaration to the scope earlier, but
165 // we don't want it there because it is part of the overloaded
166 // function declaration.
167 S->RemoveDecl(FD);
168
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000169 // We have an OverloadedFunctionDecl. Add the new FunctionDecl
170 // to its list of overloads.
171 Ovl->addOverload(FD);
172
Douglas Gregor44b43212008-12-11 16:49:14 +0000173 // Add this new function declaration to the declaration context.
174 CurContext->addDecl(Context, FD, false);
175
176 return;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000177 }
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000178 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000179
Douglas Gregore267ff32008-12-11 20:41:00 +0000180 // Add scoped declarations into their context, so that they can be
181 // found later. Declarations without a context won't be inserted
182 // into any context.
Douglas Gregor44b43212008-12-11 16:49:14 +0000183 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
184 CurContext->addDecl(Context, SD);
Douglas Gregor44b43212008-12-11 16:49:14 +0000185
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000186 IdResolver.AddDecl(D);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +0000187}
188
Steve Naroffb216c882007-10-09 22:01:59 +0000189void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattner31e05722007-08-26 06:24:45 +0000190 if (S->decl_empty()) return;
Douglas Gregor72c3f312008-12-05 18:15:24 +0000191 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
192 "Scope shouldn't contain decls!");
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000193
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
195 I != E; ++I) {
Steve Naroffc752d042007-09-13 18:10:37 +0000196 Decl *TmpD = static_cast<Decl*>(*I);
197 assert(TmpD && "This decl didn't get pushed??");
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000198
Douglas Gregor44b43212008-12-11 16:49:14 +0000199 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
200 NamedDecl *D = cast<NamedDecl>(TmpD);
Argyrios Kyrtzidis76435362008-06-10 01:32:09 +0000201
Douglas Gregor44b43212008-12-11 16:49:14 +0000202 if (!D->getDeclName()) continue;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000203
Douglas Gregor44b43212008-12-11 16:49:14 +0000204 // Remove this name from our lexical scope.
205 IdResolver.RemoveDecl(D);
Reid Spencer5f016e22007-07-11 17:01:13 +0000206 }
207}
208
Steve Naroffe8043c32008-04-01 23:04:06 +0000209/// getObjCInterfaceDecl - Look up a for a class declaration in the scope.
210/// return 0 if one not found.
Steve Naroffe8043c32008-04-01 23:04:06 +0000211ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff31102512008-04-02 18:30:49 +0000212 // The third "scope" argument is 0 since we aren't enabling lazy built-in
213 // creation from this context.
214 Decl *IDecl = LookupDecl(Id, Decl::IDNS_Ordinary, 0, false);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000215
Steve Naroffb327ce02008-04-02 14:35:35 +0000216 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahanian4cabdfc2007-10-12 19:38:20 +0000217}
218
Steve Naroffe8043c32008-04-01 23:04:06 +0000219/// LookupDecl - Look up the inner-most declaration in the specified
Reid Spencer5f016e22007-07-11 17:01:13 +0000220/// namespace.
Douglas Gregor2def4832008-11-17 20:34:05 +0000221Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000222 const DeclContext *LookupCtx,
Douglas Gregor44b43212008-12-11 16:49:14 +0000223 bool enableLazyBuiltinCreation,
Douglas Gregor0a59acb2008-12-16 00:38:16 +0000224 bool LookInParent) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000225 if (!Name) return 0;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000226 unsigned NS = NSI;
227 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
228 NS |= Decl::IDNS_Tag;
Chris Lattner7f925cc2008-04-11 07:00:53 +0000229
Douglas Gregore267ff32008-12-11 20:41:00 +0000230 if (LookupCtx == 0 &&
231 (!getLangOptions().CPlusPlus || (NS == Decl::IDNS_Label))) {
232 // Unqualified name lookup in C/Objective-C and name lookup for
233 // labels in C++ is purely lexical, so search in the
234 // declarations attached to the name.
235 assert(!LookupCtx && "Can't perform qualified name lookup here");
236 IdentifierResolver::iterator I
237 = IdResolver.begin(Name, CurContext, LookInParent);
238
239 // Scan up the scope chain looking for a decl that matches this
240 // identifier that is in the appropriate namespace. This search
241 // should not take long, as shadowing of names is uncommon, and
242 // deep shadowing is extremely uncommon.
243 for (; I != IdResolver.end(); ++I)
244 if ((*I)->getIdentifierNamespace() & NS)
245 return *I;
246 } else if (LookupCtx) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000247 assert(getLangOptions().CPlusPlus && "No qualified name lookup in C");
248
249 // Perform qualified name lookup into the LookupCtx.
250 // FIXME: Will need to look into base classes and such.
Douglas Gregore267ff32008-12-11 20:41:00 +0000251 DeclContext::lookup_const_iterator I, E;
252 for (llvm::tie(I, E) = LookupCtx->lookup(Context, Name); I != E; ++I)
253 if ((*I)->getIdentifierNamespace() & NS)
254 return *I;
255 } else {
Douglas Gregor44b43212008-12-11 16:49:14 +0000256 // Name lookup for ordinary names and tag names in C++ requires
257 // looking into scopes that aren't strictly lexical, and
258 // therefore we walk through the context as well as walking
259 // through the scopes.
260 IdentifierResolver::iterator
261 I = IdResolver.begin(Name, CurContext, true/*LookInParentCtx*/),
262 IEnd = IdResolver.end();
263 for (; S; S = S->getParent()) {
264 // Check whether the IdResolver has anything in this scope.
265 // FIXME: The isDeclScope check could be expensive. Can we do better?
266 for (; I != IEnd && S->isDeclScope(*I); ++I)
267 if ((*I)->getIdentifierNamespace() & NS)
268 return *I;
269
270 // If there is an entity associated with this scope, it's a
271 // DeclContext. We might need to perform qualified lookup into
272 // it.
273 DeclContext *Ctx = static_cast<DeclContext *>(S->getEntity());
274 while (Ctx && Ctx->isFunctionOrMethod())
275 Ctx = Ctx->getParent();
276 while (Ctx && (Ctx->isNamespace() || Ctx->isCXXRecord())) {
277 // Look for declarations of this name in this scope.
Douglas Gregore267ff32008-12-11 20:41:00 +0000278 DeclContext::lookup_const_iterator I, E;
279 for (llvm::tie(I, E) = Ctx->lookup(Context, Name); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000280 // FIXME: Cache this result in the IdResolver
Douglas Gregore267ff32008-12-11 20:41:00 +0000281 if ((*I)->getIdentifierNamespace() & NS)
282 return *I;
Douglas Gregor44b43212008-12-11 16:49:14 +0000283 }
284
285 Ctx = Ctx->getParent();
286 }
287
288 if (!LookInParent)
289 return 0;
290 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000291 }
Chris Lattner7f925cc2008-04-11 07:00:53 +0000292
Reid Spencer5f016e22007-07-11 17:01:13 +0000293 // If we didn't find a use of this identifier, and if the identifier
294 // corresponds to a compiler builtin, create the decl object for the builtin
295 // now, injecting it into translation unit scope, and return it.
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000296 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregor2def4832008-11-17 20:34:05 +0000297 IdentifierInfo *II = Name.getAsIdentifierInfo();
298 if (enableLazyBuiltinCreation && II &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000299 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroffb327ce02008-04-02 14:35:35 +0000300 // If this is a builtin on this (or all) targets, create the decl.
301 if (unsigned BuiltinID = II->getBuiltinID())
302 return LazilyCreateBuiltin((IdentifierInfo *)II, BuiltinID, S);
303 }
Douglas Gregor2def4832008-11-17 20:34:05 +0000304 if (getLangOptions().ObjC1 && II) {
Steve Naroffe8043c32008-04-01 23:04:06 +0000305 // @interface and @compatibility_alias introduce typedef-like names.
306 // Unlike typedef's, they can only be introduced at file-scope (and are
Steve Naroffc822ff42008-04-02 00:39:51 +0000307 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe8043c32008-04-01 23:04:06 +0000308 // other names in IDNS_Ordinary.
Steve Naroff31102512008-04-02 18:30:49 +0000309 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
310 if (IDI != ObjCInterfaceDecls.end())
311 return IDI->second;
Steve Naroffe8043c32008-04-01 23:04:06 +0000312 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
313 if (I != ObjCAliasDecls.end())
314 return I->second->getClassInterface();
315 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000316 }
317 return 0;
318}
319
Chris Lattner95e2c712008-05-05 22:18:14 +0000320void Sema::InitBuiltinVaListType() {
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000321 if (!Context.getBuiltinVaListType().isNull())
322 return;
323
324 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroffb327ce02008-04-02 14:35:35 +0000325 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroff733002f2007-10-18 22:17:45 +0000326 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000327 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
328}
329
Reid Spencer5f016e22007-07-11 17:01:13 +0000330/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
331/// lazily create a decl for it.
Chris Lattner22b73ba2007-10-10 23:42:28 +0000332ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
333 Scope *S) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000334 Builtin::ID BID = (Builtin::ID)bid;
335
Chris Lattnerbd7eb1c2008-09-28 05:54:29 +0000336 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson7c50aca2007-10-15 20:28:48 +0000337 InitBuiltinVaListType();
338
Anders Carlssonb2cf3572007-10-11 01:00:40 +0000339 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argyrios Kyrtzidisff898cd2008-04-17 14:47:13 +0000340 FunctionDecl *New = FunctionDecl::Create(Context,
341 Context.getTranslationUnitDecl(),
Chris Lattner0ed844b2008-04-04 06:12:32 +0000342 SourceLocation(), II, R,
Chris Lattnera98e58d2008-03-15 21:24:04 +0000343 FunctionDecl::Extern, false, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +0000344
Chris Lattner95e2c712008-05-05 22:18:14 +0000345 // Create Decl objects for each parameter, adding them to the
346 // FunctionDecl.
347 if (FunctionTypeProto *FT = dyn_cast<FunctionTypeProto>(R)) {
348 llvm::SmallVector<ParmVarDecl*, 16> Params;
349 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i)
350 Params.push_back(ParmVarDecl::Create(Context, New, SourceLocation(), 0,
351 FT->getArgType(i), VarDecl::None, 0,
352 0));
353 New->setParams(&Params[0], Params.size());
354 }
355
356
357
Chris Lattner7f925cc2008-04-11 07:00:53 +0000358 // TUScope is the translation-unit scope to insert this function into.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000359 PushOnScopeChains(New, TUScope);
Reid Spencer5f016e22007-07-11 17:01:13 +0000360 return New;
361}
362
Sebastian Redlc42e1182008-11-11 11:37:55 +0000363/// GetStdNamespace - This method gets the C++ "std" namespace. This is where
364/// everything from the standard library is defined.
365NamespaceDecl *Sema::GetStdNamespace() {
366 if (!StdNamespace) {
Chris Lattner8edea832008-11-20 05:45:14 +0000367 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlc42e1182008-11-11 11:37:55 +0000368 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattner8edea832008-11-20 05:45:14 +0000369 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlc42e1182008-11-11 11:37:55 +0000370 0, Global, /*enableLazyBuiltinCreation=*/false);
371 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
372 }
373 return StdNamespace;
374}
375
Reid Spencer5f016e22007-07-11 17:01:13 +0000376/// MergeTypeDefDecl - We just parsed a typedef 'New' which has the same name
377/// and scope as a previous declaration 'Old'. Figure out how to resolve this
378/// situation, merging decls or emitting diagnostics as appropriate.
379///
Steve Naroffe8043c32008-04-01 23:04:06 +0000380TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff2b255c42008-09-09 14:32:20 +0000381 // Allow multiple definitions for ObjC built-in typedefs.
382 // FIXME: Verify the underlying types are equivalent!
383 if (getLangOptions().ObjC1) {
Chris Lattner2bac0f62008-11-20 05:41:43 +0000384 const IdentifierInfo *TypeID = New->getIdentifier();
385 switch (TypeID->getLength()) {
386 default: break;
387 case 2:
388 if (!TypeID->isStr("id"))
389 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000390 Context.setObjCIdType(New);
391 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000392 case 5:
393 if (!TypeID->isStr("Class"))
394 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000395 Context.setObjCClassType(New);
396 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000397 case 3:
398 if (!TypeID->isStr("SEL"))
399 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000400 Context.setObjCSelType(New);
401 return New;
Chris Lattner2bac0f62008-11-20 05:41:43 +0000402 case 8:
403 if (!TypeID->isStr("Protocol"))
404 break;
Steve Naroff2b255c42008-09-09 14:32:20 +0000405 Context.setObjCProtoType(New->getUnderlyingType());
406 return New;
407 }
408 // Fall through - the typedef name was not a builtin type.
409 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000410 // Verify the old decl was also a typedef.
411 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
412 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000413 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000414 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000415 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000416 return New;
417 }
418
Chris Lattner99cb9972008-07-25 18:44:27 +0000419 // If the typedef types are not identical, reject them in all languages and
420 // with any extensions enabled.
421 if (Old->getUnderlyingType() != New->getUnderlyingType() &&
422 Context.getCanonicalType(Old->getUnderlyingType()) !=
423 Context.getCanonicalType(New->getUnderlyingType())) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000424 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattnerd1625842008-11-24 06:25:27 +0000425 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000426 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner99cb9972008-07-25 18:44:27 +0000427 return Old;
428 }
429
Eli Friedman54ecfce2008-06-11 06:20:39 +0000430 if (getLangOptions().Microsoft) return New;
431
Douglas Gregorbbe27432008-11-21 16:29:06 +0000432 // C++ [dcl.typedef]p2:
433 // In a given non-class scope, a typedef specifier can be used to
434 // redefine the name of any type declared in that scope to refer
435 // to the type to which it already refers.
436 if (getLangOptions().CPlusPlus && !isa<CXXRecordDecl>(CurContext))
437 return New;
438
439 // In C, redeclaration of a type is a constraint violation (6.7.2.3p1).
Steve Naroff4c49a6c2008-01-30 23:46:05 +0000440 // Apparently GCC, Intel, and Sun all silently ignore the redeclaration if
441 // *either* declaration is in a system header. The code below implements
442 // this adhoc compatibility rule. FIXME: The following code will not
443 // work properly when compiling ".i" files (containing preprocessed output).
Daniel Dunbar2fe09972008-09-12 18:10:20 +0000444 if (PP.getDiagnostics().getSuppressSystemWarnings()) {
445 SourceManager &SrcMgr = Context.getSourceManager();
446 if (SrcMgr.isInSystemHeader(Old->getLocation()))
447 return New;
448 if (SrcMgr.isInSystemHeader(New->getLocation()))
449 return New;
450 }
Eli Friedman54ecfce2008-06-11 06:20:39 +0000451
Chris Lattner08631c52008-11-23 21:45:46 +0000452 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000453 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000454 return New;
455}
456
Chris Lattner6b6b5372008-06-26 18:38:35 +0000457/// DeclhasAttr - returns true if decl Declaration already has the target
458/// attribute.
Chris Lattnerddee4232008-03-03 03:28:21 +0000459static bool DeclHasAttr(const Decl *decl, const Attr *target) {
460 for (const Attr *attr = decl->getAttrs(); attr; attr = attr->getNext())
461 if (attr->getKind() == target->getKind())
462 return true;
463
464 return false;
465}
466
467/// MergeAttributes - append attributes from the Old decl to the New one.
468static void MergeAttributes(Decl *New, Decl *Old) {
469 Attr *attr = const_cast<Attr*>(Old->getAttrs()), *tmp;
470
Chris Lattnerddee4232008-03-03 03:28:21 +0000471 while (attr) {
472 tmp = attr;
473 attr = attr->getNext();
474
475 if (!DeclHasAttr(New, tmp)) {
476 New->addAttr(tmp);
477 } else {
478 tmp->setNext(0);
479 delete(tmp);
480 }
481 }
Nuno Lopes9141bee2008-06-01 22:53:53 +0000482
483 Old->invalidateAttrs();
Chris Lattnerddee4232008-03-03 03:28:21 +0000484}
485
Chris Lattner04421082008-04-08 04:40:51 +0000486/// MergeFunctionDecl - We just parsed a function 'New' from
487/// declarator D which has the same name and scope as a previous
488/// declaration 'Old'. Figure out how to resolve this situation,
489/// merging decls or emitting diagnostics as appropriate.
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000490/// Redeclaration will be set true if this New is a redeclaration OldD.
491///
492/// In C++, New and Old must be declarations that are not
493/// overloaded. Use IsOverload to determine whether New and Old are
494/// overloaded, and to select the Old declaration that New should be
495/// merged with.
Douglas Gregorf0097952008-04-21 02:02:58 +0000496FunctionDecl *
497Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000498 assert(!isa<OverloadedFunctionDecl>(OldD) &&
499 "Cannot merge with an overloaded function declaration");
500
Douglas Gregorf0097952008-04-21 02:02:58 +0000501 Redeclaration = false;
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 // Verify the old decl was also a function.
503 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
504 if (!Old) {
Chris Lattner5dc266a2008-11-20 06:13:02 +0000505 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000506 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000507 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 return New;
509 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000510
511 // Determine whether the previous declaration was a definition,
512 // implicit declaration, or a declaration.
513 diag::kind PrevDiag;
514 if (Old->isThisDeclarationADefinition())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000515 PrevDiag = diag::note_previous_definition;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000516 else if (Old->isImplicit())
Chris Lattner5f4a6822008-11-23 23:12:31 +0000517 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000518 else
Chris Lattner5f4a6822008-11-23 23:12:31 +0000519 PrevDiag = diag::note_previous_declaration;
Chris Lattner04421082008-04-08 04:40:51 +0000520
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000521 QualType OldQType = Context.getCanonicalType(Old->getType());
522 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner55196442007-11-20 19:04:50 +0000523
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000524 if (getLangOptions().CPlusPlus) {
525 // (C++98 13.1p2):
526 // Certain function declarations cannot be overloaded:
527 // -- Function declarations that differ only in the return type
528 // cannot be overloaded.
529 QualType OldReturnType
530 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
531 QualType NewReturnType
532 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
533 if (OldReturnType != NewReturnType) {
534 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
535 Diag(Old->getLocation(), PrevDiag);
536 return New;
537 }
538
539 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
540 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
541 if (OldMethod && NewMethod) {
542 // -- Member function declarations with the same name and the
543 // same parameter types cannot be overloaded if any of them
544 // is a static member function declaration.
545 if (OldMethod->isStatic() || NewMethod->isStatic()) {
546 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
547 Diag(Old->getLocation(), PrevDiag);
548 return New;
549 }
Douglas Gregor9e7d9de2008-12-15 21:24:18 +0000550
551 // C++ [class.mem]p1:
552 // [...] A member shall not be declared twice in the
553 // member-specification, except that a nested class or member
554 // class template can be declared and then later defined.
555 if (OldMethod->getLexicalDeclContext() ==
556 NewMethod->getLexicalDeclContext()) {
557 unsigned NewDiag;
558 if (isa<CXXConstructorDecl>(OldMethod))
559 NewDiag = diag::err_constructor_redeclared;
560 else if (isa<CXXDestructorDecl>(NewMethod))
561 NewDiag = diag::err_destructor_redeclared;
562 else if (isa<CXXConversionDecl>(NewMethod))
563 NewDiag = diag::err_conv_function_redeclared;
564 else
565 NewDiag = diag::err_member_redeclared;
566
567 Diag(New->getLocation(), NewDiag);
568 Diag(Old->getLocation(), PrevDiag);
569 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +0000570 }
571
572 // (C++98 8.3.5p3):
573 // All declarations for a function shall agree exactly in both the
574 // return type and the parameter-type-list.
575 if (OldQType == NewQType) {
576 // We have a redeclaration.
577 MergeAttributes(New, Old);
578 Redeclaration = true;
579 return MergeCXXFunctionDecl(New, Old);
580 }
581
582 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000583 }
Chris Lattner04421082008-04-08 04:40:51 +0000584
585 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000586 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000587 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000588 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000589 MergeAttributes(New, Old);
590 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000591 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000592 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000593
Steve Naroff837618c2008-01-16 15:01:34 +0000594 // A function that has already been declared has been redeclared or defined
595 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000596
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
598 // TODO: This is totally simplistic. It should handle merging functions
599 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000600 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000601 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000602 return New;
603}
604
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000605/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000606static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000607 if (VD->isFileVarDecl())
608 return (!VD->getInit() &&
609 (VD->getStorageClass() == VarDecl::None ||
610 VD->getStorageClass() == VarDecl::Static));
611 return false;
612}
613
614/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
615/// when dealing with C "tentative" external object definitions (C99 6.9.2).
616void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
617 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000618 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000619
620 for (IdentifierResolver::iterator
621 I = IdResolver.begin(VD->getIdentifier(),
622 VD->getDeclContext(), false/*LookInParentCtx*/),
623 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000624 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000625 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
626
Steve Narofff855e6f2008-08-10 15:20:13 +0000627 // Handle the following case:
628 // int a[10];
629 // int a[]; - the code below makes sure we set the correct type.
630 // int a[11]; - this is an error, size isn't 10.
631 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
632 OldDecl->getType()->isConstantArrayType())
633 VD->setType(OldDecl->getType());
634
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000635 // Check for "tentative" definitions. We can't accomplish this in
636 // MergeVarDecl since the initializer hasn't been attached.
637 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
638 continue;
639
640 // Handle __private_extern__ just like extern.
641 if (OldDecl->getStorageClass() != VarDecl::Extern &&
642 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
643 VD->getStorageClass() != VarDecl::Extern &&
644 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000645 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000646 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000647 }
648 }
649 }
650}
651
Reid Spencer5f016e22007-07-11 17:01:13 +0000652/// MergeVarDecl - We just parsed a variable 'New' which has the same name
653/// and scope as a previous declaration 'Old'. Figure out how to resolve this
654/// situation, merging decls or emitting diagnostics as appropriate.
655///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000656/// Tentative definition rules (C99 6.9.2p2) are checked by
657/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
658/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000659///
Steve Naroffe8043c32008-04-01 23:04:06 +0000660VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000661 // Verify the old decl was also a variable.
662 VarDecl *Old = dyn_cast<VarDecl>(OldD);
663 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000664 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000665 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000666 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000667 return New;
668 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000669
670 MergeAttributes(New, Old);
671
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000673 QualType OldCType = Context.getCanonicalType(Old->getType());
674 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000675 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000676 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000677 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000678 return New;
679 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000680 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
681 if (New->getStorageClass() == VarDecl::Static &&
682 (Old->getStorageClass() == VarDecl::None ||
683 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000684 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000685 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000686 return New;
687 }
688 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
689 if (New->getStorageClass() != VarDecl::Static &&
690 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000691 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000692 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000693 return New;
694 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000695 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
696 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000697 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000698 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 }
700 return New;
701}
702
Chris Lattner04421082008-04-08 04:40:51 +0000703/// CheckParmsForFunctionDef - Check that the parameters of the given
704/// function are appropriate for the definition of a function. This
705/// takes care of any checks that cannot be performed on the
706/// declaration itself, e.g., that the types of each of the function
707/// parameters are complete.
708bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
709 bool HasInvalidParm = false;
710 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
711 ParmVarDecl *Param = FD->getParamDecl(p);
712
713 // C99 6.7.5.3p4: the parameters in a parameter type list in a
714 // function declarator that is part of a function definition of
715 // that function shall not have incomplete type.
716 if (Param->getType()->isIncompleteType() &&
717 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000718 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000719 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000720 Param->setInvalidDecl();
721 HasInvalidParm = true;
722 }
Chris Lattner777f07b2008-12-17 07:32:46 +0000723
724 // C99 6.9.1p5: If the declarator includes a parameter type list, the
725 // declaration of each parameter shall include an identifier.
726 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
727 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner04421082008-04-08 04:40:51 +0000728 }
729
730 return HasInvalidParm;
731}
732
Reid Spencer5f016e22007-07-11 17:01:13 +0000733/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
734/// no declarator (e.g. "struct foo;") is parsed.
735Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
736 // TODO: emit error on 'int;' or 'const enum foo;'.
737 // TODO: emit error on 'typedef int;'
738 // if (!DS.isMissingDeclaratorOk()) Diag(...);
739
Steve Naroff92199282007-11-17 21:37:36 +0000740 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000741}
742
Steve Naroffd0091aa2008-01-10 22:15:12 +0000743bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000744 // Get the type before calling CheckSingleAssignmentConstraints(), since
745 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000746 QualType InitType = Init->getType();
Douglas Gregor45920e82008-12-19 17:40:08 +0000747
748 if (getLangOptions().CPlusPlus)
749 return PerformCopyInitialization(Init, DeclType, "initializing");
750
Chris Lattner5cf216b2008-01-04 18:04:52 +0000751 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
752 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
753 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000754}
755
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000756bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000757 const ArrayType *AT = Context.getAsArrayType(DeclT);
758
759 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000760 // C99 6.7.8p14. We have an array of character type with unknown size
761 // being initialized to a string literal.
762 llvm::APSInt ConstVal(32);
763 ConstVal = strLiteral->getByteLength() + 1;
764 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000765 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000766 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000767 } else {
768 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000769 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000770 // FIXME: Avoid truncation for 64-bit length strings.
771 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000772 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000773 diag::warn_initializer_string_for_char_array_too_long)
774 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000775 }
776 // Set type from "char *" to "constant array of char".
777 strLiteral->setType(DeclT);
778 // For now, we always return false (meaning success).
779 return false;
780}
781
782StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000783 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000784 if (AT && AT->getElementType()->isCharType()) {
785 return dyn_cast<StringLiteral>(Init);
786 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000787 return 0;
788}
789
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000790bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
791 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000792 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +0000793 if (DeclType->isDependentType() || Init->isTypeDependent())
794 return false;
795
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000796 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000797 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000798 // (8.3.2), shall be initialized by an object, or function, of
799 // type T or by an object that can be converted into a T.
800 if (DeclType->isReferenceType())
801 return CheckReferenceInit(Init, DeclType);
802
Steve Naroffca107302008-01-21 23:53:58 +0000803 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
804 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000805 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000806 return Diag(InitLoc, diag::err_variable_object_no_init)
807 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000808
Steve Naroff2fdc3742007-12-10 22:44:33 +0000809 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
810 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000811 // FIXME: Handle wide strings
812 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
813 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000814
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000815 // C++ [dcl.init]p14:
816 // -- If the destination type is a (possibly cv-qualified) class
817 // type:
818 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
819 QualType DeclTypeC = Context.getCanonicalType(DeclType);
820 QualType InitTypeC = Context.getCanonicalType(Init->getType());
821
822 // -- If the initialization is direct-initialization, or if it is
823 // copy-initialization where the cv-unqualified version of the
824 // source type is the same class as, or a derived class of, the
825 // class of the destination, constructors are considered.
826 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
827 IsDerivedFrom(InitTypeC, DeclTypeC)) {
828 CXXConstructorDecl *Constructor
829 = PerformInitializationByConstructor(DeclType, &Init, 1,
830 InitLoc, Init->getSourceRange(),
831 InitEntity, IK_Copy);
832 return Constructor == 0;
833 }
834
835 // -- Otherwise (i.e., for the remaining copy-initialization
836 // cases), user-defined conversion sequences that can
837 // convert from the source type to the destination type or
838 // (when a conversion function is used) to a derived class
839 // thereof are enumerated as described in 13.3.1.4, and the
840 // best one is chosen through overload resolution
841 // (13.3). If the conversion cannot be done or is
842 // ambiguous, the initialization is ill-formed. The
843 // function selected is called with the initializer
844 // expression as its argument; if the function is a
845 // constructor, the call initializes a temporary of the
846 // destination type.
847 // FIXME: We're pretending to do copy elision here; return to
848 // this when we have ASTs for such things.
Douglas Gregor45920e82008-12-19 17:40:08 +0000849 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000850 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000851
852 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000853 << DeclType << InitEntity << "initializing"
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000854 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000855 }
856
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000857 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000858 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000859 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
860 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000861
Steve Naroffd0091aa2008-01-10 22:15:12 +0000862 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000863 } else if (getLangOptions().CPlusPlus) {
864 // C++ [dcl.init]p14:
865 // [...] If the class is an aggregate (8.5.1), and the initializer
866 // is a brace-enclosed list, see 8.5.1.
867 //
868 // Note: 8.5.1 is handled below; here, we diagnose the case where
869 // we have an initializer list and a destination type that is not
870 // an aggregate.
871 // FIXME: In C++0x, this is yet another form of initialization.
872 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
873 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
874 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000875 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000876 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000877 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000878 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000879
Steve Naroff0cca7492008-05-01 22:18:59 +0000880 InitListChecker CheckInitList(this, InitList, DeclType);
881 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000882}
883
Douglas Gregor10bd3682008-11-17 22:58:34 +0000884/// GetNameForDeclarator - Determine the full declaration name for the
885/// given Declarator.
886DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
887 switch (D.getKind()) {
888 case Declarator::DK_Abstract:
889 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
890 return DeclarationName();
891
892 case Declarator::DK_Normal:
893 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
894 return DeclarationName(D.getIdentifier());
895
896 case Declarator::DK_Constructor: {
897 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
898 Ty = Context.getCanonicalType(Ty);
899 return Context.DeclarationNames.getCXXConstructorName(Ty);
900 }
901
902 case Declarator::DK_Destructor: {
903 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
904 Ty = Context.getCanonicalType(Ty);
905 return Context.DeclarationNames.getCXXDestructorName(Ty);
906 }
907
908 case Declarator::DK_Conversion: {
909 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
910 Ty = Context.getCanonicalType(Ty);
911 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
912 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000913
914 case Declarator::DK_Operator:
915 assert(D.getIdentifier() == 0 && "operator names have no identifier");
916 return Context.DeclarationNames.getCXXOperatorName(
917 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000918 }
919
920 assert(false && "Unknown name kind");
921 return DeclarationName();
922}
923
Douglas Gregor584049d2008-12-15 23:53:10 +0000924/// isNearlyMatchingMemberFunction - Determine whether the C++ member
925/// functions Declaration and Definition are "nearly" matching. This
926/// heuristic is used to improve diagnostics in the case where an
927/// out-of-line member function definition doesn't match any
928/// declaration within the class.
929static bool isNearlyMatchingMemberFunction(ASTContext &Context,
930 FunctionDecl *Declaration,
931 FunctionDecl *Definition) {
932 if (Declaration->param_size() != Definition->param_size())
933 return false;
934 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
935 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
936 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
937
938 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
939 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
940 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
941 return false;
942 }
943
944 return true;
945}
946
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000947Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +0000948Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
949 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +0000950 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000951 DeclarationName Name = GetNameForDeclarator(D);
952
Chris Lattnere80a59c2007-07-25 00:24:17 +0000953 // All of these full declarators require an identifier. If it doesn't have
954 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000955 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000956 if (!D.getInvalidType()) // Reject this if we think it is valid.
957 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000958 diag::err_declarator_need_ident)
959 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000960 return 0;
961 }
962
Chris Lattner31e05722007-08-26 06:24:45 +0000963 // The scope passed in may not be a decl scope. Zip up the scope tree until
964 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +0000965 while ((S->getFlags() & Scope::DeclScope) == 0 ||
966 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +0000967 S = S->getParent();
968
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000969 DeclContext *DC;
970 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000971 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000972 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000973
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000974 // See if this is a redefinition of a variable in the same scope.
975 if (!D.getCXXScopeSpec().isSet()) {
976 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +0000977 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000978 } else { // Something like "int foo::x;"
979 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000980 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000981
982 // C++ 7.3.1.2p2:
983 // Members (including explicit specializations of templates) of a named
984 // namespace can also be defined outside that namespace by explicit
985 // qualification of the name being defined, provided that the entity being
986 // defined was already declared in the namespace and the definition appears
987 // after the point of declaration in a namespace that encloses the
988 // declarations namespace.
989 //
Douglas Gregor584049d2008-12-15 23:53:10 +0000990 // Note that we only check the context at this point. We don't yet
991 // have enough information to make sure that PrevDecl is actually
992 // the declaration we want to match. For example, given:
993 //
Douglas Gregor9d350972008-12-12 08:25:50 +0000994 // class X {
995 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +0000996 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +0000997 // };
998 //
Douglas Gregor584049d2008-12-15 23:53:10 +0000999 // void X::f(int) { } // ill-formed
1000 //
1001 // In this case, PrevDecl will point to the overload set
1002 // containing the two f's declared in X, but neither of them
1003 // matches.
1004 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001005 // The qualifying scope doesn't enclose the original declaration.
1006 // Emit diagnostic based on current scope.
1007 SourceLocation L = D.getIdentifierLoc();
1008 SourceRange R = D.getCXXScopeSpec().getRange();
1009 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001010 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001011 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001012 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001013 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001014 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001015 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001016 }
1017 }
1018
Douglas Gregorf57172b2008-12-08 18:40:42 +00001019 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001020 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001021 InvalidDecl = InvalidDecl
1022 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001023 // Just pretend that we didn't see the previous declaration.
1024 PrevDecl = 0;
1025 }
1026
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001027 // In C++, the previous declaration we find might be a tag type
1028 // (class or enum). In this case, the new declaration will hide the
1029 // tag type.
1030 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1031 PrevDecl = 0;
1032
Chris Lattner41af0932007-11-14 06:34:38 +00001033 QualType R = GetTypeForDeclarator(D, S);
1034 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1035
Reid Spencer5f016e22007-07-11 17:01:13 +00001036 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001037 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1038 if (D.getCXXScopeSpec().isSet()) {
1039 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1040 << D.getCXXScopeSpec().getRange();
1041 InvalidDecl = true;
1042 // Pretend we didn't see the scope specifier.
1043 DC = 0;
1044 }
1045
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001046 // Check that there are no default arguments (C++ only).
1047 if (getLangOptions().CPlusPlus)
1048 CheckExtraCXXDefaultArguments(D);
1049
Chris Lattner41af0932007-11-14 06:34:38 +00001050 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001051 if (!NewTD) return 0;
1052
1053 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001054 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001055 // Merge the decl with the existing one if appropriate. If the decl is
1056 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001057 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001058 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1059 if (NewTD == 0) return 0;
1060 }
1061 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001062 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001063 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1064 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001065 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001066 if (NewTD->getUnderlyingType()->isVariableArrayType())
1067 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1068 else
1069 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1070
Steve Naroffd7444aa2007-08-31 17:20:07 +00001071 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001072 }
1073 }
Chris Lattner41af0932007-11-14 06:34:38 +00001074 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001075 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001076 switch (D.getDeclSpec().getStorageClassSpec()) {
1077 default: assert(0 && "Unknown storage class!");
1078 case DeclSpec::SCS_auto:
1079 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001080 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001081 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001082 InvalidDecl = true;
1083 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001084 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1085 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1086 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001087 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001088 }
1089
Chris Lattnera98e58d2008-03-15 21:24:04 +00001090 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001091 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001092 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1093
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001094 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001095 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001096 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001097 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001098 "Constructors can only be declared in a member context");
1099
Douglas Gregor42a552f2008-11-05 20:51:48 +00001100 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001101
1102 // Create the new declaration
1103 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001104 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001105 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001106 isExplicit, isInline,
1107 /*isImplicitlyDeclared=*/false);
1108
Douglas Gregor42a552f2008-11-05 20:51:48 +00001109 if (isInvalidDecl)
1110 NewFD->setInvalidDecl();
1111 } else if (D.getKind() == Declarator::DK_Destructor) {
1112 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001113 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001114 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001115
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001116 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001117 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001118 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001119 isInline,
1120 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001121
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001122 if (isInvalidDecl)
1123 NewFD->setInvalidDecl();
1124 } else {
1125 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1126 // Create a FunctionDecl to satisfy the function definition parsing
1127 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001128 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001129 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001130 // FIXME: Move to DeclGroup...
1131 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001132 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001133 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001134 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001135 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001136 Diag(D.getIdentifierLoc(),
1137 diag::err_conv_function_not_member);
1138 return 0;
1139 } else {
1140 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1141
1142 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001143 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001144 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001145 isInline, isExplicit);
1146
1147 if (isInvalidDecl)
1148 NewFD->setInvalidDecl();
1149 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001150 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001151 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001152 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001153 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001154 (SC == FunctionDecl::Static), isInline,
1155 LastDeclarator);
1156 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001157 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001158 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001159 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001160 // FIXME: Move to DeclGroup...
1161 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001162 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001163
Ted Kremenekf5c93c12008-02-27 22:18:07 +00001164 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001165 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +00001166
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001167 // Set the lexical context. If the declarator has a C++
1168 // scope specifier, the lexical context will be different
1169 // from the semantic context.
1170 NewFD->setLexicalDeclContext(CurContext);
1171
Daniel Dunbara80f8742008-08-05 01:35:17 +00001172 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001173 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001174 // The parser guarantees this is a string.
1175 StringLiteral *SE = cast<StringLiteral>(E);
1176 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1177 SE->getByteLength())));
1178 }
1179
Chris Lattner04421082008-04-08 04:40:51 +00001180 // Copy the parameter declarations from the declarator D to
1181 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001182 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001183 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1184
1185 // Create Decl objects for each parameter, adding them to the
1186 // FunctionDecl.
1187 llvm::SmallVector<ParmVarDecl*, 16> Params;
1188
1189 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1190 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001191 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001192 // We let through "const void" here because Sema::GetTypeForDeclarator
1193 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001194 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1195 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001196 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1197 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001198 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1199
Chris Lattnerdef026a2008-04-10 02:26:16 +00001200 // In C++, the empty parameter-type-list must be spelled "void"; a
1201 // typedef of void is not permitted.
1202 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001203 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001204 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1205 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001206 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001207 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1208 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1209 }
1210
1211 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001212 } else if (R->getAsTypedefType()) {
1213 // When we're declaring a function with a typedef, as in the
1214 // following example, we'll need to synthesize (unnamed)
1215 // parameters for use in the declaration.
1216 //
1217 // @code
1218 // typedef void fn(int);
1219 // fn f;
1220 // @endcode
1221 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1222 if (!FT) {
1223 // This is a typedef of a function with no prototype, so we
1224 // don't need to do anything.
1225 } else if ((FT->getNumArgs() == 0) ||
1226 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1227 FT->getArgType(0)->isVoidType())) {
1228 // This is a zero-argument function. We don't need to do anything.
1229 } else {
1230 // Synthesize a parameter for each argument type.
1231 llvm::SmallVector<ParmVarDecl*, 16> Params;
1232 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1233 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001234 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001235 SourceLocation(), 0,
1236 *ArgType, VarDecl::None,
1237 0, 0));
1238 }
1239
1240 NewFD->setParams(&Params[0], Params.size());
1241 }
Chris Lattner04421082008-04-08 04:40:51 +00001242 }
1243
Douglas Gregor72b505b2008-12-16 21:30:33 +00001244 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1245 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001246 else if (isa<CXXDestructorDecl>(NewFD))
1247 cast<CXXRecordDecl>(NewFD->getParent())->setUserDeclaredDestructor(true);
1248 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001249 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001250
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001251 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1252 if (NewFD->isOverloadedOperator() &&
1253 CheckOverloadedOperatorDeclaration(NewFD))
1254 NewFD->setInvalidDecl();
1255
Steve Naroffffce4d52008-01-09 23:34:55 +00001256 // Merge the decl with the existing one if appropriate. Since C functions
1257 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001258 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001259 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001260 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001261
1262 // If C++, determine whether NewFD is an overload of PrevDecl or
1263 // a declaration that requires merging. If it's an overload,
1264 // there's no more work to do here; we'll just add the new
1265 // function to the scope.
1266 OverloadedFunctionDecl::function_iterator MatchedDecl;
1267 if (!getLangOptions().CPlusPlus ||
1268 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1269 Decl *OldDecl = PrevDecl;
1270
1271 // If PrevDecl was an overloaded function, extract the
1272 // FunctionDecl that matched.
1273 if (isa<OverloadedFunctionDecl>(PrevDecl))
1274 OldDecl = *MatchedDecl;
1275
1276 // NewFD and PrevDecl represent declarations that need to be
1277 // merged.
1278 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1279
1280 if (NewFD == 0) return 0;
1281 if (Redeclaration) {
1282 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1283
1284 if (OldDecl == PrevDecl) {
1285 // Remove the name binding for the previous
Douglas Gregor44b43212008-12-11 16:49:14 +00001286 // declaration.
1287 if (S->isDeclScope(PrevDecl)) {
1288 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1289 S->RemoveDecl(PrevDecl);
1290 }
1291
1292 // Introduce the new binding for this declaration.
1293 IdResolver.AddDecl(NewFD);
1294 if (getLangOptions().CPlusPlus && NewFD->getParent())
1295 NewFD->getParent()->insert(Context, NewFD);
1296
1297 // Add the redeclaration to the current scope, since we'll
1298 // be skipping PushOnScopeChains.
1299 S->AddDecl(NewFD);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001300 } else {
1301 // We need to update the OverloadedFunctionDecl with the
1302 // latest declaration of this function, so that name
1303 // lookup will always refer to the latest declaration of
1304 // this function.
1305 *MatchedDecl = NewFD;
Douglas Gregor44b43212008-12-11 16:49:14 +00001306 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001307
Douglas Gregor44b43212008-12-11 16:49:14 +00001308 if (getLangOptions().CPlusPlus) {
1309 // Add this declaration to the current context.
1310 CurContext->addDecl(Context, NewFD, false);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001311
Douglas Gregor44b43212008-12-11 16:49:14 +00001312 // Check default arguments now that we have merged decls.
1313 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001314
1315 // An out-of-line member function declaration must also be a
1316 // definition (C++ [dcl.meaning]p1).
1317 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1318 !InvalidDecl) {
1319 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1320 << D.getCXXScopeSpec().getRange();
1321 NewFD->setInvalidDecl();
1322 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001323 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001324
Douglas Gregor44b43212008-12-11 16:49:14 +00001325 return NewFD;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001326 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001327 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001328
1329 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1330 // The user tried to provide an out-of-line definition for a
1331 // member function, but there was no such member function
1332 // declared (C++ [class.mfct]p2). For example:
1333 //
1334 // class X {
1335 // void f() const;
1336 // };
1337 //
1338 // void X::f() { } // ill-formed
1339 //
1340 // Complain about this problem, and attempt to suggest close
1341 // matches (e.g., those that differ only in cv-qualifiers and
1342 // whether the parameter types are references).
1343 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1344 << cast<CXXRecordDecl>(DC)->getDeclName()
1345 << D.getCXXScopeSpec().getRange();
1346 InvalidDecl = true;
1347
1348 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1349 if (!PrevDecl) {
1350 // Nothing to suggest.
1351 } else if (OverloadedFunctionDecl *Ovl
1352 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1353 for (OverloadedFunctionDecl::function_iterator
1354 Func = Ovl->function_begin(),
1355 FuncEnd = Ovl->function_end();
1356 Func != FuncEnd; ++Func) {
1357 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1358 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1359
1360 }
1361 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1362 // Suggest this no matter how mismatched it is; it's the only
1363 // thing we have.
1364 unsigned diag;
1365 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1366 diag = diag::note_member_def_close_match;
1367 else if (Method->getBody())
1368 diag = diag::note_previous_definition;
1369 else
1370 diag = diag::note_previous_declaration;
1371 Diag(Method->getLocation(), diag);
1372 }
1373
1374 PrevDecl = 0;
1375 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001376 }
1377 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001378
Douglas Gregor584049d2008-12-15 23:53:10 +00001379 if (getLangOptions().CPlusPlus) {
1380 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001381 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001382
1383 // An out-of-line member function declaration must also be a
1384 // definition (C++ [dcl.meaning]p1).
1385 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet()) {
1386 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1387 << D.getCXXScopeSpec().getRange();
1388 InvalidDecl = true;
1389 }
1390 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001391 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001392 // Check that there are no default arguments (C++ only).
1393 if (getLangOptions().CPlusPlus)
1394 CheckExtraCXXDefaultArguments(D);
1395
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001396 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001397 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1398 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001399 InvalidDecl = true;
1400 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001401
1402 VarDecl *NewVD;
1403 VarDecl::StorageClass SC;
1404 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001405 default: assert(0 && "Unknown storage class!");
1406 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1407 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1408 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1409 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1410 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1411 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001412 case DeclSpec::SCS_mutable:
1413 // mutable can only appear on non-static class members, so it's always
1414 // an error here
1415 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1416 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001417 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001418 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001419 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001420
1421 IdentifierInfo *II = Name.getAsIdentifierInfo();
1422 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001423 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1424 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001425 return 0;
1426 }
1427
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001428 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001429 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001430 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001431 D.getIdentifierLoc(), II,
1432 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001433 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001434 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001435 if (S->getFnParent() == 0) {
1436 // C99 6.9p2: The storage-class specifiers auto and register shall not
1437 // appear in the declaration specifiers in an external declaration.
1438 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001439 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001440 InvalidDecl = true;
1441 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001442 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001443 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1444 II, R, SC, LastDeclarator,
1445 // FIXME: Move to DeclGroup...
1446 D.getDeclSpec().getSourceRange().getBegin());
1447 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001448 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001449 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001450 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001451
Daniel Dunbara735ad82008-08-06 00:03:29 +00001452 // Handle GNU asm-label extension (encoded as an attribute).
1453 if (Expr *E = (Expr*) D.getAsmLabel()) {
1454 // The parser guarantees this is a string.
1455 StringLiteral *SE = cast<StringLiteral>(E);
1456 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1457 SE->getByteLength())));
1458 }
1459
Nate Begemanc8e89a82008-03-14 18:07:10 +00001460 // Emit an error if an address space was applied to decl with local storage.
1461 // This includes arrays of objects with address space qualifiers, but not
1462 // automatic variables that point to other address spaces.
1463 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001464 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1465 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1466 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001467 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001468 // Merge the decl with the existing one if appropriate. If the decl is
1469 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001470 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001471 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1472 // The user tried to define a non-static data member
1473 // out-of-line (C++ [dcl.meaning]p1).
1474 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1475 << D.getCXXScopeSpec().getRange();
1476 NewVD->Destroy(Context);
1477 return 0;
1478 }
1479
Reid Spencer5f016e22007-07-11 17:01:13 +00001480 NewVD = MergeVarDecl(NewVD, PrevDecl);
1481 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001482
1483 if (D.getCXXScopeSpec().isSet()) {
1484 // No previous declaration in the qualifying scope.
1485 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1486 << Name << D.getCXXScopeSpec().getRange();
1487 InvalidDecl = true;
1488 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001489 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001490 New = NewVD;
1491 }
1492
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001493 // Set the lexical context. If the declarator has a C++ scope specifier, the
1494 // lexical context will be different from the semantic context.
1495 New->setLexicalDeclContext(CurContext);
1496
Reid Spencer5f016e22007-07-11 17:01:13 +00001497 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001498 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001499 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001500 // If any semantic error occurred, mark the decl as invalid.
1501 if (D.getInvalidType() || InvalidDecl)
1502 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001503
1504 return New;
1505}
1506
Steve Naroff6594a702008-10-27 11:34:16 +00001507void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001508 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1509 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001510}
1511
Eli Friedmanc594b322008-05-20 13:48:25 +00001512bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1513 switch (Init->getStmtClass()) {
1514 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001515 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001516 return true;
1517 case Expr::ParenExprClass: {
1518 const ParenExpr* PE = cast<ParenExpr>(Init);
1519 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1520 }
1521 case Expr::CompoundLiteralExprClass:
1522 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1523 case Expr::DeclRefExprClass: {
1524 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001525 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1526 if (VD->hasGlobalStorage())
1527 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001528 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001529 return true;
1530 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001531 if (isa<FunctionDecl>(D))
1532 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001533 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001534 return true;
1535 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001536 case Expr::MemberExprClass: {
1537 const MemberExpr *M = cast<MemberExpr>(Init);
1538 if (M->isArrow())
1539 return CheckAddressConstantExpression(M->getBase());
1540 return CheckAddressConstantExpressionLValue(M->getBase());
1541 }
1542 case Expr::ArraySubscriptExprClass: {
1543 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1544 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1545 return CheckAddressConstantExpression(ASE->getBase()) ||
1546 CheckArithmeticConstantExpression(ASE->getIdx());
1547 }
1548 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001549 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001550 return false;
1551 case Expr::UnaryOperatorClass: {
1552 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1553
1554 // C99 6.6p9
1555 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001556 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001557
Steve Naroff6594a702008-10-27 11:34:16 +00001558 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001559 return true;
1560 }
1561 }
1562}
1563
1564bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1565 switch (Init->getStmtClass()) {
1566 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001567 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001568 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001569 case Expr::ParenExprClass:
1570 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001571 case Expr::StringLiteralClass:
1572 case Expr::ObjCStringLiteralClass:
1573 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001574 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001575 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001576 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1577 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1578 Builtin::BI__builtin___CFStringMakeConstantString)
1579 return false;
1580
Steve Naroff6594a702008-10-27 11:34:16 +00001581 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001582 return true;
1583
Eli Friedmanc594b322008-05-20 13:48:25 +00001584 case Expr::UnaryOperatorClass: {
1585 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1586
1587 // C99 6.6p9
1588 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1589 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1590
1591 if (Exp->getOpcode() == UnaryOperator::Extension)
1592 return CheckAddressConstantExpression(Exp->getSubExpr());
1593
Steve Naroff6594a702008-10-27 11:34:16 +00001594 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001595 return true;
1596 }
1597 case Expr::BinaryOperatorClass: {
1598 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1599 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1600
1601 Expr *PExp = Exp->getLHS();
1602 Expr *IExp = Exp->getRHS();
1603 if (IExp->getType()->isPointerType())
1604 std::swap(PExp, IExp);
1605
1606 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1607 return CheckAddressConstantExpression(PExp) ||
1608 CheckArithmeticConstantExpression(IExp);
1609 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001610 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001611 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001612 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001613 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1614 // Check for implicit promotion
1615 if (SubExpr->getType()->isFunctionType() ||
1616 SubExpr->getType()->isArrayType())
1617 return CheckAddressConstantExpressionLValue(SubExpr);
1618 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001619
1620 // Check for pointer->pointer cast
1621 if (SubExpr->getType()->isPointerType())
1622 return CheckAddressConstantExpression(SubExpr);
1623
Eli Friedmanc3f07642008-08-25 20:46:57 +00001624 if (SubExpr->getType()->isIntegralType()) {
1625 // Check for the special-case of a pointer->int->pointer cast;
1626 // this isn't standard, but some code requires it. See
1627 // PR2720 for an example.
1628 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1629 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1630 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1631 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1632 if (IntWidth >= PointerWidth) {
1633 return CheckAddressConstantExpression(SubCast->getSubExpr());
1634 }
1635 }
1636 }
1637 }
1638 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001639 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001640 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001641
Steve Naroff6594a702008-10-27 11:34:16 +00001642 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001643 return true;
1644 }
1645 case Expr::ConditionalOperatorClass: {
1646 // FIXME: Should we pedwarn here?
1647 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1648 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001649 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001650 return true;
1651 }
1652 if (CheckArithmeticConstantExpression(Exp->getCond()))
1653 return true;
1654 if (Exp->getLHS() &&
1655 CheckAddressConstantExpression(Exp->getLHS()))
1656 return true;
1657 return CheckAddressConstantExpression(Exp->getRHS());
1658 }
1659 case Expr::AddrLabelExprClass:
1660 return false;
1661 }
1662}
1663
Eli Friedman4caf0552008-06-09 05:05:07 +00001664static const Expr* FindExpressionBaseAddress(const Expr* E);
1665
1666static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1667 switch (E->getStmtClass()) {
1668 default:
1669 return E;
1670 case Expr::ParenExprClass: {
1671 const ParenExpr* PE = cast<ParenExpr>(E);
1672 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1673 }
1674 case Expr::MemberExprClass: {
1675 const MemberExpr *M = cast<MemberExpr>(E);
1676 if (M->isArrow())
1677 return FindExpressionBaseAddress(M->getBase());
1678 return FindExpressionBaseAddressLValue(M->getBase());
1679 }
1680 case Expr::ArraySubscriptExprClass: {
1681 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1682 return FindExpressionBaseAddress(ASE->getBase());
1683 }
1684 case Expr::UnaryOperatorClass: {
1685 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1686
1687 if (Exp->getOpcode() == UnaryOperator::Deref)
1688 return FindExpressionBaseAddress(Exp->getSubExpr());
1689
1690 return E;
1691 }
1692 }
1693}
1694
1695static const Expr* FindExpressionBaseAddress(const Expr* E) {
1696 switch (E->getStmtClass()) {
1697 default:
1698 return E;
1699 case Expr::ParenExprClass: {
1700 const ParenExpr* PE = cast<ParenExpr>(E);
1701 return FindExpressionBaseAddress(PE->getSubExpr());
1702 }
1703 case Expr::UnaryOperatorClass: {
1704 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1705
1706 // C99 6.6p9
1707 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1708 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1709
1710 if (Exp->getOpcode() == UnaryOperator::Extension)
1711 return FindExpressionBaseAddress(Exp->getSubExpr());
1712
1713 return E;
1714 }
1715 case Expr::BinaryOperatorClass: {
1716 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1717
1718 Expr *PExp = Exp->getLHS();
1719 Expr *IExp = Exp->getRHS();
1720 if (IExp->getType()->isPointerType())
1721 std::swap(PExp, IExp);
1722
1723 return FindExpressionBaseAddress(PExp);
1724 }
1725 case Expr::ImplicitCastExprClass: {
1726 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1727
1728 // Check for implicit promotion
1729 if (SubExpr->getType()->isFunctionType() ||
1730 SubExpr->getType()->isArrayType())
1731 return FindExpressionBaseAddressLValue(SubExpr);
1732
1733 // Check for pointer->pointer cast
1734 if (SubExpr->getType()->isPointerType())
1735 return FindExpressionBaseAddress(SubExpr);
1736
1737 // We assume that we have an arithmetic expression here;
1738 // if we don't, we'll figure it out later
1739 return 0;
1740 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001741 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001742 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1743
1744 // Check for pointer->pointer cast
1745 if (SubExpr->getType()->isPointerType())
1746 return FindExpressionBaseAddress(SubExpr);
1747
1748 // We assume that we have an arithmetic expression here;
1749 // if we don't, we'll figure it out later
1750 return 0;
1751 }
1752 }
1753}
1754
Anders Carlsson51fe9962008-11-22 21:04:56 +00001755bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001756 switch (Init->getStmtClass()) {
1757 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001758 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001759 return true;
1760 case Expr::ParenExprClass: {
1761 const ParenExpr* PE = cast<ParenExpr>(Init);
1762 return CheckArithmeticConstantExpression(PE->getSubExpr());
1763 }
1764 case Expr::FloatingLiteralClass:
1765 case Expr::IntegerLiteralClass:
1766 case Expr::CharacterLiteralClass:
1767 case Expr::ImaginaryLiteralClass:
1768 case Expr::TypesCompatibleExprClass:
1769 case Expr::CXXBoolLiteralExprClass:
1770 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001771 case Expr::CallExprClass:
1772 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001773 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001774
1775 // Allow any constant foldable calls to builtins.
1776 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001777 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001778
Steve Naroff6594a702008-10-27 11:34:16 +00001779 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001780 return true;
1781 }
1782 case Expr::DeclRefExprClass: {
1783 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1784 if (isa<EnumConstantDecl>(D))
1785 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001786 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001787 return true;
1788 }
1789 case Expr::CompoundLiteralExprClass:
1790 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1791 // but vectors are allowed to be magic.
1792 if (Init->getType()->isVectorType())
1793 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001794 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001795 return true;
1796 case Expr::UnaryOperatorClass: {
1797 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1798
1799 switch (Exp->getOpcode()) {
1800 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1801 // See C99 6.6p3.
1802 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001803 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001804 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001805 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001806 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1807 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001808 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001809 return true;
1810 case UnaryOperator::Extension:
1811 case UnaryOperator::LNot:
1812 case UnaryOperator::Plus:
1813 case UnaryOperator::Minus:
1814 case UnaryOperator::Not:
1815 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1816 }
1817 }
Sebastian Redl05189992008-11-11 17:56:53 +00001818 case Expr::SizeOfAlignOfExprClass: {
1819 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001820 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001821 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001822 return false;
1823 // alignof always evaluates to a constant.
1824 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001825 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001826 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001827 return true;
1828 }
1829 return false;
1830 }
1831 case Expr::BinaryOperatorClass: {
1832 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1833
1834 if (Exp->getLHS()->getType()->isArithmeticType() &&
1835 Exp->getRHS()->getType()->isArithmeticType()) {
1836 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1837 CheckArithmeticConstantExpression(Exp->getRHS());
1838 }
1839
Eli Friedman4caf0552008-06-09 05:05:07 +00001840 if (Exp->getLHS()->getType()->isPointerType() &&
1841 Exp->getRHS()->getType()->isPointerType()) {
1842 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1843 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1844
1845 // Only allow a null (constant integer) base; we could
1846 // allow some additional cases if necessary, but this
1847 // is sufficient to cover offsetof-like constructs.
1848 if (!LHSBase && !RHSBase) {
1849 return CheckAddressConstantExpression(Exp->getLHS()) ||
1850 CheckAddressConstantExpression(Exp->getRHS());
1851 }
1852 }
1853
Steve Naroff6594a702008-10-27 11:34:16 +00001854 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001855 return true;
1856 }
1857 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001858 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001859 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001860 if (SubExpr->getType()->isArithmeticType())
1861 return CheckArithmeticConstantExpression(SubExpr);
1862
Eli Friedmanb529d832008-09-02 09:37:00 +00001863 if (SubExpr->getType()->isPointerType()) {
1864 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1865 // If the pointer has a null base, this is an offsetof-like construct
1866 if (!Base)
1867 return CheckAddressConstantExpression(SubExpr);
1868 }
1869
Steve Naroff6594a702008-10-27 11:34:16 +00001870 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001871 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001872 }
1873 case Expr::ConditionalOperatorClass: {
1874 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001875
1876 // If GNU extensions are disabled, we require all operands to be arithmetic
1877 // constant expressions.
1878 if (getLangOptions().NoExtensions) {
1879 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1880 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1881 CheckArithmeticConstantExpression(Exp->getRHS());
1882 }
1883
1884 // Otherwise, we have to emulate some of the behavior of fold here.
1885 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1886 // because it can constant fold things away. To retain compatibility with
1887 // GCC code, we see if we can fold the condition to a constant (which we
1888 // should always be able to do in theory). If so, we only require the
1889 // specified arm of the conditional to be a constant. This is a horrible
1890 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001891 Expr::EvalResult EvalResult;
1892 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
1893 EvalResult.HasSideEffects) {
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001894 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001895 // won't be able to either. Use it to emit the diagnostic though.
1896 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001897 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001898 return Res;
1899 }
1900
1901 // Verify that the side following the condition is also a constant.
1902 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00001903 if (EvalResult.Val.getInt() == 0)
Chris Lattner46cfefa2008-10-06 05:42:39 +00001904 std::swap(TrueSide, FalseSide);
1905
1906 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001907 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001908
1909 // Okay, the evaluated side evaluates to a constant, so we accept this.
1910 // Check to see if the other side is obviously not a constant. If so,
1911 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001912 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001913 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001914 diag::ext_typecheck_expression_not_constant_but_accepted)
1915 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001916 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001917 }
1918 }
1919}
1920
1921bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001922 Expr::EvalResult Result;
1923
Nuno Lopes9a979c32008-07-07 16:46:50 +00001924 Init = Init->IgnoreParens();
1925
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001926 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1927 return false;
1928
Eli Friedmanc594b322008-05-20 13:48:25 +00001929 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1930 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1931 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1932
Nuno Lopes9a979c32008-07-07 16:46:50 +00001933 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1934 return CheckForConstantInitializer(e->getInitializer(), DclT);
1935
Eli Friedmanc594b322008-05-20 13:48:25 +00001936 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1937 unsigned numInits = Exp->getNumInits();
1938 for (unsigned i = 0; i < numInits; i++) {
1939 // FIXME: Need to get the type of the declaration for C++,
1940 // because it could be a reference?
1941 if (CheckForConstantInitializer(Exp->getInit(i),
1942 Exp->getInit(i)->getType()))
1943 return true;
1944 }
1945 return false;
1946 }
1947
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001948 // FIXME: We can probably remove some of this code below, now that
1949 // Expr::Evaluate is doing the heavy lifting for scalars.
1950
Eli Friedmanc594b322008-05-20 13:48:25 +00001951 if (Init->isNullPointerConstant(Context))
1952 return false;
1953 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001954 QualType InitTy = Context.getCanonicalType(Init->getType())
1955 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001956 if (InitTy == Context.BoolTy) {
1957 // Special handling for pointers implicitly cast to bool;
1958 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1959 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1960 Expr* SubE = ICE->getSubExpr();
1961 if (SubE->getType()->isPointerType() ||
1962 SubE->getType()->isArrayType() ||
1963 SubE->getType()->isFunctionType()) {
1964 return CheckAddressConstantExpression(Init);
1965 }
1966 }
1967 } else if (InitTy->isIntegralType()) {
1968 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001969 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001970 SubE = CE->getSubExpr();
1971 // Special check for pointer cast to int; we allow as an extension
1972 // an address constant cast to an integer if the integer
1973 // is of an appropriate width (this sort of code is apparently used
1974 // in some places).
1975 // FIXME: Add pedwarn?
1976 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1977 if (SubE && (SubE->getType()->isPointerType() ||
1978 SubE->getType()->isArrayType() ||
1979 SubE->getType()->isFunctionType())) {
1980 unsigned IntWidth = Context.getTypeSize(Init->getType());
1981 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1982 if (IntWidth >= PointerWidth)
1983 return CheckAddressConstantExpression(Init);
1984 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001985 }
1986
1987 return CheckArithmeticConstantExpression(Init);
1988 }
1989
1990 if (Init->getType()->isPointerType())
1991 return CheckAddressConstantExpression(Init);
1992
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001993 // An array type at the top level that isn't an init-list must
1994 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001995 if (Init->getType()->isArrayType())
1996 return false;
1997
Nuno Lopes73419bf2008-09-01 18:42:41 +00001998 if (Init->getType()->isFunctionType())
1999 return false;
2000
Steve Naroff8af6a452008-10-02 17:12:56 +00002001 // Allow block exprs at top level.
2002 if (Init->getType()->isBlockPointerType())
2003 return false;
2004
Steve Naroff6594a702008-10-27 11:34:16 +00002005 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002006 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002007}
2008
Sebastian Redl798d1192008-12-13 16:23:55 +00002009void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002010 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002011 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002012 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002013
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002014 // If there is no declaration, there was an error parsing it. Just ignore
2015 // the initializer.
2016 if (RealDecl == 0) {
2017 delete Init;
2018 return;
2019 }
Steve Naroffbb204692007-09-12 14:07:44 +00002020
Steve Naroff410e3e22007-09-12 20:13:48 +00002021 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2022 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002023 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2024 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002025 RealDecl->setInvalidDecl();
2026 return;
2027 }
Steve Naroffbb204692007-09-12 14:07:44 +00002028 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002029 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002030 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002031 if (VDecl->isBlockVarDecl()) {
2032 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002033 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002034 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002035 VDecl->setInvalidDecl();
2036 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002037 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002038 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002039 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002040
2041 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2042 if (!getLangOptions().CPlusPlus) {
2043 if (SC == VarDecl::Static) // C99 6.7.8p4.
2044 CheckForConstantInitializer(Init, DclT);
2045 }
Steve Naroffbb204692007-09-12 14:07:44 +00002046 }
Steve Naroff248a7532008-04-15 22:42:06 +00002047 } else if (VDecl->isFileVarDecl()) {
2048 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002049 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002050 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002051 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002052 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002053 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002054
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002055 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2056 if (!getLangOptions().CPlusPlus) {
2057 // C99 6.7.8p4. All file scoped initializers need to be constant.
2058 CheckForConstantInitializer(Init, DclT);
2059 }
Steve Naroffbb204692007-09-12 14:07:44 +00002060 }
2061 // If the type changed, it means we had an incomplete type that was
2062 // completed by the initializer. For example:
2063 // int ary[] = { 1, 3, 5 };
2064 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002065 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002066 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002067 Init->setType(DclT);
2068 }
Steve Naroffbb204692007-09-12 14:07:44 +00002069
2070 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002071 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002072 return;
2073}
2074
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002075void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2076 Decl *RealDecl = static_cast<Decl *>(dcl);
2077
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002078 // If there is no declaration, there was an error parsing it. Just ignore it.
2079 if (RealDecl == 0)
2080 return;
2081
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002082 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2083 QualType Type = Var->getType();
2084 // C++ [dcl.init.ref]p3:
2085 // The initializer can be omitted for a reference only in a
2086 // parameter declaration (8.3.5), in the declaration of a
2087 // function return type, in the declaration of a class member
2088 // within its class declaration (9.2), and where the extern
2089 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002090 if (Type->isReferenceType() &&
2091 Var->getStorageClass() != VarDecl::Extern &&
2092 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002093 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002094 << Var->getDeclName()
2095 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002096 Var->setInvalidDecl();
2097 return;
2098 }
2099
2100 // C++ [dcl.init]p9:
2101 //
2102 // If no initializer is specified for an object, and the object
2103 // is of (possibly cv-qualified) non-POD class type (or array
2104 // thereof), the object shall be default-initialized; if the
2105 // object is of const-qualified type, the underlying class type
2106 // shall have a user-declared default constructor.
2107 if (getLangOptions().CPlusPlus) {
2108 QualType InitType = Type;
2109 if (const ArrayType *Array = Context.getAsArrayType(Type))
2110 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002111 if (Var->getStorageClass() != VarDecl::Extern &&
2112 Var->getStorageClass() != VarDecl::PrivateExtern &&
2113 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002114 const CXXConstructorDecl *Constructor
2115 = PerformInitializationByConstructor(InitType, 0, 0,
2116 Var->getLocation(),
2117 SourceRange(Var->getLocation(),
2118 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002119 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002120 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002121 if (!Constructor)
2122 Var->setInvalidDecl();
2123 }
2124 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002125
Douglas Gregor818ce482008-10-29 13:50:18 +00002126#if 0
2127 // FIXME: Temporarily disabled because we are not properly parsing
2128 // linkage specifications on declarations, e.g.,
2129 //
2130 // extern "C" const CGPoint CGPointerZero;
2131 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002132 // C++ [dcl.init]p9:
2133 //
2134 // If no initializer is specified for an object, and the
2135 // object is of (possibly cv-qualified) non-POD class type (or
2136 // array thereof), the object shall be default-initialized; if
2137 // the object is of const-qualified type, the underlying class
2138 // type shall have a user-declared default
2139 // constructor. Otherwise, if no initializer is specified for
2140 // an object, the object and its subobjects, if any, have an
2141 // indeterminate initial value; if the object or any of its
2142 // subobjects are of const-qualified type, the program is
2143 // ill-formed.
2144 //
2145 // This isn't technically an error in C, so we don't diagnose it.
2146 //
2147 // FIXME: Actually perform the POD/user-defined default
2148 // constructor check.
2149 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002150 Context.getCanonicalType(Type).isConstQualified() &&
2151 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002152 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2153 << Var->getName()
2154 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002155#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002156 }
2157}
2158
Reid Spencer5f016e22007-07-11 17:01:13 +00002159/// The declarators are chained together backwards, reverse the list.
2160Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2161 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002162 Decl *GroupDecl = static_cast<Decl*>(group);
2163 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002164 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002165
2166 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2167 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002168 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002169 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002170 else { // reverse the list.
2171 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002172 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002173 Group->setNextDeclarator(NewGroup);
2174 NewGroup = Group;
2175 Group = Next;
2176 }
2177 }
2178 // Perform semantic analysis that depends on having fully processed both
2179 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002180 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002181 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2182 if (!IDecl)
2183 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002184 QualType T = IDecl->getType();
2185
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002186 if (T->isVariableArrayType()) {
Anders Carlssonfcdbb932008-12-20 21:51:53 +00002187 const VariableArrayType *VAT = Context.getAsVariableArrayType(T);
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002188
2189 // FIXME: This won't give the correct result for
2190 // int a[10][n];
2191 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002192 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002193 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2194 SizeRange;
2195
Eli Friedmanc5773c42008-02-15 18:16:39 +00002196 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002197 } else {
2198 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2199 // static storage duration, it shall not have a variable length array.
2200 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002201 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2202 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002203 IDecl->setInvalidDecl();
2204 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002205 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2206 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002207 IDecl->setInvalidDecl();
2208 }
2209 }
2210 } else if (T->isVariablyModifiedType()) {
2211 if (IDecl->isFileVarDecl()) {
2212 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2213 IDecl->setInvalidDecl();
2214 } else {
2215 if (IDecl->getStorageClass() == VarDecl::Extern) {
2216 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2217 IDecl->setInvalidDecl();
2218 }
Steve Naroffbb204692007-09-12 14:07:44 +00002219 }
2220 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002221
Steve Naroffbb204692007-09-12 14:07:44 +00002222 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2223 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002224 if (IDecl->isBlockVarDecl() &&
2225 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002226 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002227 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002228 IDecl->setInvalidDecl();
2229 }
2230 }
2231 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2232 // object that has file scope without an initializer, and without a
2233 // storage-class specifier or with the storage-class specifier "static",
2234 // constitutes a tentative definition. Note: A tentative definition with
2235 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002236 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002237 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002238 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2239 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002240 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002241 // C99 6.9.2p3: If the declaration of an identifier for an object is
2242 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2243 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002244 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002245 IDecl->setInvalidDecl();
2246 }
2247 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002248 if (IDecl->isFileVarDecl())
2249 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002250 }
2251 return NewGroup;
2252}
Steve Naroffe1223f72007-08-28 03:03:08 +00002253
Chris Lattner04421082008-04-08 04:40:51 +00002254/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2255/// to introduce parameters into function prototype scope.
2256Sema::DeclTy *
2257Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002258 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002259
Chris Lattner04421082008-04-08 04:40:51 +00002260 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002261 VarDecl::StorageClass StorageClass = VarDecl::None;
2262 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2263 StorageClass = VarDecl::Register;
2264 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002265 Diag(DS.getStorageClassSpecLoc(),
2266 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002267 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002268 }
2269 if (DS.isThreadSpecified()) {
2270 Diag(DS.getThreadSpecLoc(),
2271 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002272 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002273 }
2274
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002275 // Check that there are no default arguments inside the type of this
2276 // parameter (C++ only).
2277 if (getLangOptions().CPlusPlus)
2278 CheckExtraCXXDefaultArguments(D);
2279
Chris Lattner04421082008-04-08 04:40:51 +00002280 // In this context, we *do not* check D.getInvalidType(). If the declarator
2281 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2282 // though it will not reflect the user specified type.
2283 QualType parmDeclType = GetTypeForDeclarator(D, S);
2284
2285 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2286
Reid Spencer5f016e22007-07-11 17:01:13 +00002287 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2288 // Can this happen for params? We already checked that they don't conflict
2289 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002290 IdentifierInfo *II = D.getIdentifier();
2291 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002292 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002293 // Maybe we will complain about the shadowed template parameter.
2294 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2295 // Just pretend that we didn't see the previous declaration.
2296 PrevDecl = 0;
2297 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002298 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002299
2300 // Recover by removing the name
2301 II = 0;
2302 D.SetIdentifier(0, D.getIdentifierLoc());
2303 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002304 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002305
2306 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2307 // Doing the promotion here has a win and a loss. The win is the type for
2308 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2309 // code generator). The loss is the orginal type isn't preserved. For example:
2310 //
2311 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2312 // int blockvardecl[5];
2313 // sizeof(parmvardecl); // size == 4
2314 // sizeof(blockvardecl); // size == 20
2315 // }
2316 //
2317 // For expressions, all implicit conversions are captured using the
2318 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2319 //
2320 // FIXME: If a source translation tool needs to see the original type, then
2321 // we need to consider storing both types (in ParmVarDecl)...
2322 //
Chris Lattnere6327742008-04-02 05:18:44 +00002323 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002324 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002325 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002326 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002327 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002328
Chris Lattner04421082008-04-08 04:40:51 +00002329 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2330 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002331 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002332 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002333
Chris Lattner04421082008-04-08 04:40:51 +00002334 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002335 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002336
Douglas Gregor584049d2008-12-15 23:53:10 +00002337 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2338 if (D.getCXXScopeSpec().isSet()) {
2339 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2340 << D.getCXXScopeSpec().getRange();
2341 New->setInvalidDecl();
2342 }
2343
Douglas Gregor44b43212008-12-11 16:49:14 +00002344 // Add the parameter declaration into this scope.
2345 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002346 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002347 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002348
Chris Lattner3ff30c82008-06-29 00:02:00 +00002349 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002350 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002351
Reid Spencer5f016e22007-07-11 17:01:13 +00002352}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002353
Chris Lattnerb652cea2007-10-09 17:14:05 +00002354Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002355 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002356 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2357 "Not a function declarator!");
2358 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002359
Reid Spencer5f016e22007-07-11 17:01:13 +00002360 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2361 // for a K&R function.
2362 if (!FTI.hasPrototype) {
2363 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002364 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002365 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2366 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002367 // Implicitly declare the argument as type 'int' for lack of a better
2368 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002369 DeclSpec DS;
2370 const char* PrevSpec; // unused
2371 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2372 PrevSpec);
2373 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2374 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2375 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002376 }
2377 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002378 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002379 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002380 }
2381
Douglas Gregor584049d2008-12-15 23:53:10 +00002382 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002383
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002384 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002385 ActOnDeclarator(ParentScope, D, 0,
2386 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002387}
2388
2389Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2390 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002391 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002392
2393 // See if this is a redefinition.
2394 const FunctionDecl *Definition;
2395 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002396 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002397 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002398 }
2399
Douglas Gregor44b43212008-12-11 16:49:14 +00002400 PushDeclContext(FnBodyScope, FD);
Chris Lattner04421082008-04-08 04:40:51 +00002401
2402 // Check the validity of our function parameters
2403 CheckParmsForFunctionDef(FD);
2404
2405 // Introduce our parameters into the function scope
2406 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2407 ParmVarDecl *Param = FD->getParamDecl(p);
2408 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002409 if (Param->getIdentifier())
2410 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002411 }
Chris Lattner04421082008-04-08 04:40:51 +00002412
Reid Spencer5f016e22007-07-11 17:01:13 +00002413 return FD;
2414}
2415
Sebastian Redl798d1192008-12-13 16:23:55 +00002416Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002417 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002418 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002419 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002420 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002421 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002422 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002423 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002424 } else
2425 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002426 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002427 // Verify and clean out per-function state.
2428
2429 // Check goto/label use.
2430 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2431 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2432 // Verify that we have no forward references left. If so, there was a goto
2433 // or address of a label taken, but no definition of it. Label fwd
2434 // definitions are indicated with a null substmt.
2435 if (I->second->getSubStmt() == 0) {
2436 LabelStmt *L = I->second;
2437 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002438 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002439
2440 // At this point, we have gotos that use the bogus label. Stitch it into
2441 // the function body so that they aren't leaked and that the AST is well
2442 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002443 if (Body) {
2444 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002445 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002446 } else {
2447 // The whole function wasn't parsed correctly, just delete this.
2448 delete L;
2449 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 }
2451 }
2452 LabelMap.clear();
2453
Steve Naroffd6d054d2007-11-11 23:20:51 +00002454 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002455}
2456
Reid Spencer5f016e22007-07-11 17:01:13 +00002457/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2458/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002459ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2460 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002461 // Extension in C99. Legal in C90, but warn about it.
2462 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002463 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002464 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002465 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002466
2467 // FIXME: handle stuff like:
2468 // void foo() { extern float X(); }
2469 // void bar() { X(); } <-- implicit decl for X in another scope.
2470
2471 // Set a Declarator for the implicit definition: int foo();
2472 const char *Dummy;
2473 DeclSpec DS;
2474 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2475 Error = Error; // Silence warning.
2476 assert(!Error && "Error setting up implicit decl!");
2477 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002478 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 D.SetIdentifier(&II, Loc);
2480
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002481 // Insert this function into translation-unit scope.
2482
2483 DeclContext *PrevDC = CurContext;
2484 CurContext = Context.getTranslationUnitDecl();
2485
Steve Naroffe2ef8152008-04-04 14:32:09 +00002486 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002487 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002488 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002489
2490 CurContext = PrevDC;
2491
Steve Naroffe2ef8152008-04-04 14:32:09 +00002492 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002493}
2494
2495
Chris Lattner41af0932007-11-14 06:34:38 +00002496TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002497 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002498 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002499 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002500
2501 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002502 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2503 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002504 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002505 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002506 if (D.getInvalidType())
2507 NewTD->setInvalidDecl();
2508 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002509}
2510
Steve Naroff08d92e42007-09-15 18:49:24 +00002511/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002512/// former case, Name will be non-null. In the later case, Name will be null.
2513/// TagType indicates what kind of tag this is. TK indicates whether this is a
2514/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002515Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002516 SourceLocation KWLoc, const CXXScopeSpec &SS,
2517 IdentifierInfo *Name, SourceLocation NameLoc,
2518 AttributeList *Attr) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002519 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002520 assert((Name != 0 || TK == TK_Definition) &&
2521 "Nameless record must be a definition!");
2522
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002523 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002524 switch (TagType) {
2525 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002526 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2527 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2528 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2529 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002530 }
2531
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002532 DeclContext *DC = CurContext;
2533 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002534
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002535 if (Name && SS.isNotEmpty()) {
2536 // We have a nested-name tag ('struct foo::bar').
2537
2538 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002539 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002540 Name = 0;
2541 goto CreateNewDecl;
2542 }
2543
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002544 DC = static_cast<DeclContext*>(SS.getScopeRep());
2545 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002546 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2547
2548 // A tag 'foo::bar' must already exist.
2549 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002550 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002551 Name = 0;
2552 goto CreateNewDecl;
2553 }
2554 } else {
2555 // If this is a named struct, check to see if there was a previous forward
2556 // declaration or definition.
2557 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2558 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2559 }
2560
Douglas Gregorf57172b2008-12-08 18:40:42 +00002561 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002562 // Maybe we will complain about the shadowed template parameter.
2563 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2564 // Just pretend that we didn't see the previous declaration.
2565 PrevDecl = 0;
2566 }
2567
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002568 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002569 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2570 "unexpected Decl type");
2571 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002572 // If this is a use of a previous tag, or if the tag is already declared
2573 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002574 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002575 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002576 // Make sure that this wasn't declared as an enum and now used as a
2577 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002578 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002579 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002580 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002581 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002582 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002583 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002584 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002585 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002586
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002587 // FIXME: In the future, return a variant or some other clue
2588 // for the consumer of this Decl to know it doesn't own it.
2589 // For our current ASTs this shouldn't be a problem, but will
2590 // need to be changed with DeclGroups.
2591 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002592 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002593
2594 // Diagnose attempts to redefine a tag.
2595 if (TK == TK_Definition) {
2596 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2597 Diag(NameLoc, diag::err_redefinition) << Name;
2598 Diag(Def->getLocation(), diag::note_previous_definition);
2599 // If this is a redefinition, recover by making this struct be
2600 // anonymous, which will make any later references get the previous
2601 // definition.
2602 Name = 0;
2603 PrevDecl = 0;
2604 }
2605 // Okay, this is definition of a previously declared or referenced
2606 // tag PrevDecl. We're going to create a new Decl for it.
2607 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002608 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002609 // If we get here we have (another) forward declaration or we
2610 // have a definition. Just create a new decl.
2611 } else {
2612 // If we get here, this is a definition of a new tag type in a nested
2613 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2614 // new decl/type. We set PrevDecl to NULL so that the entities
2615 // have distinct types.
2616 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002617 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002618 // If we get here, we're going to create a new Decl. If PrevDecl
2619 // is non-NULL, it's a definition of the tag declared by
2620 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002621 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002622 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002623 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002624 // The tag name clashes with a namespace name, issue an error and
2625 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002626 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002627 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002628 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002629 PrevDecl = 0;
2630 } else {
2631 // The existing declaration isn't relevant to us; we're in a
2632 // new scope, so clear out the previous declaration.
2633 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002634 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002635 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002636 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002637
Chris Lattnercc98eac2008-12-17 07:13:27 +00002638CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002639
2640 // If there is an identifier, use the location of the identifier as the
2641 // location of the decl, otherwise use the location of the struct/union
2642 // keyword.
2643 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2644
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002645 // Otherwise, create a new declaration. If there is a previous
2646 // declaration of the same entity, the two will be linked via
2647 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002648 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002649 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002650 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2651 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002652 New = EnumDecl::Create(Context, DC, Loc, Name,
2653 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002654 // If this is an undefined enum, warn.
2655 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002656 } else {
2657 // struct/union/class
2658
Reid Spencer5f016e22007-07-11 17:01:13 +00002659 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2660 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002661 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002662 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002663 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2664 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002665 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002666 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2667 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002668 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002669
2670 if (Kind != TagDecl::TK_enum) {
2671 // Handle #pragma pack: if the #pragma pack stack has non-default
2672 // alignment, make up a packed attribute for this decl. These
2673 // attributes are checked when the ASTContext lays out the
2674 // structure.
2675 //
2676 // It is important for implementing the correct semantics that this
2677 // happen here (in act on tag decl). The #pragma pack stack is
2678 // maintained as a result of parser callbacks which can occur at
2679 // many points during the parsing of a struct declaration (because
2680 // the #pragma tokens are effectively skipped over during the
2681 // parsing of the struct).
2682 if (unsigned Alignment = PackContext.getAlignment())
2683 New->addAttr(new PackedAttr(Alignment * 8));
2684 }
2685
2686 if (Attr)
2687 ProcessDeclAttributeList(New, Attr);
2688
2689 // Set the lexical context. If the tag has a C++ scope specifier, the
2690 // lexical context will be different from the semantic context.
2691 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002692
2693 // If this has an identifier, add it to the scope stack.
2694 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002695 // The scope passed in may not be a decl scope. Zip up the scope tree until
2696 // we find one that is.
2697 while ((S->getFlags() & Scope::DeclScope) == 0)
2698 S = S->getParent();
2699
2700 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002701 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002702 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002703
Reid Spencer5f016e22007-07-11 17:01:13 +00002704 return New;
2705}
2706
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002707
Chris Lattner1d353ba2008-11-12 21:17:48 +00002708/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2709/// types into constant array types in certain situations which would otherwise
2710/// be errors (for GCC compatibility).
2711static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2712 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002713 // This method tries to turn a variable array into a constant
2714 // array even when the size isn't an ICE. This is necessary
2715 // for compatibility with code that depends on gcc's buggy
2716 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002717 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2718 if (!VLATy) return QualType();
2719
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002720 Expr::EvalResult EvalResult;
Chris Lattner57d57882008-11-12 19:48:13 +00002721 if (!VLATy->getSizeExpr() ||
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002722 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002723 return QualType();
2724
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00002725 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2726 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattner57d57882008-11-12 19:48:13 +00002727 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2728 return Context.getConstantArrayType(VLATy->getElementType(),
2729 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002730 return QualType();
2731}
2732
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002733bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002734 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002735 // FIXME: 6.7.2.1p4 - verify the field type.
2736
2737 llvm::APSInt Value;
2738 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2739 return true;
2740
Chris Lattnercd087072008-12-12 04:56:04 +00002741 // Zero-width bitfield is ok for anonymous field.
2742 if (Value == 0 && FieldName)
2743 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2744
2745 if (Value.isNegative())
2746 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002747
2748 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2749 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002750 if (TypeSize && Value.getZExtValue() > TypeSize)
2751 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2752 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002753
2754 return false;
2755}
2756
Steve Naroff08d92e42007-09-15 18:49:24 +00002757/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002758/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002759Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002760 SourceLocation DeclStart,
2761 Declarator &D, ExprTy *BitfieldWidth) {
2762 IdentifierInfo *II = D.getIdentifier();
2763 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002764 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002765 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002766 if (II) Loc = D.getIdentifierLoc();
2767
2768 // FIXME: Unnamed fields can be handled in various different ways, for
2769 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002770
Reid Spencer5f016e22007-07-11 17:01:13 +00002771 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002772 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2773 bool InvalidDecl = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002774
Reid Spencer5f016e22007-07-11 17:01:13 +00002775 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2776 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002777 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002778 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002779 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002780 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002781 T = FixedTy;
2782 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002783 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002784 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002785 InvalidDecl = true;
2786 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002787 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002788
2789 if (BitWidth) {
2790 if (VerifyBitField(Loc, II, T, BitWidth))
2791 InvalidDecl = true;
2792 } else {
2793 // Not a bitfield.
2794
2795 // validate II.
2796
2797 }
2798
Reid Spencer5f016e22007-07-11 17:01:13 +00002799 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002800 FieldDecl *NewFD;
2801
Douglas Gregor44b43212008-12-11 16:49:14 +00002802 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2803 // other way to determine the current RecordDecl.
2804 NewFD = FieldDecl::Create(Context, Record,
2805 Loc, II, T, BitWidth,
2806 D.getDeclSpec().getStorageClassSpec() ==
2807 DeclSpec::SCS_mutable,
2808 /*PrevDecl=*/0);
2809
Douglas Gregor72b505b2008-12-16 21:30:33 +00002810 if (getLangOptions().CPlusPlus)
2811 CheckExtraCXXDefaultArguments(D);
2812
Chris Lattner3ff30c82008-06-29 00:02:00 +00002813 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002814
Steve Naroff5912a352007-08-28 20:14:24 +00002815 if (D.getInvalidType() || InvalidDecl)
2816 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002817
2818 if (II && getLangOptions().CPlusPlus)
2819 PushOnScopeChains(NewFD, S);
2820 else
2821 Record->addDecl(Context, NewFD);
2822
Steve Naroff5912a352007-08-28 20:14:24 +00002823 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002824}
2825
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002826/// TranslateIvarVisibility - Translate visibility from a token ID to an
2827/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002828static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002829TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002830 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002831 default: assert(0 && "Unknown visitibility kind");
2832 case tok::objc_private: return ObjCIvarDecl::Private;
2833 case tok::objc_public: return ObjCIvarDecl::Public;
2834 case tok::objc_protected: return ObjCIvarDecl::Protected;
2835 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002836 }
2837}
2838
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002839/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2840/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002841Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002842 SourceLocation DeclStart,
2843 Declarator &D, ExprTy *BitfieldWidth,
2844 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002845 IdentifierInfo *II = D.getIdentifier();
2846 Expr *BitWidth = (Expr*)BitfieldWidth;
2847 SourceLocation Loc = DeclStart;
2848 if (II) Loc = D.getIdentifierLoc();
2849
2850 // FIXME: Unnamed fields can be handled in various different ways, for
2851 // example, unnamed unions inject all members into the struct namespace!
2852
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002853 QualType T = GetTypeForDeclarator(D, S);
2854 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2855 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002856
2857 if (BitWidth) {
2858 // TODO: Validate.
2859 //printf("WARNING: BITFIELDS IGNORED!\n");
2860
2861 // 6.7.2.1p3
2862 // 6.7.2.1p4
2863
2864 } else {
2865 // Not a bitfield.
2866
2867 // validate II.
2868
2869 }
2870
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002871 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2872 // than a variably modified type.
2873 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002874 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002875 InvalidDecl = true;
2876 }
2877
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002878 // Get the visibility (access control) for this ivar.
2879 ObjCIvarDecl::AccessControl ac =
2880 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2881 : ObjCIvarDecl::None;
2882
2883 // Construct the decl.
2884 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002885 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002886
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002887 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002888 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002889
2890 if (D.getInvalidType() || InvalidDecl)
2891 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002892
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002893 return NewID;
2894}
2895
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002896void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002897 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002898 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002899 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002900 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002901 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2902 assert(EnclosingDecl && "missing record or interface decl");
2903 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2904
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002905 if (Record)
2906 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2907 // Diagnose code like:
2908 // struct S { struct S {} X; };
2909 // We discover this when we complete the outer S. Reject and ignore the
2910 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002911 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002912 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002913 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002914 Record->setInvalidDecl();
2915 return;
2916 }
2917
Reid Spencer5f016e22007-07-11 17:01:13 +00002918 // Verify that all the fields are okay.
2919 unsigned NumNamedMembers = 0;
2920 llvm::SmallVector<FieldDecl*, 32> RecFields;
2921 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002922
Reid Spencer5f016e22007-07-11 17:01:13 +00002923 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002924
Steve Naroff74216642007-09-14 22:20:54 +00002925 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2926 assert(FD && "missing field decl");
2927
2928 // Remember all fields.
2929 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002930
2931 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002932 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002933
Reid Spencer5f016e22007-07-11 17:01:13 +00002934 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002935 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002936 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002937 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002938 FD->setInvalidDecl();
2939 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002940 continue;
2941 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002942 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2943 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002944 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002945 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002946 FD->setInvalidDecl();
2947 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002948 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002949 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002950 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002951 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002952 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002953 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002954 FD->setInvalidDecl();
2955 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002956 continue;
2957 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002958 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002959 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002960 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002961 FD->setInvalidDecl();
2962 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002963 continue;
2964 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002966 if (Record)
2967 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002968 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2970 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002971 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002972 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2973 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002974 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002975 Record->setHasFlexibleArrayMember(true);
2976 } else {
2977 // If this is a struct/class and this is not the last element, reject
2978 // it. Note that GCC supports variable sized arrays in the middle of
2979 // structures.
2980 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002981 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002982 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002983 FD->setInvalidDecl();
2984 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002985 continue;
2986 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002987 // We support flexible arrays at the end of structs in other structs
2988 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002989 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002990 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002991 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002992 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002993 }
2994 }
2995 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002996 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002997 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002998 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00002999 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003000 FD->setInvalidDecl();
3001 EnclosingDecl->setInvalidDecl();
3002 continue;
3003 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003004 // Keep track of the number of named members.
3005 if (IdentifierInfo *II = FD->getIdentifier()) {
3006 // Detect duplicate member names.
3007 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003008 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003009 // Find the previous decl.
3010 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003011 for (unsigned i = 0; ; ++i) {
3012 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003013 if (RecFields[i]->getIdentifier() == II) {
3014 PrevLoc = RecFields[i]->getLocation();
3015 break;
3016 }
3017 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003018 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003019 FD->setInvalidDecl();
3020 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003021 continue;
3022 }
3023 ++NumNamedMembers;
3024 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003025 }
3026
Reid Spencer5f016e22007-07-11 17:01:13 +00003027 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003028 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003029 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003030 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3031 // Sema::ActOnFinishCXXClassDef.
3032 if (!isa<CXXRecordDecl>(Record))
3033 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003034 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003035 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003036 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003037 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003038 // Must enforce the rule that ivars in the base classes may not be
3039 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003040 if (ID->getSuperClass()) {
3041 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3042 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3043 ObjCIvarDecl* Ivar = (*IVI);
3044 IdentifierInfo *II = Ivar->getIdentifier();
3045 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3046 if (prevIvar) {
3047 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3048 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003049 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003050 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003051 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003052 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003053 else if (ObjCImplementationDecl *IMPDecl =
3054 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003055 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3056 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003057 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003058 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003059 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003060
3061 if (Attr)
3062 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003063}
3064
Steve Naroff08d92e42007-09-15 18:49:24 +00003065Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003066 DeclTy *lastEnumConst,
3067 SourceLocation IdLoc, IdentifierInfo *Id,
3068 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003069 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003070 EnumConstantDecl *LastEnumConst =
3071 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3072 Expr *Val = static_cast<Expr*>(val);
3073
Chris Lattner31e05722007-08-26 06:24:45 +00003074 // The scope passed in may not be a decl scope. Zip up the scope tree until
3075 // we find one that is.
3076 while ((S->getFlags() & Scope::DeclScope) == 0)
3077 S = S->getParent();
3078
Reid Spencer5f016e22007-07-11 17:01:13 +00003079 // Verify that there isn't already something declared with this name in this
3080 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003081 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003082 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003083 // Maybe we will complain about the shadowed template parameter.
3084 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3085 // Just pretend that we didn't see the previous declaration.
3086 PrevDecl = 0;
3087 }
3088
3089 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003090 // When in C++, we may get a TagDecl with the same name; in this case the
3091 // enum constant will 'hide' the tag.
3092 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3093 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003094 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003095 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003096 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003097 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003098 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003099 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003100 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003101 return 0;
3102 }
3103 }
3104
3105 llvm::APSInt EnumVal(32);
3106 QualType EltTy;
3107 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003108 // Make sure to promote the operand type to int.
3109 UsualUnaryConversions(Val);
3110
Reid Spencer5f016e22007-07-11 17:01:13 +00003111 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3112 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003113 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003114 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003115 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003116 } else {
3117 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003118 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003119 }
3120
3121 if (!Val) {
3122 if (LastEnumConst) {
3123 // Assign the last value + 1.
3124 EnumVal = LastEnumConst->getInitVal();
3125 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003126
3127 // Check for overflow on increment.
3128 if (EnumVal < LastEnumConst->getInitVal())
3129 Diag(IdLoc, diag::warn_enum_value_overflow);
3130
Chris Lattnerb7416f92007-08-27 17:37:24 +00003131 EltTy = LastEnumConst->getType();
3132 } else {
3133 // First value, set to zero.
3134 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003135 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003136 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003137 }
3138
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003139 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003140 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3141 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003142 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003143
3144 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003145 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003146
3147 // Add this enumerator into the enum itself.
3148 // FIXME: This means that the enumerator is stored in two
3149 // DeclContexts. This is not a long-term solution.
3150 New->setLexicalDeclContext(TheEnumDecl);
3151 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003152 return New;
3153}
3154
Steve Naroff02408c62008-08-07 14:08:16 +00003155// FIXME: For consistency with ActOnFields(), we should have the parser
3156// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003157void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003158 DeclTy **Elements, unsigned NumElements) {
3159 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00003160
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003161 if (Enum) {
3162 if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) {
3163 // Diagnose code like:
3164 // enum e0 {
3165 // E0 = sizeof(enum e0 { E1 })
3166 // };
3167 Diag(Def->getLocation(), diag::err_nested_redefinition)
3168 << Enum->getDeclName();
3169 Diag(Enum->getLocation(), diag::note_previous_definition);
3170 Enum->setInvalidDecl();
3171 return;
3172 }
Steve Naroff02408c62008-08-07 14:08:16 +00003173 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00003174 // TODO: If the result value doesn't fit in an int, it must be a long or long
3175 // long value. ISO C does not support this, but GCC does as an extension,
3176 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003177 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003178
Chris Lattnerac609682007-08-28 06:15:15 +00003179 // Verify that all the values are okay, compute the size of the values, and
3180 // reverse the list.
3181 unsigned NumNegativeBits = 0;
3182 unsigned NumPositiveBits = 0;
3183
3184 // Keep track of whether all elements have type int.
3185 bool AllElementsInt = true;
3186
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003187 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003188 EnumConstantDecl *EltList = 0;
3189 for (unsigned i = 0; i != NumElements; ++i) {
3190 EnumConstantDecl *ECD =
3191 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3192 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003193
3194 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003195 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003196 assert(InitVal.getBitWidth() >= IntWidth &&
3197 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003198 if (InitVal.getBitWidth() > IntWidth) {
3199 llvm::APSInt V(InitVal);
3200 V.trunc(IntWidth);
3201 V.extend(InitVal.getBitWidth());
3202 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003203 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3204 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003205 }
Chris Lattnerac609682007-08-28 06:15:15 +00003206
3207 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003208 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003209 NumPositiveBits = std::max(NumPositiveBits,
3210 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003211 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003212 NumNegativeBits = std::max(NumNegativeBits,
3213 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003214
Chris Lattnerac609682007-08-28 06:15:15 +00003215 // Keep track of whether every enum element has type int (very commmon).
3216 if (AllElementsInt)
3217 AllElementsInt = ECD->getType() == Context.IntTy;
3218
Reid Spencer5f016e22007-07-11 17:01:13 +00003219 ECD->setNextDeclarator(EltList);
3220 EltList = ECD;
3221 }
3222
Chris Lattnerac609682007-08-28 06:15:15 +00003223 // Figure out the type that should be used for this enum.
3224 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3225 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003226 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003227
3228 if (NumNegativeBits) {
3229 // If there is a negative value, figure out the smallest integer type (of
3230 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003231 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003232 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003233 BestWidth = IntWidth;
3234 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003235 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003236
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003237 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003238 BestType = Context.LongTy;
3239 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003240 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003241
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003242 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003243 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3244 BestType = Context.LongLongTy;
3245 }
3246 }
3247 } else {
3248 // If there is no negative value, figure out which of uint, ulong, ulonglong
3249 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003250 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003251 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003252 BestWidth = IntWidth;
3253 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003254 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003255 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003256 } else {
3257 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003258 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003259 "How could an initializer get larger than ULL?");
3260 BestType = Context.UnsignedLongLongTy;
3261 }
3262 }
3263
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003264 // Loop over all of the enumerator constants, changing their types to match
3265 // the type of the enum if needed.
3266 for (unsigned i = 0; i != NumElements; ++i) {
3267 EnumConstantDecl *ECD =
3268 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3269 if (!ECD) continue; // Already issued a diagnostic.
3270
3271 // Standard C says the enumerators have int type, but we allow, as an
3272 // extension, the enumerators to be larger than int size. If each
3273 // enumerator value fits in an int, type it as an int, otherwise type it the
3274 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3275 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003276 if (ECD->getType() == Context.IntTy) {
3277 // Make sure the init value is signed.
3278 llvm::APSInt IV = ECD->getInitVal();
3279 IV.setIsSigned(true);
3280 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003281
3282 if (getLangOptions().CPlusPlus)
3283 // C++ [dcl.enum]p4: Following the closing brace of an
3284 // enum-specifier, each enumerator has the type of its
3285 // enumeration.
3286 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003287 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003288 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003289
3290 // Determine whether the value fits into an int.
3291 llvm::APSInt InitVal = ECD->getInitVal();
3292 bool FitsInInt;
3293 if (InitVal.isUnsigned() || !InitVal.isNegative())
3294 FitsInInt = InitVal.getActiveBits() < IntWidth;
3295 else
3296 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3297
3298 // If it fits into an integer type, force it. Otherwise force it to match
3299 // the enum decl type.
3300 QualType NewTy;
3301 unsigned NewWidth;
3302 bool NewSign;
3303 if (FitsInInt) {
3304 NewTy = Context.IntTy;
3305 NewWidth = IntWidth;
3306 NewSign = true;
3307 } else if (ECD->getType() == BestType) {
3308 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003309 if (getLangOptions().CPlusPlus)
3310 // C++ [dcl.enum]p4: Following the closing brace of an
3311 // enum-specifier, each enumerator has the type of its
3312 // enumeration.
3313 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003314 continue;
3315 } else {
3316 NewTy = BestType;
3317 NewWidth = BestWidth;
3318 NewSign = BestType->isSignedIntegerType();
3319 }
3320
3321 // Adjust the APSInt value.
3322 InitVal.extOrTrunc(NewWidth);
3323 InitVal.setIsSigned(NewSign);
3324 ECD->setInitVal(InitVal);
3325
3326 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003327 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3328 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003329 if (getLangOptions().CPlusPlus)
3330 // C++ [dcl.enum]p4: Following the closing brace of an
3331 // enum-specifier, each enumerator has the type of its
3332 // enumeration.
3333 ECD->setType(EnumType);
3334 else
3335 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003336 }
Chris Lattnerac609682007-08-28 06:15:15 +00003337
Douglas Gregor44b43212008-12-11 16:49:14 +00003338 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003339 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003340}
3341
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003342Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003343 ExprArg expr) {
3344 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3345
Chris Lattner8e25d862008-03-16 00:16:02 +00003346 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003347}
3348
Douglas Gregorf44515a2008-12-16 22:23:02 +00003349
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003350void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3351 ExprTy *alignment, SourceLocation PragmaLoc,
3352 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3353 Expr *Alignment = static_cast<Expr *>(alignment);
3354
3355 // If specified then alignment must be a "small" power of two.
3356 unsigned AlignmentVal = 0;
3357 if (Alignment) {
3358 llvm::APSInt Val;
3359 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3360 !Val.isPowerOf2() ||
3361 Val.getZExtValue() > 16) {
3362 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3363 delete Alignment;
3364 return; // Ignore
3365 }
3366
3367 AlignmentVal = (unsigned) Val.getZExtValue();
3368 }
3369
3370 switch (Kind) {
3371 case Action::PPK_Default: // pack([n])
3372 PackContext.setAlignment(AlignmentVal);
3373 break;
3374
3375 case Action::PPK_Show: // pack(show)
3376 // Show the current alignment, making sure to show the right value
3377 // for the default.
3378 AlignmentVal = PackContext.getAlignment();
3379 // FIXME: This should come from the target.
3380 if (AlignmentVal == 0)
3381 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003382 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003383 break;
3384
3385 case Action::PPK_Push: // pack(push [, id] [, [n])
3386 PackContext.push(Name);
3387 // Set the new alignment if specified.
3388 if (Alignment)
3389 PackContext.setAlignment(AlignmentVal);
3390 break;
3391
3392 case Action::PPK_Pop: // pack(pop [, id] [, n])
3393 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3394 // "#pragma pack(pop, identifier, n) is undefined"
3395 if (Alignment && Name)
3396 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3397
3398 // Do the pop.
3399 if (!PackContext.pop(Name)) {
3400 // If a name was specified then failure indicates the name
3401 // wasn't found. Otherwise failure indicates the stack was
3402 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003403 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3404 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003405
3406 // FIXME: Warn about popping named records as MSVC does.
3407 } else {
3408 // Pop succeeded, set the new alignment if specified.
3409 if (Alignment)
3410 PackContext.setAlignment(AlignmentVal);
3411 }
3412 break;
3413
3414 default:
3415 assert(0 && "Invalid #pragma pack kind.");
3416 }
3417}
3418
3419bool PragmaPackStack::pop(IdentifierInfo *Name) {
3420 if (Stack.empty())
3421 return false;
3422
3423 // If name is empty just pop top.
3424 if (!Name) {
3425 Alignment = Stack.back().first;
3426 Stack.pop_back();
3427 return true;
3428 }
3429
3430 // Otherwise, find the named record.
3431 for (unsigned i = Stack.size(); i != 0; ) {
3432 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003433 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003434 // Found it, pop up to and including this record.
3435 Alignment = Stack[i].first;
3436 Stack.erase(Stack.begin() + i, Stack.end());
3437 return true;
3438 }
3439 }
3440
3441 return false;
3442}