blob: 925a7bb29b56947048cc9e73f83ba589bcb304ee [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();
Steve Narofff0090632007-09-02 02:04:30 +0000747
Chris Lattner5cf216b2008-01-04 18:04:52 +0000748 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
749 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
750 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000751}
752
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000753bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000754 const ArrayType *AT = Context.getAsArrayType(DeclT);
755
756 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000757 // C99 6.7.8p14. We have an array of character type with unknown size
758 // being initialized to a string literal.
759 llvm::APSInt ConstVal(32);
760 ConstVal = strLiteral->getByteLength() + 1;
761 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000762 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000763 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000764 } else {
765 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000766 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000767 // FIXME: Avoid truncation for 64-bit length strings.
768 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000769 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000770 diag::warn_initializer_string_for_char_array_too_long)
771 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000772 }
773 // Set type from "char *" to "constant array of char".
774 strLiteral->setType(DeclT);
775 // For now, we always return false (meaning success).
776 return false;
777}
778
779StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000780 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000781 if (AT && AT->getElementType()->isCharType()) {
782 return dyn_cast<StringLiteral>(Init);
783 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000784 return 0;
785}
786
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000787bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
788 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000789 DeclarationName InitEntity) {
Douglas Gregor264c8ed2008-12-18 21:49:58 +0000790 if (DeclType->isDependentType() || Init->isTypeDependent())
791 return false;
792
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000793 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000794 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000795 // (8.3.2), shall be initialized by an object, or function, of
796 // type T or by an object that can be converted into a T.
797 if (DeclType->isReferenceType())
798 return CheckReferenceInit(Init, DeclType);
799
Steve Naroffca107302008-01-21 23:53:58 +0000800 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
801 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000802 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000803 return Diag(InitLoc, diag::err_variable_object_no_init)
804 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000805
Steve Naroff2fdc3742007-12-10 22:44:33 +0000806 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
807 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000808 // FIXME: Handle wide strings
809 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
810 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000811
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000812 // C++ [dcl.init]p14:
813 // -- If the destination type is a (possibly cv-qualified) class
814 // type:
815 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
816 QualType DeclTypeC = Context.getCanonicalType(DeclType);
817 QualType InitTypeC = Context.getCanonicalType(Init->getType());
818
819 // -- If the initialization is direct-initialization, or if it is
820 // copy-initialization where the cv-unqualified version of the
821 // source type is the same class as, or a derived class of, the
822 // class of the destination, constructors are considered.
823 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
824 IsDerivedFrom(InitTypeC, DeclTypeC)) {
825 CXXConstructorDecl *Constructor
826 = PerformInitializationByConstructor(DeclType, &Init, 1,
827 InitLoc, Init->getSourceRange(),
828 InitEntity, IK_Copy);
829 return Constructor == 0;
830 }
831
832 // -- Otherwise (i.e., for the remaining copy-initialization
833 // cases), user-defined conversion sequences that can
834 // convert from the source type to the destination type or
835 // (when a conversion function is used) to a derived class
836 // thereof are enumerated as described in 13.3.1.4, and the
837 // best one is chosen through overload resolution
838 // (13.3). If the conversion cannot be done or is
839 // ambiguous, the initialization is ill-formed. The
840 // function selected is called with the initializer
841 // expression as its argument; if the function is a
842 // constructor, the call initializes a temporary of the
843 // destination type.
844 // FIXME: We're pretending to do copy elision here; return to
845 // this when we have ASTs for such things.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000846 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000847 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000848
849 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000850 << DeclType << InitEntity << "initializing"
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000851 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000852 }
853
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000854 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000855 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000856 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
857 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000858
Steve Naroffd0091aa2008-01-10 22:15:12 +0000859 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000860 } else if (getLangOptions().CPlusPlus) {
861 // C++ [dcl.init]p14:
862 // [...] If the class is an aggregate (8.5.1), and the initializer
863 // is a brace-enclosed list, see 8.5.1.
864 //
865 // Note: 8.5.1 is handled below; here, we diagnose the case where
866 // we have an initializer list and a destination type that is not
867 // an aggregate.
868 // FIXME: In C++0x, this is yet another form of initialization.
869 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
870 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
871 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000872 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000873 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000874 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000875 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000876
Steve Naroff0cca7492008-05-01 22:18:59 +0000877 InitListChecker CheckInitList(this, InitList, DeclType);
878 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000879}
880
Douglas Gregor10bd3682008-11-17 22:58:34 +0000881/// GetNameForDeclarator - Determine the full declaration name for the
882/// given Declarator.
883DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
884 switch (D.getKind()) {
885 case Declarator::DK_Abstract:
886 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
887 return DeclarationName();
888
889 case Declarator::DK_Normal:
890 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
891 return DeclarationName(D.getIdentifier());
892
893 case Declarator::DK_Constructor: {
894 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
895 Ty = Context.getCanonicalType(Ty);
896 return Context.DeclarationNames.getCXXConstructorName(Ty);
897 }
898
899 case Declarator::DK_Destructor: {
900 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
901 Ty = Context.getCanonicalType(Ty);
902 return Context.DeclarationNames.getCXXDestructorName(Ty);
903 }
904
905 case Declarator::DK_Conversion: {
906 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
907 Ty = Context.getCanonicalType(Ty);
908 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
909 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000910
911 case Declarator::DK_Operator:
912 assert(D.getIdentifier() == 0 && "operator names have no identifier");
913 return Context.DeclarationNames.getCXXOperatorName(
914 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000915 }
916
917 assert(false && "Unknown name kind");
918 return DeclarationName();
919}
920
Douglas Gregor584049d2008-12-15 23:53:10 +0000921/// isNearlyMatchingMemberFunction - Determine whether the C++ member
922/// functions Declaration and Definition are "nearly" matching. This
923/// heuristic is used to improve diagnostics in the case where an
924/// out-of-line member function definition doesn't match any
925/// declaration within the class.
926static bool isNearlyMatchingMemberFunction(ASTContext &Context,
927 FunctionDecl *Declaration,
928 FunctionDecl *Definition) {
929 if (Declaration->param_size() != Definition->param_size())
930 return false;
931 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
932 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
933 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
934
935 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
936 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
937 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
938 return false;
939 }
940
941 return true;
942}
943
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000944Sema::DeclTy *
Douglas Gregor584049d2008-12-15 23:53:10 +0000945Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
946 bool IsFunctionDefinition) {
Steve Naroff94745042007-09-13 23:52:58 +0000947 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000948 DeclarationName Name = GetNameForDeclarator(D);
949
Chris Lattnere80a59c2007-07-25 00:24:17 +0000950 // All of these full declarators require an identifier. If it doesn't have
951 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000952 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000953 if (!D.getInvalidType()) // Reject this if we think it is valid.
954 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000955 diag::err_declarator_need_ident)
956 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000957 return 0;
958 }
959
Chris Lattner31e05722007-08-26 06:24:45 +0000960 // The scope passed in may not be a decl scope. Zip up the scope tree until
961 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +0000962 while ((S->getFlags() & Scope::DeclScope) == 0 ||
963 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +0000964 S = S->getParent();
965
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000966 DeclContext *DC;
967 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000968 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000969 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000970
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000971 // See if this is a redefinition of a variable in the same scope.
972 if (!D.getCXXScopeSpec().isSet()) {
973 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +0000974 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000975 } else { // Something like "int foo::x;"
976 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000977 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000978
979 // C++ 7.3.1.2p2:
980 // Members (including explicit specializations of templates) of a named
981 // namespace can also be defined outside that namespace by explicit
982 // qualification of the name being defined, provided that the entity being
983 // defined was already declared in the namespace and the definition appears
984 // after the point of declaration in a namespace that encloses the
985 // declarations namespace.
986 //
Douglas Gregor584049d2008-12-15 23:53:10 +0000987 // Note that we only check the context at this point. We don't yet
988 // have enough information to make sure that PrevDecl is actually
989 // the declaration we want to match. For example, given:
990 //
Douglas Gregor9d350972008-12-12 08:25:50 +0000991 // class X {
992 // void f();
Douglas Gregor584049d2008-12-15 23:53:10 +0000993 // void f(float);
Douglas Gregor9d350972008-12-12 08:25:50 +0000994 // };
995 //
Douglas Gregor584049d2008-12-15 23:53:10 +0000996 // void X::f(int) { } // ill-formed
997 //
998 // In this case, PrevDecl will point to the overload set
999 // containing the two f's declared in X, but neither of them
1000 // matches.
1001 if (!CurContext->Encloses(DC)) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001002 // The qualifying scope doesn't enclose the original declaration.
1003 // Emit diagnostic based on current scope.
1004 SourceLocation L = D.getIdentifierLoc();
1005 SourceRange R = D.getCXXScopeSpec().getRange();
1006 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001007 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001008 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +00001009 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001010 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001011 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001012 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001013 }
1014 }
1015
Douglas Gregorf57172b2008-12-08 18:40:42 +00001016 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00001017 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +00001018 InvalidDecl = InvalidDecl
1019 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +00001020 // Just pretend that we didn't see the previous declaration.
1021 PrevDecl = 0;
1022 }
1023
Douglas Gregor2ce52f32008-04-13 21:07:44 +00001024 // In C++, the previous declaration we find might be a tag type
1025 // (class or enum). In this case, the new declaration will hide the
1026 // tag type.
1027 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1028 PrevDecl = 0;
1029
Chris Lattner41af0932007-11-14 06:34:38 +00001030 QualType R = GetTypeForDeclarator(D, S);
1031 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1032
Reid Spencer5f016e22007-07-11 17:01:13 +00001033 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001034 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1035 if (D.getCXXScopeSpec().isSet()) {
1036 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1037 << D.getCXXScopeSpec().getRange();
1038 InvalidDecl = true;
1039 // Pretend we didn't see the scope specifier.
1040 DC = 0;
1041 }
1042
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001043 // Check that there are no default arguments (C++ only).
1044 if (getLangOptions().CPlusPlus)
1045 CheckExtraCXXDefaultArguments(D);
1046
Chris Lattner41af0932007-11-14 06:34:38 +00001047 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +00001048 if (!NewTD) return 0;
1049
1050 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001051 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +00001052 // Merge the decl with the existing one if appropriate. If the decl is
1053 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001054 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001055 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1056 if (NewTD == 0) return 0;
1057 }
1058 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001059 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001060 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1061 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +00001062 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00001063 if (NewTD->getUnderlyingType()->isVariableArrayType())
1064 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1065 else
1066 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1067
Steve Naroffd7444aa2007-08-31 17:20:07 +00001068 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +00001069 }
1070 }
Chris Lattner41af0932007-11-14 06:34:38 +00001071 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001072 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001073 switch (D.getDeclSpec().getStorageClassSpec()) {
1074 default: assert(0 && "Unknown storage class!");
1075 case DeclSpec::SCS_auto:
1076 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001077 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001078 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001079 InvalidDecl = true;
1080 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001081 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1082 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1083 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001084 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001085 }
1086
Chris Lattnera98e58d2008-03-15 21:24:04 +00001087 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001088 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001089 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1090
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001091 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001092 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001093 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001094 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001095 "Constructors can only be declared in a member context");
1096
Douglas Gregor42a552f2008-11-05 20:51:48 +00001097 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001098
1099 // Create the new declaration
1100 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001101 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001102 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001103 isExplicit, isInline,
1104 /*isImplicitlyDeclared=*/false);
1105
Douglas Gregor42a552f2008-11-05 20:51:48 +00001106 if (isInvalidDecl)
1107 NewFD->setInvalidDecl();
1108 } else if (D.getKind() == Declarator::DK_Destructor) {
1109 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001110 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001111 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001112
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001113 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001114 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001115 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001116 isInline,
1117 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001118
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001119 if (isInvalidDecl)
1120 NewFD->setInvalidDecl();
1121 } else {
1122 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1123 // Create a FunctionDecl to satisfy the function definition parsing
1124 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001125 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001126 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001127 // FIXME: Move to DeclGroup...
1128 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001129 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001130 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001131 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001132 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001133 Diag(D.getIdentifierLoc(),
1134 diag::err_conv_function_not_member);
1135 return 0;
1136 } else {
1137 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1138
1139 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001140 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001141 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001142 isInline, isExplicit);
1143
1144 if (isInvalidDecl)
1145 NewFD->setInvalidDecl();
1146 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001147 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001148 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001149 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001150 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001151 (SC == FunctionDecl::Static), isInline,
1152 LastDeclarator);
1153 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001154 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001155 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001156 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001157 // FIXME: Move to DeclGroup...
1158 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001159 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001160
Ted Kremenekf5c93c12008-02-27 22:18:07 +00001161 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001162 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +00001163
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001164 // Set the lexical context. If the declarator has a C++
1165 // scope specifier, the lexical context will be different
1166 // from the semantic context.
1167 NewFD->setLexicalDeclContext(CurContext);
1168
Daniel Dunbara80f8742008-08-05 01:35:17 +00001169 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001170 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001171 // The parser guarantees this is a string.
1172 StringLiteral *SE = cast<StringLiteral>(E);
1173 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1174 SE->getByteLength())));
1175 }
1176
Chris Lattner04421082008-04-08 04:40:51 +00001177 // Copy the parameter declarations from the declarator D to
1178 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001179 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001180 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1181
1182 // Create Decl objects for each parameter, adding them to the
1183 // FunctionDecl.
1184 llvm::SmallVector<ParmVarDecl*, 16> Params;
1185
1186 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1187 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001188 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001189 // We let through "const void" here because Sema::GetTypeForDeclarator
1190 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001191 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1192 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001193 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1194 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001195 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1196
Chris Lattnerdef026a2008-04-10 02:26:16 +00001197 // In C++, the empty parameter-type-list must be spelled "void"; a
1198 // typedef of void is not permitted.
1199 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001200 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001201 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1202 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001203 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001204 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1205 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1206 }
1207
1208 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001209 } else if (R->getAsTypedefType()) {
1210 // When we're declaring a function with a typedef, as in the
1211 // following example, we'll need to synthesize (unnamed)
1212 // parameters for use in the declaration.
1213 //
1214 // @code
1215 // typedef void fn(int);
1216 // fn f;
1217 // @endcode
1218 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1219 if (!FT) {
1220 // This is a typedef of a function with no prototype, so we
1221 // don't need to do anything.
1222 } else if ((FT->getNumArgs() == 0) ||
1223 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1224 FT->getArgType(0)->isVoidType())) {
1225 // This is a zero-argument function. We don't need to do anything.
1226 } else {
1227 // Synthesize a parameter for each argument type.
1228 llvm::SmallVector<ParmVarDecl*, 16> Params;
1229 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1230 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001231 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001232 SourceLocation(), 0,
1233 *ArgType, VarDecl::None,
1234 0, 0));
1235 }
1236
1237 NewFD->setParams(&Params[0], Params.size());
1238 }
Chris Lattner04421082008-04-08 04:40:51 +00001239 }
1240
Douglas Gregor72b505b2008-12-16 21:30:33 +00001241 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1242 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00001243 else if (isa<CXXDestructorDecl>(NewFD))
1244 cast<CXXRecordDecl>(NewFD->getParent())->setUserDeclaredDestructor(true);
1245 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregor2def4832008-11-17 20:34:05 +00001246 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001247
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001248 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1249 if (NewFD->isOverloadedOperator() &&
1250 CheckOverloadedOperatorDeclaration(NewFD))
1251 NewFD->setInvalidDecl();
1252
Steve Naroffffce4d52008-01-09 23:34:55 +00001253 // Merge the decl with the existing one if appropriate. Since C functions
1254 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001255 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001256 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001257 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001258
1259 // If C++, determine whether NewFD is an overload of PrevDecl or
1260 // a declaration that requires merging. If it's an overload,
1261 // there's no more work to do here; we'll just add the new
1262 // function to the scope.
1263 OverloadedFunctionDecl::function_iterator MatchedDecl;
1264 if (!getLangOptions().CPlusPlus ||
1265 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1266 Decl *OldDecl = PrevDecl;
1267
1268 // If PrevDecl was an overloaded function, extract the
1269 // FunctionDecl that matched.
1270 if (isa<OverloadedFunctionDecl>(PrevDecl))
1271 OldDecl = *MatchedDecl;
1272
1273 // NewFD and PrevDecl represent declarations that need to be
1274 // merged.
1275 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1276
1277 if (NewFD == 0) return 0;
1278 if (Redeclaration) {
1279 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1280
1281 if (OldDecl == PrevDecl) {
1282 // Remove the name binding for the previous
Douglas Gregor44b43212008-12-11 16:49:14 +00001283 // declaration.
1284 if (S->isDeclScope(PrevDecl)) {
1285 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1286 S->RemoveDecl(PrevDecl);
1287 }
1288
1289 // Introduce the new binding for this declaration.
1290 IdResolver.AddDecl(NewFD);
1291 if (getLangOptions().CPlusPlus && NewFD->getParent())
1292 NewFD->getParent()->insert(Context, NewFD);
1293
1294 // Add the redeclaration to the current scope, since we'll
1295 // be skipping PushOnScopeChains.
1296 S->AddDecl(NewFD);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001297 } else {
1298 // We need to update the OverloadedFunctionDecl with the
1299 // latest declaration of this function, so that name
1300 // lookup will always refer to the latest declaration of
1301 // this function.
1302 *MatchedDecl = NewFD;
Douglas Gregor44b43212008-12-11 16:49:14 +00001303 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001304
Douglas Gregor44b43212008-12-11 16:49:14 +00001305 if (getLangOptions().CPlusPlus) {
1306 // Add this declaration to the current context.
1307 CurContext->addDecl(Context, NewFD, false);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001308
Douglas Gregor44b43212008-12-11 16:49:14 +00001309 // Check default arguments now that we have merged decls.
1310 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001311
1312 // An out-of-line member function declaration must also be a
1313 // definition (C++ [dcl.meaning]p1).
1314 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1315 !InvalidDecl) {
1316 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1317 << D.getCXXScopeSpec().getRange();
1318 NewFD->setInvalidDecl();
1319 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001320 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001321
Douglas Gregor44b43212008-12-11 16:49:14 +00001322 return NewFD;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001323 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001324 }
Douglas Gregor584049d2008-12-15 23:53:10 +00001325
1326 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1327 // The user tried to provide an out-of-line definition for a
1328 // member function, but there was no such member function
1329 // declared (C++ [class.mfct]p2). For example:
1330 //
1331 // class X {
1332 // void f() const;
1333 // };
1334 //
1335 // void X::f() { } // ill-formed
1336 //
1337 // Complain about this problem, and attempt to suggest close
1338 // matches (e.g., those that differ only in cv-qualifiers and
1339 // whether the parameter types are references).
1340 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1341 << cast<CXXRecordDecl>(DC)->getDeclName()
1342 << D.getCXXScopeSpec().getRange();
1343 InvalidDecl = true;
1344
1345 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1346 if (!PrevDecl) {
1347 // Nothing to suggest.
1348 } else if (OverloadedFunctionDecl *Ovl
1349 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1350 for (OverloadedFunctionDecl::function_iterator
1351 Func = Ovl->function_begin(),
1352 FuncEnd = Ovl->function_end();
1353 Func != FuncEnd; ++Func) {
1354 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1355 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1356
1357 }
1358 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1359 // Suggest this no matter how mismatched it is; it's the only
1360 // thing we have.
1361 unsigned diag;
1362 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1363 diag = diag::note_member_def_close_match;
1364 else if (Method->getBody())
1365 diag = diag::note_previous_definition;
1366 else
1367 diag = diag::note_previous_declaration;
1368 Diag(Method->getLocation(), diag);
1369 }
1370
1371 PrevDecl = 0;
1372 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001373 }
1374 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001375
Douglas Gregor584049d2008-12-15 23:53:10 +00001376 if (getLangOptions().CPlusPlus) {
1377 // In C++, check default arguments now that we have merged decls.
Chris Lattner04421082008-04-08 04:40:51 +00001378 CheckCXXDefaultArguments(NewFD);
Douglas Gregor584049d2008-12-15 23:53:10 +00001379
1380 // An out-of-line member function declaration must also be a
1381 // definition (C++ [dcl.meaning]p1).
1382 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet()) {
1383 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1384 << D.getCXXScopeSpec().getRange();
1385 InvalidDecl = true;
1386 }
1387 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001388 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001389 // Check that there are no default arguments (C++ only).
1390 if (getLangOptions().CPlusPlus)
1391 CheckExtraCXXDefaultArguments(D);
1392
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001393 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001394 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1395 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001396 InvalidDecl = true;
1397 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001398
1399 VarDecl *NewVD;
1400 VarDecl::StorageClass SC;
1401 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001402 default: assert(0 && "Unknown storage class!");
1403 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1404 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1405 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1406 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1407 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1408 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001409 case DeclSpec::SCS_mutable:
1410 // mutable can only appear on non-static class members, so it's always
1411 // an error here
1412 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1413 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001414 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001415 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001416 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001417
1418 IdentifierInfo *II = Name.getAsIdentifierInfo();
1419 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001420 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1421 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001422 return 0;
1423 }
1424
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001425 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001426 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001427 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001428 D.getIdentifierLoc(), II,
1429 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001430 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001431 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001432 if (S->getFnParent() == 0) {
1433 // C99 6.9p2: The storage-class specifiers auto and register shall not
1434 // appear in the declaration specifiers in an external declaration.
1435 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001436 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001437 InvalidDecl = true;
1438 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001439 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001440 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1441 II, R, SC, LastDeclarator,
1442 // FIXME: Move to DeclGroup...
1443 D.getDeclSpec().getSourceRange().getBegin());
1444 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001445 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001446 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001447 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001448
Daniel Dunbara735ad82008-08-06 00:03:29 +00001449 // Handle GNU asm-label extension (encoded as an attribute).
1450 if (Expr *E = (Expr*) D.getAsmLabel()) {
1451 // The parser guarantees this is a string.
1452 StringLiteral *SE = cast<StringLiteral>(E);
1453 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1454 SE->getByteLength())));
1455 }
1456
Nate Begemanc8e89a82008-03-14 18:07:10 +00001457 // Emit an error if an address space was applied to decl with local storage.
1458 // This includes arrays of objects with address space qualifiers, but not
1459 // automatic variables that point to other address spaces.
1460 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001461 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1462 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1463 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001464 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001465 // Merge the decl with the existing one if appropriate. If the decl is
1466 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001467 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregor584049d2008-12-15 23:53:10 +00001468 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1469 // The user tried to define a non-static data member
1470 // out-of-line (C++ [dcl.meaning]p1).
1471 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1472 << D.getCXXScopeSpec().getRange();
1473 NewVD->Destroy(Context);
1474 return 0;
1475 }
1476
Reid Spencer5f016e22007-07-11 17:01:13 +00001477 NewVD = MergeVarDecl(NewVD, PrevDecl);
1478 if (NewVD == 0) return 0;
Douglas Gregor584049d2008-12-15 23:53:10 +00001479
1480 if (D.getCXXScopeSpec().isSet()) {
1481 // No previous declaration in the qualifying scope.
1482 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1483 << Name << D.getCXXScopeSpec().getRange();
1484 InvalidDecl = true;
1485 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001486 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001487 New = NewVD;
1488 }
1489
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001490 // Set the lexical context. If the declarator has a C++ scope specifier, the
1491 // lexical context will be different from the semantic context.
1492 New->setLexicalDeclContext(CurContext);
1493
Reid Spencer5f016e22007-07-11 17:01:13 +00001494 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001495 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001496 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001497 // If any semantic error occurred, mark the decl as invalid.
1498 if (D.getInvalidType() || InvalidDecl)
1499 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001500
1501 return New;
1502}
1503
Steve Naroff6594a702008-10-27 11:34:16 +00001504void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001505 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1506 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001507}
1508
Eli Friedmanc594b322008-05-20 13:48:25 +00001509bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1510 switch (Init->getStmtClass()) {
1511 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001512 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001513 return true;
1514 case Expr::ParenExprClass: {
1515 const ParenExpr* PE = cast<ParenExpr>(Init);
1516 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1517 }
1518 case Expr::CompoundLiteralExprClass:
1519 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1520 case Expr::DeclRefExprClass: {
1521 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001522 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1523 if (VD->hasGlobalStorage())
1524 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001525 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001526 return true;
1527 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001528 if (isa<FunctionDecl>(D))
1529 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001530 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001531 return true;
1532 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001533 case Expr::MemberExprClass: {
1534 const MemberExpr *M = cast<MemberExpr>(Init);
1535 if (M->isArrow())
1536 return CheckAddressConstantExpression(M->getBase());
1537 return CheckAddressConstantExpressionLValue(M->getBase());
1538 }
1539 case Expr::ArraySubscriptExprClass: {
1540 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1541 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1542 return CheckAddressConstantExpression(ASE->getBase()) ||
1543 CheckArithmeticConstantExpression(ASE->getIdx());
1544 }
1545 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001546 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001547 return false;
1548 case Expr::UnaryOperatorClass: {
1549 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1550
1551 // C99 6.6p9
1552 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001553 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001554
Steve Naroff6594a702008-10-27 11:34:16 +00001555 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001556 return true;
1557 }
1558 }
1559}
1560
1561bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1562 switch (Init->getStmtClass()) {
1563 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001564 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001565 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001566 case Expr::ParenExprClass:
1567 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001568 case Expr::StringLiteralClass:
1569 case Expr::ObjCStringLiteralClass:
1570 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001571 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001572 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001573 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1574 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1575 Builtin::BI__builtin___CFStringMakeConstantString)
1576 return false;
1577
Steve Naroff6594a702008-10-27 11:34:16 +00001578 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001579 return true;
1580
Eli Friedmanc594b322008-05-20 13:48:25 +00001581 case Expr::UnaryOperatorClass: {
1582 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1583
1584 // C99 6.6p9
1585 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1586 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1587
1588 if (Exp->getOpcode() == UnaryOperator::Extension)
1589 return CheckAddressConstantExpression(Exp->getSubExpr());
1590
Steve Naroff6594a702008-10-27 11:34:16 +00001591 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001592 return true;
1593 }
1594 case Expr::BinaryOperatorClass: {
1595 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1596 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1597
1598 Expr *PExp = Exp->getLHS();
1599 Expr *IExp = Exp->getRHS();
1600 if (IExp->getType()->isPointerType())
1601 std::swap(PExp, IExp);
1602
1603 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1604 return CheckAddressConstantExpression(PExp) ||
1605 CheckArithmeticConstantExpression(IExp);
1606 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001607 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001608 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001609 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001610 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1611 // Check for implicit promotion
1612 if (SubExpr->getType()->isFunctionType() ||
1613 SubExpr->getType()->isArrayType())
1614 return CheckAddressConstantExpressionLValue(SubExpr);
1615 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001616
1617 // Check for pointer->pointer cast
1618 if (SubExpr->getType()->isPointerType())
1619 return CheckAddressConstantExpression(SubExpr);
1620
Eli Friedmanc3f07642008-08-25 20:46:57 +00001621 if (SubExpr->getType()->isIntegralType()) {
1622 // Check for the special-case of a pointer->int->pointer cast;
1623 // this isn't standard, but some code requires it. See
1624 // PR2720 for an example.
1625 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1626 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1627 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1628 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1629 if (IntWidth >= PointerWidth) {
1630 return CheckAddressConstantExpression(SubCast->getSubExpr());
1631 }
1632 }
1633 }
1634 }
1635 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001636 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001637 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001638
Steve Naroff6594a702008-10-27 11:34:16 +00001639 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001640 return true;
1641 }
1642 case Expr::ConditionalOperatorClass: {
1643 // FIXME: Should we pedwarn here?
1644 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1645 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001646 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001647 return true;
1648 }
1649 if (CheckArithmeticConstantExpression(Exp->getCond()))
1650 return true;
1651 if (Exp->getLHS() &&
1652 CheckAddressConstantExpression(Exp->getLHS()))
1653 return true;
1654 return CheckAddressConstantExpression(Exp->getRHS());
1655 }
1656 case Expr::AddrLabelExprClass:
1657 return false;
1658 }
1659}
1660
Eli Friedman4caf0552008-06-09 05:05:07 +00001661static const Expr* FindExpressionBaseAddress(const Expr* E);
1662
1663static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1664 switch (E->getStmtClass()) {
1665 default:
1666 return E;
1667 case Expr::ParenExprClass: {
1668 const ParenExpr* PE = cast<ParenExpr>(E);
1669 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1670 }
1671 case Expr::MemberExprClass: {
1672 const MemberExpr *M = cast<MemberExpr>(E);
1673 if (M->isArrow())
1674 return FindExpressionBaseAddress(M->getBase());
1675 return FindExpressionBaseAddressLValue(M->getBase());
1676 }
1677 case Expr::ArraySubscriptExprClass: {
1678 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1679 return FindExpressionBaseAddress(ASE->getBase());
1680 }
1681 case Expr::UnaryOperatorClass: {
1682 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1683
1684 if (Exp->getOpcode() == UnaryOperator::Deref)
1685 return FindExpressionBaseAddress(Exp->getSubExpr());
1686
1687 return E;
1688 }
1689 }
1690}
1691
1692static const Expr* FindExpressionBaseAddress(const Expr* E) {
1693 switch (E->getStmtClass()) {
1694 default:
1695 return E;
1696 case Expr::ParenExprClass: {
1697 const ParenExpr* PE = cast<ParenExpr>(E);
1698 return FindExpressionBaseAddress(PE->getSubExpr());
1699 }
1700 case Expr::UnaryOperatorClass: {
1701 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1702
1703 // C99 6.6p9
1704 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1705 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1706
1707 if (Exp->getOpcode() == UnaryOperator::Extension)
1708 return FindExpressionBaseAddress(Exp->getSubExpr());
1709
1710 return E;
1711 }
1712 case Expr::BinaryOperatorClass: {
1713 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1714
1715 Expr *PExp = Exp->getLHS();
1716 Expr *IExp = Exp->getRHS();
1717 if (IExp->getType()->isPointerType())
1718 std::swap(PExp, IExp);
1719
1720 return FindExpressionBaseAddress(PExp);
1721 }
1722 case Expr::ImplicitCastExprClass: {
1723 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1724
1725 // Check for implicit promotion
1726 if (SubExpr->getType()->isFunctionType() ||
1727 SubExpr->getType()->isArrayType())
1728 return FindExpressionBaseAddressLValue(SubExpr);
1729
1730 // Check for pointer->pointer cast
1731 if (SubExpr->getType()->isPointerType())
1732 return FindExpressionBaseAddress(SubExpr);
1733
1734 // We assume that we have an arithmetic expression here;
1735 // if we don't, we'll figure it out later
1736 return 0;
1737 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001738 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001739 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1740
1741 // Check for pointer->pointer cast
1742 if (SubExpr->getType()->isPointerType())
1743 return FindExpressionBaseAddress(SubExpr);
1744
1745 // We assume that we have an arithmetic expression here;
1746 // if we don't, we'll figure it out later
1747 return 0;
1748 }
1749 }
1750}
1751
Anders Carlsson51fe9962008-11-22 21:04:56 +00001752bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001753 switch (Init->getStmtClass()) {
1754 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001755 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001756 return true;
1757 case Expr::ParenExprClass: {
1758 const ParenExpr* PE = cast<ParenExpr>(Init);
1759 return CheckArithmeticConstantExpression(PE->getSubExpr());
1760 }
1761 case Expr::FloatingLiteralClass:
1762 case Expr::IntegerLiteralClass:
1763 case Expr::CharacterLiteralClass:
1764 case Expr::ImaginaryLiteralClass:
1765 case Expr::TypesCompatibleExprClass:
1766 case Expr::CXXBoolLiteralExprClass:
1767 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001768 case Expr::CallExprClass:
1769 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001770 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001771
1772 // Allow any constant foldable calls to builtins.
1773 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001774 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001775
Steve Naroff6594a702008-10-27 11:34:16 +00001776 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001777 return true;
1778 }
1779 case Expr::DeclRefExprClass: {
1780 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1781 if (isa<EnumConstantDecl>(D))
1782 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001783 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001784 return true;
1785 }
1786 case Expr::CompoundLiteralExprClass:
1787 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1788 // but vectors are allowed to be magic.
1789 if (Init->getType()->isVectorType())
1790 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001791 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001792 return true;
1793 case Expr::UnaryOperatorClass: {
1794 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1795
1796 switch (Exp->getOpcode()) {
1797 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1798 // See C99 6.6p3.
1799 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001800 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001801 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001802 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001803 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1804 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001805 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001806 return true;
1807 case UnaryOperator::Extension:
1808 case UnaryOperator::LNot:
1809 case UnaryOperator::Plus:
1810 case UnaryOperator::Minus:
1811 case UnaryOperator::Not:
1812 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1813 }
1814 }
Sebastian Redl05189992008-11-11 17:56:53 +00001815 case Expr::SizeOfAlignOfExprClass: {
1816 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001817 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001818 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001819 return false;
1820 // alignof always evaluates to a constant.
1821 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001822 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001823 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001824 return true;
1825 }
1826 return false;
1827 }
1828 case Expr::BinaryOperatorClass: {
1829 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1830
1831 if (Exp->getLHS()->getType()->isArithmeticType() &&
1832 Exp->getRHS()->getType()->isArithmeticType()) {
1833 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1834 CheckArithmeticConstantExpression(Exp->getRHS());
1835 }
1836
Eli Friedman4caf0552008-06-09 05:05:07 +00001837 if (Exp->getLHS()->getType()->isPointerType() &&
1838 Exp->getRHS()->getType()->isPointerType()) {
1839 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1840 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1841
1842 // Only allow a null (constant integer) base; we could
1843 // allow some additional cases if necessary, but this
1844 // is sufficient to cover offsetof-like constructs.
1845 if (!LHSBase && !RHSBase) {
1846 return CheckAddressConstantExpression(Exp->getLHS()) ||
1847 CheckAddressConstantExpression(Exp->getRHS());
1848 }
1849 }
1850
Steve Naroff6594a702008-10-27 11:34:16 +00001851 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001852 return true;
1853 }
1854 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001855 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001856 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001857 if (SubExpr->getType()->isArithmeticType())
1858 return CheckArithmeticConstantExpression(SubExpr);
1859
Eli Friedmanb529d832008-09-02 09:37:00 +00001860 if (SubExpr->getType()->isPointerType()) {
1861 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1862 // If the pointer has a null base, this is an offsetof-like construct
1863 if (!Base)
1864 return CheckAddressConstantExpression(SubExpr);
1865 }
1866
Steve Naroff6594a702008-10-27 11:34:16 +00001867 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001868 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001869 }
1870 case Expr::ConditionalOperatorClass: {
1871 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001872
1873 // If GNU extensions are disabled, we require all operands to be arithmetic
1874 // constant expressions.
1875 if (getLangOptions().NoExtensions) {
1876 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1877 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1878 CheckArithmeticConstantExpression(Exp->getRHS());
1879 }
1880
1881 // Otherwise, we have to emulate some of the behavior of fold here.
1882 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1883 // because it can constant fold things away. To retain compatibility with
1884 // GCC code, we see if we can fold the condition to a constant (which we
1885 // should always be able to do in theory). If so, we only require the
1886 // specified arm of the conditional to be a constant. This is a horrible
1887 // hack, but is require by real world code that uses __builtin_constant_p.
1888 APValue Val;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001889 if (!Exp->getCond()->Evaluate(Val, Context)) {
1890 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001891 // won't be able to either. Use it to emit the diagnostic though.
1892 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001893 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001894 return Res;
1895 }
1896
1897 // Verify that the side following the condition is also a constant.
1898 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1899 if (Val.getInt() == 0)
1900 std::swap(TrueSide, FalseSide);
1901
1902 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001903 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001904
1905 // Okay, the evaluated side evaluates to a constant, so we accept this.
1906 // Check to see if the other side is obviously not a constant. If so,
1907 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001908 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001909 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001910 diag::ext_typecheck_expression_not_constant_but_accepted)
1911 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001912 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001913 }
1914 }
1915}
1916
1917bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001918 Expr::EvalResult Result;
1919
Nuno Lopes9a979c32008-07-07 16:46:50 +00001920 Init = Init->IgnoreParens();
1921
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001922 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1923 return false;
1924
Eli Friedmanc594b322008-05-20 13:48:25 +00001925 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1926 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1927 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1928
Nuno Lopes9a979c32008-07-07 16:46:50 +00001929 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1930 return CheckForConstantInitializer(e->getInitializer(), DclT);
1931
Eli Friedmanc594b322008-05-20 13:48:25 +00001932 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1933 unsigned numInits = Exp->getNumInits();
1934 for (unsigned i = 0; i < numInits; i++) {
1935 // FIXME: Need to get the type of the declaration for C++,
1936 // because it could be a reference?
1937 if (CheckForConstantInitializer(Exp->getInit(i),
1938 Exp->getInit(i)->getType()))
1939 return true;
1940 }
1941 return false;
1942 }
1943
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001944 // FIXME: We can probably remove some of this code below, now that
1945 // Expr::Evaluate is doing the heavy lifting for scalars.
1946
Eli Friedmanc594b322008-05-20 13:48:25 +00001947 if (Init->isNullPointerConstant(Context))
1948 return false;
1949 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001950 QualType InitTy = Context.getCanonicalType(Init->getType())
1951 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001952 if (InitTy == Context.BoolTy) {
1953 // Special handling for pointers implicitly cast to bool;
1954 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1955 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1956 Expr* SubE = ICE->getSubExpr();
1957 if (SubE->getType()->isPointerType() ||
1958 SubE->getType()->isArrayType() ||
1959 SubE->getType()->isFunctionType()) {
1960 return CheckAddressConstantExpression(Init);
1961 }
1962 }
1963 } else if (InitTy->isIntegralType()) {
1964 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001965 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001966 SubE = CE->getSubExpr();
1967 // Special check for pointer cast to int; we allow as an extension
1968 // an address constant cast to an integer if the integer
1969 // is of an appropriate width (this sort of code is apparently used
1970 // in some places).
1971 // FIXME: Add pedwarn?
1972 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1973 if (SubE && (SubE->getType()->isPointerType() ||
1974 SubE->getType()->isArrayType() ||
1975 SubE->getType()->isFunctionType())) {
1976 unsigned IntWidth = Context.getTypeSize(Init->getType());
1977 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1978 if (IntWidth >= PointerWidth)
1979 return CheckAddressConstantExpression(Init);
1980 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001981 }
1982
1983 return CheckArithmeticConstantExpression(Init);
1984 }
1985
1986 if (Init->getType()->isPointerType())
1987 return CheckAddressConstantExpression(Init);
1988
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001989 // An array type at the top level that isn't an init-list must
1990 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001991 if (Init->getType()->isArrayType())
1992 return false;
1993
Nuno Lopes73419bf2008-09-01 18:42:41 +00001994 if (Init->getType()->isFunctionType())
1995 return false;
1996
Steve Naroff8af6a452008-10-02 17:12:56 +00001997 // Allow block exprs at top level.
1998 if (Init->getType()->isBlockPointerType())
1999 return false;
2000
Steve Naroff6594a702008-10-27 11:34:16 +00002001 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00002002 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00002003}
2004
Sebastian Redl798d1192008-12-13 16:23:55 +00002005void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002006 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl798d1192008-12-13 16:23:55 +00002007 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002008 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00002009
Chris Lattner9a11b9a2007-10-19 20:10:30 +00002010 // If there is no declaration, there was an error parsing it. Just ignore
2011 // the initializer.
2012 if (RealDecl == 0) {
2013 delete Init;
2014 return;
2015 }
Steve Naroffbb204692007-09-12 14:07:44 +00002016
Steve Naroff410e3e22007-09-12 20:13:48 +00002017 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2018 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00002019 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2020 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00002021 RealDecl->setInvalidDecl();
2022 return;
2023 }
Steve Naroffbb204692007-09-12 14:07:44 +00002024 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00002025 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00002026 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00002027 if (VDecl->isBlockVarDecl()) {
2028 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00002029 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00002030 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002031 VDecl->setInvalidDecl();
2032 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002033 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002034 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002035 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002036
2037 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2038 if (!getLangOptions().CPlusPlus) {
2039 if (SC == VarDecl::Static) // C99 6.7.8p4.
2040 CheckForConstantInitializer(Init, DclT);
2041 }
Steve Naroffbb204692007-09-12 14:07:44 +00002042 }
Steve Naroff248a7532008-04-15 22:42:06 +00002043 } else if (VDecl->isFileVarDecl()) {
2044 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00002045 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00002046 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002047 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002048 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00002049 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00002050
Anders Carlssonc5eb7312008-08-22 05:00:02 +00002051 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2052 if (!getLangOptions().CPlusPlus) {
2053 // C99 6.7.8p4. All file scoped initializers need to be constant.
2054 CheckForConstantInitializer(Init, DclT);
2055 }
Steve Naroffbb204692007-09-12 14:07:44 +00002056 }
2057 // If the type changed, it means we had an incomplete type that was
2058 // completed by the initializer. For example:
2059 // int ary[] = { 1, 3, 5 };
2060 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00002061 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00002062 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00002063 Init->setType(DclT);
2064 }
Steve Naroffbb204692007-09-12 14:07:44 +00002065
2066 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00002067 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00002068 return;
2069}
2070
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002071void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2072 Decl *RealDecl = static_cast<Decl *>(dcl);
2073
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00002074 // If there is no declaration, there was an error parsing it. Just ignore it.
2075 if (RealDecl == 0)
2076 return;
2077
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002078 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2079 QualType Type = Var->getType();
2080 // C++ [dcl.init.ref]p3:
2081 // The initializer can be omitted for a reference only in a
2082 // parameter declaration (8.3.5), in the declaration of a
2083 // function return type, in the declaration of a class member
2084 // within its class declaration (9.2), and where the extern
2085 // specifier is explicitly used.
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002086 if (Type->isReferenceType() &&
2087 Var->getStorageClass() != VarDecl::Extern &&
2088 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00002089 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002090 << Var->getDeclName()
2091 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00002092 Var->setInvalidDecl();
2093 return;
2094 }
2095
2096 // C++ [dcl.init]p9:
2097 //
2098 // If no initializer is specified for an object, and the object
2099 // is of (possibly cv-qualified) non-POD class type (or array
2100 // thereof), the object shall be default-initialized; if the
2101 // object is of const-qualified type, the underlying class type
2102 // shall have a user-declared default constructor.
2103 if (getLangOptions().CPlusPlus) {
2104 QualType InitType = Type;
2105 if (const ArrayType *Array = Context.getAsArrayType(Type))
2106 InitType = Array->getElementType();
Douglas Gregor9e7d9de2008-12-15 21:24:18 +00002107 if (Var->getStorageClass() != VarDecl::Extern &&
2108 Var->getStorageClass() != VarDecl::PrivateExtern &&
2109 InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002110 const CXXConstructorDecl *Constructor
2111 = PerformInitializationByConstructor(InitType, 0, 0,
2112 Var->getLocation(),
2113 SourceRange(Var->getLocation(),
2114 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002115 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00002116 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00002117 if (!Constructor)
2118 Var->setInvalidDecl();
2119 }
2120 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002121
Douglas Gregor818ce482008-10-29 13:50:18 +00002122#if 0
2123 // FIXME: Temporarily disabled because we are not properly parsing
2124 // linkage specifications on declarations, e.g.,
2125 //
2126 // extern "C" const CGPoint CGPointerZero;
2127 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002128 // C++ [dcl.init]p9:
2129 //
2130 // If no initializer is specified for an object, and the
2131 // object is of (possibly cv-qualified) non-POD class type (or
2132 // array thereof), the object shall be default-initialized; if
2133 // the object is of const-qualified type, the underlying class
2134 // type shall have a user-declared default
2135 // constructor. Otherwise, if no initializer is specified for
2136 // an object, the object and its subobjects, if any, have an
2137 // indeterminate initial value; if the object or any of its
2138 // subobjects are of const-qualified type, the program is
2139 // ill-formed.
2140 //
2141 // This isn't technically an error in C, so we don't diagnose it.
2142 //
2143 // FIXME: Actually perform the POD/user-defined default
2144 // constructor check.
2145 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00002146 Context.getCanonicalType(Type).isConstQualified() &&
2147 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002148 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2149 << Var->getName()
2150 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002151#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002152 }
2153}
2154
Reid Spencer5f016e22007-07-11 17:01:13 +00002155/// The declarators are chained together backwards, reverse the list.
2156Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2157 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002158 Decl *GroupDecl = static_cast<Decl*>(group);
2159 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002160 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002161
2162 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2163 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002164 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002165 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002166 else { // reverse the list.
2167 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002168 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002169 Group->setNextDeclarator(NewGroup);
2170 NewGroup = Group;
2171 Group = Next;
2172 }
2173 }
2174 // Perform semantic analysis that depends on having fully processed both
2175 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002176 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002177 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2178 if (!IDecl)
2179 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002180 QualType T = IDecl->getType();
2181
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002182 if (T->isVariableArrayType()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002183 const VariableArrayType *VAT =
2184 cast<VariableArrayType>(T.getUnqualifiedType());
2185
2186 // FIXME: This won't give the correct result for
2187 // int a[10][n];
2188 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002189 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002190 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2191 SizeRange;
2192
Eli Friedmanc5773c42008-02-15 18:16:39 +00002193 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002194 } else {
2195 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2196 // static storage duration, it shall not have a variable length array.
2197 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002198 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2199 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002200 IDecl->setInvalidDecl();
2201 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002202 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2203 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002204 IDecl->setInvalidDecl();
2205 }
2206 }
2207 } else if (T->isVariablyModifiedType()) {
2208 if (IDecl->isFileVarDecl()) {
2209 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2210 IDecl->setInvalidDecl();
2211 } else {
2212 if (IDecl->getStorageClass() == VarDecl::Extern) {
2213 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2214 IDecl->setInvalidDecl();
2215 }
Steve Naroffbb204692007-09-12 14:07:44 +00002216 }
2217 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002218
Steve Naroffbb204692007-09-12 14:07:44 +00002219 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2220 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002221 if (IDecl->isBlockVarDecl() &&
2222 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002223 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002224 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002225 IDecl->setInvalidDecl();
2226 }
2227 }
2228 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2229 // object that has file scope without an initializer, and without a
2230 // storage-class specifier or with the storage-class specifier "static",
2231 // constitutes a tentative definition. Note: A tentative definition with
2232 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002233 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002234 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002235 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2236 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002237 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002238 // C99 6.9.2p3: If the declaration of an identifier for an object is
2239 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2240 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002241 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002242 IDecl->setInvalidDecl();
2243 }
2244 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002245 if (IDecl->isFileVarDecl())
2246 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002247 }
2248 return NewGroup;
2249}
Steve Naroffe1223f72007-08-28 03:03:08 +00002250
Chris Lattner04421082008-04-08 04:40:51 +00002251/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2252/// to introduce parameters into function prototype scope.
2253Sema::DeclTy *
2254Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner985abd92008-06-26 06:49:43 +00002255 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregor584049d2008-12-15 23:53:10 +00002256
Chris Lattner04421082008-04-08 04:40:51 +00002257 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002258 VarDecl::StorageClass StorageClass = VarDecl::None;
2259 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2260 StorageClass = VarDecl::Register;
2261 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002262 Diag(DS.getStorageClassSpecLoc(),
2263 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002264 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002265 }
2266 if (DS.isThreadSpecified()) {
2267 Diag(DS.getThreadSpecLoc(),
2268 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002269 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002270 }
2271
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002272 // Check that there are no default arguments inside the type of this
2273 // parameter (C++ only).
2274 if (getLangOptions().CPlusPlus)
2275 CheckExtraCXXDefaultArguments(D);
2276
Chris Lattner04421082008-04-08 04:40:51 +00002277 // In this context, we *do not* check D.getInvalidType(). If the declarator
2278 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2279 // though it will not reflect the user specified type.
2280 QualType parmDeclType = GetTypeForDeclarator(D, S);
2281
2282 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2283
Reid Spencer5f016e22007-07-11 17:01:13 +00002284 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2285 // Can this happen for params? We already checked that they don't conflict
2286 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002287 IdentifierInfo *II = D.getIdentifier();
2288 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002289 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002290 // Maybe we will complain about the shadowed template parameter.
2291 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2292 // Just pretend that we didn't see the previous declaration.
2293 PrevDecl = 0;
2294 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002295 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002296
2297 // Recover by removing the name
2298 II = 0;
2299 D.SetIdentifier(0, D.getIdentifierLoc());
2300 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002301 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002302
2303 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2304 // Doing the promotion here has a win and a loss. The win is the type for
2305 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2306 // code generator). The loss is the orginal type isn't preserved. For example:
2307 //
2308 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2309 // int blockvardecl[5];
2310 // sizeof(parmvardecl); // size == 4
2311 // sizeof(blockvardecl); // size == 20
2312 // }
2313 //
2314 // For expressions, all implicit conversions are captured using the
2315 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2316 //
2317 // FIXME: If a source translation tool needs to see the original type, then
2318 // we need to consider storing both types (in ParmVarDecl)...
2319 //
Chris Lattnere6327742008-04-02 05:18:44 +00002320 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002321 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002322 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002323 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002324 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002325
Chris Lattner04421082008-04-08 04:40:51 +00002326 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2327 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002328 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002329 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002330
Chris Lattner04421082008-04-08 04:40:51 +00002331 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002332 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002333
Douglas Gregor584049d2008-12-15 23:53:10 +00002334 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2335 if (D.getCXXScopeSpec().isSet()) {
2336 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2337 << D.getCXXScopeSpec().getRange();
2338 New->setInvalidDecl();
2339 }
2340
Douglas Gregor44b43212008-12-11 16:49:14 +00002341 // Add the parameter declaration into this scope.
2342 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002343 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002344 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002345
Chris Lattner3ff30c82008-06-29 00:02:00 +00002346 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002347 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002348
Reid Spencer5f016e22007-07-11 17:01:13 +00002349}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002350
Chris Lattnerb652cea2007-10-09 17:14:05 +00002351Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002352 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002353 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2354 "Not a function declarator!");
2355 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002356
Reid Spencer5f016e22007-07-11 17:01:13 +00002357 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2358 // for a K&R function.
2359 if (!FTI.hasPrototype) {
2360 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002361 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002362 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2363 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 // Implicitly declare the argument as type 'int' for lack of a better
2365 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002366 DeclSpec DS;
2367 const char* PrevSpec; // unused
2368 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2369 PrevSpec);
2370 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2371 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2372 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002373 }
2374 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002375 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002376 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002377 }
2378
Douglas Gregor584049d2008-12-15 23:53:10 +00002379 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002380
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002381 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregor584049d2008-12-15 23:53:10 +00002382 ActOnDeclarator(ParentScope, D, 0,
2383 /*IsFunctionDefinition=*/true));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002384}
2385
2386Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2387 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002388 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002389
2390 // See if this is a redefinition.
2391 const FunctionDecl *Definition;
2392 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002393 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002394 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002395 }
2396
Douglas Gregor44b43212008-12-11 16:49:14 +00002397 PushDeclContext(FnBodyScope, FD);
Chris Lattner04421082008-04-08 04:40:51 +00002398
2399 // Check the validity of our function parameters
2400 CheckParmsForFunctionDef(FD);
2401
2402 // Introduce our parameters into the function scope
2403 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2404 ParmVarDecl *Param = FD->getParamDecl(p);
2405 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002406 if (Param->getIdentifier())
2407 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002408 }
Chris Lattner04421082008-04-08 04:40:51 +00002409
Reid Spencer5f016e22007-07-11 17:01:13 +00002410 return FD;
2411}
2412
Sebastian Redl798d1192008-12-13 16:23:55 +00002413Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002414 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl798d1192008-12-13 16:23:55 +00002415 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff394f3f42008-07-25 17:57:26 +00002416 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl798d1192008-12-13 16:23:55 +00002417 FD->setBody(Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002418 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002419 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002420 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002421 } else
2422 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002423 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002424 // Verify and clean out per-function state.
2425
2426 // Check goto/label use.
2427 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2428 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2429 // Verify that we have no forward references left. If so, there was a goto
2430 // or address of a label taken, but no definition of it. Label fwd
2431 // definitions are indicated with a null substmt.
2432 if (I->second->getSubStmt() == 0) {
2433 LabelStmt *L = I->second;
2434 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002435 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002436
2437 // At this point, we have gotos that use the bogus label. Stitch it into
2438 // the function body so that they aren't leaked and that the AST is well
2439 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002440 if (Body) {
2441 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl798d1192008-12-13 16:23:55 +00002442 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner0cbc2152008-01-25 00:01:10 +00002443 } else {
2444 // The whole function wasn't parsed correctly, just delete this.
2445 delete L;
2446 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002447 }
2448 }
2449 LabelMap.clear();
2450
Steve Naroffd6d054d2007-11-11 23:20:51 +00002451 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002452}
2453
Reid Spencer5f016e22007-07-11 17:01:13 +00002454/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2455/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002456ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2457 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002458 // Extension in C99. Legal in C90, but warn about it.
2459 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002460 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002461 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002462 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002463
2464 // FIXME: handle stuff like:
2465 // void foo() { extern float X(); }
2466 // void bar() { X(); } <-- implicit decl for X in another scope.
2467
2468 // Set a Declarator for the implicit definition: int foo();
2469 const char *Dummy;
2470 DeclSpec DS;
2471 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2472 Error = Error; // Silence warning.
2473 assert(!Error && "Error setting up implicit decl!");
2474 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002475 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 D.SetIdentifier(&II, Loc);
2477
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002478 // Insert this function into translation-unit scope.
2479
2480 DeclContext *PrevDC = CurContext;
2481 CurContext = Context.getTranslationUnitDecl();
2482
Steve Naroffe2ef8152008-04-04 14:32:09 +00002483 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002484 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002485 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002486
2487 CurContext = PrevDC;
2488
Steve Naroffe2ef8152008-04-04 14:32:09 +00002489 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002490}
2491
2492
Chris Lattner41af0932007-11-14 06:34:38 +00002493TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002494 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002495 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002496 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002497
2498 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002499 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2500 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002501 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002502 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002503 if (D.getInvalidType())
2504 NewTD->setInvalidDecl();
2505 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002506}
2507
Steve Naroff08d92e42007-09-15 18:49:24 +00002508/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002509/// former case, Name will be non-null. In the later case, Name will be null.
2510/// TagType indicates what kind of tag this is. TK indicates whether this is a
2511/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002512Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002513 SourceLocation KWLoc, const CXXScopeSpec &SS,
2514 IdentifierInfo *Name, SourceLocation NameLoc,
2515 AttributeList *Attr) {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002516 // If this is not a definition, it must have a name.
Reid Spencer5f016e22007-07-11 17:01:13 +00002517 assert((Name != 0 || TK == TK_Definition) &&
2518 "Nameless record must be a definition!");
2519
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002520 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002521 switch (TagType) {
2522 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002523 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2524 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2525 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2526 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002527 }
2528
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002529 DeclContext *DC = CurContext;
2530 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002531
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002532 if (Name && SS.isNotEmpty()) {
2533 // We have a nested-name tag ('struct foo::bar').
2534
2535 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002536 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002537 Name = 0;
2538 goto CreateNewDecl;
2539 }
2540
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002541 DC = static_cast<DeclContext*>(SS.getScopeRep());
2542 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002543 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2544
2545 // A tag 'foo::bar' must already exist.
2546 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002547 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002548 Name = 0;
2549 goto CreateNewDecl;
2550 }
2551 } else {
2552 // If this is a named struct, check to see if there was a previous forward
2553 // declaration or definition.
2554 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2555 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2556 }
2557
Douglas Gregorf57172b2008-12-08 18:40:42 +00002558 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002559 // Maybe we will complain about the shadowed template parameter.
2560 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2561 // Just pretend that we didn't see the previous declaration.
2562 PrevDecl = 0;
2563 }
2564
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002565 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002566 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2567 "unexpected Decl type");
2568 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002569 // If this is a use of a previous tag, or if the tag is already declared
2570 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002571 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002572 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002573 // Make sure that this wasn't declared as an enum and now used as a
2574 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002575 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002576 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002577 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002578 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002579 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002580 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002581 } else {
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002582 // If this is a use, just return the declaration we found.
Chris Lattner14943b92008-07-03 03:30:58 +00002583
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002584 // FIXME: In the future, return a variant or some other clue
2585 // for the consumer of this Decl to know it doesn't own it.
2586 // For our current ASTs this shouldn't be a problem, but will
2587 // need to be changed with DeclGroups.
2588 if (TK == TK_Reference)
Chris Lattner14943b92008-07-03 03:30:58 +00002589 return PrevDecl;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002590
2591 // Diagnose attempts to redefine a tag.
2592 if (TK == TK_Definition) {
2593 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2594 Diag(NameLoc, diag::err_redefinition) << Name;
2595 Diag(Def->getLocation(), diag::note_previous_definition);
2596 // If this is a redefinition, recover by making this struct be
2597 // anonymous, which will make any later references get the previous
2598 // definition.
2599 Name = 0;
2600 PrevDecl = 0;
2601 }
2602 // Okay, this is definition of a previously declared or referenced
2603 // tag PrevDecl. We're going to create a new Decl for it.
2604 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002605 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002606 // If we get here we have (another) forward declaration or we
2607 // have a definition. Just create a new decl.
2608 } else {
2609 // If we get here, this is a definition of a new tag type in a nested
2610 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2611 // new decl/type. We set PrevDecl to NULL so that the entities
2612 // have distinct types.
2613 PrevDecl = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +00002614 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002615 // If we get here, we're going to create a new Decl. If PrevDecl
2616 // is non-NULL, it's a definition of the tag declared by
2617 // PrevDecl. If it's NULL, we have a new definition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002618 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002619 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002620 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002621 // The tag name clashes with a namespace name, issue an error and
2622 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002623 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002624 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002625 Name = 0;
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002626 PrevDecl = 0;
2627 } else {
2628 // The existing declaration isn't relevant to us; we're in a
2629 // new scope, so clear out the previous declaration.
2630 PrevDecl = 0;
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002631 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002632 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002633 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002634
Chris Lattnercc98eac2008-12-17 07:13:27 +00002635CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002636
2637 // If there is an identifier, use the location of the identifier as the
2638 // location of the decl, otherwise use the location of the struct/union
2639 // keyword.
2640 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2641
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002642 // Otherwise, create a new declaration. If there is a previous
2643 // declaration of the same entity, the two will be linked via
2644 // PrevDecl.
Reid Spencer5f016e22007-07-11 17:01:13 +00002645 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002646 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002647 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2648 // enum X { A, B, C } D; D should chain to X.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002649 New = EnumDecl::Create(Context, DC, Loc, Name,
2650 cast_or_null<EnumDecl>(PrevDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00002651 // If this is an undefined enum, warn.
2652 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002653 } else {
2654 // struct/union/class
2655
Reid Spencer5f016e22007-07-11 17:01:13 +00002656 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2657 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002658 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002659 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002660 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2661 cast_or_null<CXXRecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002662 else
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002663 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2664 cast_or_null<RecordDecl>(PrevDecl));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002665 }
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00002666
2667 if (Kind != TagDecl::TK_enum) {
2668 // Handle #pragma pack: if the #pragma pack stack has non-default
2669 // alignment, make up a packed attribute for this decl. These
2670 // attributes are checked when the ASTContext lays out the
2671 // structure.
2672 //
2673 // It is important for implementing the correct semantics that this
2674 // happen here (in act on tag decl). The #pragma pack stack is
2675 // maintained as a result of parser callbacks which can occur at
2676 // many points during the parsing of a struct declaration (because
2677 // the #pragma tokens are effectively skipped over during the
2678 // parsing of the struct).
2679 if (unsigned Alignment = PackContext.getAlignment())
2680 New->addAttr(new PackedAttr(Alignment * 8));
2681 }
2682
2683 if (Attr)
2684 ProcessDeclAttributeList(New, Attr);
2685
2686 // Set the lexical context. If the tag has a C++ scope specifier, the
2687 // lexical context will be different from the semantic context.
2688 New->setLexicalDeclContext(CurContext);
Reid Spencer5f016e22007-07-11 17:01:13 +00002689
2690 // If this has an identifier, add it to the scope stack.
2691 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002692 // The scope passed in may not be a decl scope. Zip up the scope tree until
2693 // we find one that is.
2694 while ((S->getFlags() & Scope::DeclScope) == 0)
2695 S = S->getParent();
2696
2697 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002698 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002699 }
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002700
Reid Spencer5f016e22007-07-11 17:01:13 +00002701 return New;
2702}
2703
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002704
Chris Lattner1d353ba2008-11-12 21:17:48 +00002705/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2706/// types into constant array types in certain situations which would otherwise
2707/// be errors (for GCC compatibility).
2708static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2709 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002710 // This method tries to turn a variable array into a constant
2711 // array even when the size isn't an ICE. This is necessary
2712 // for compatibility with code that depends on gcc's buggy
2713 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002714 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2715 if (!VLATy) return QualType();
2716
2717 APValue Result;
2718 if (!VLATy->getSizeExpr() ||
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002719 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002720 return QualType();
2721
2722 assert(Result.isInt() && "Size expressions must be integers!");
2723 llvm::APSInt &Res = Result.getInt();
2724 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2725 return Context.getConstantArrayType(VLATy->getElementType(),
2726 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002727 return QualType();
2728}
2729
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002730bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002731 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002732 // FIXME: 6.7.2.1p4 - verify the field type.
2733
2734 llvm::APSInt Value;
2735 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2736 return true;
2737
Chris Lattnercd087072008-12-12 04:56:04 +00002738 // Zero-width bitfield is ok for anonymous field.
2739 if (Value == 0 && FieldName)
2740 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2741
2742 if (Value.isNegative())
2743 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002744
2745 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2746 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002747 if (TypeSize && Value.getZExtValue() > TypeSize)
2748 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2749 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002750
2751 return false;
2752}
2753
Steve Naroff08d92e42007-09-15 18:49:24 +00002754/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002755/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002756Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002757 SourceLocation DeclStart,
2758 Declarator &D, ExprTy *BitfieldWidth) {
2759 IdentifierInfo *II = D.getIdentifier();
2760 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002761 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002762 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002763 if (II) Loc = D.getIdentifierLoc();
2764
2765 // FIXME: Unnamed fields can be handled in various different ways, for
2766 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002767
Reid Spencer5f016e22007-07-11 17:01:13 +00002768 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002769 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2770 bool InvalidDecl = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002771
Reid Spencer5f016e22007-07-11 17:01:13 +00002772 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2773 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002774 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002775 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002776 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002777 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002778 T = FixedTy;
2779 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002780 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002781 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002782 InvalidDecl = true;
2783 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002784 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002785
2786 if (BitWidth) {
2787 if (VerifyBitField(Loc, II, T, BitWidth))
2788 InvalidDecl = true;
2789 } else {
2790 // Not a bitfield.
2791
2792 // validate II.
2793
2794 }
2795
Reid Spencer5f016e22007-07-11 17:01:13 +00002796 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002797 FieldDecl *NewFD;
2798
Douglas Gregor44b43212008-12-11 16:49:14 +00002799 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2800 // other way to determine the current RecordDecl.
2801 NewFD = FieldDecl::Create(Context, Record,
2802 Loc, II, T, BitWidth,
2803 D.getDeclSpec().getStorageClassSpec() ==
2804 DeclSpec::SCS_mutable,
2805 /*PrevDecl=*/0);
2806
Douglas Gregor72b505b2008-12-16 21:30:33 +00002807 if (getLangOptions().CPlusPlus)
2808 CheckExtraCXXDefaultArguments(D);
2809
Chris Lattner3ff30c82008-06-29 00:02:00 +00002810 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002811
Steve Naroff5912a352007-08-28 20:14:24 +00002812 if (D.getInvalidType() || InvalidDecl)
2813 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002814
2815 if (II && getLangOptions().CPlusPlus)
2816 PushOnScopeChains(NewFD, S);
2817 else
2818 Record->addDecl(Context, NewFD);
2819
Steve Naroff5912a352007-08-28 20:14:24 +00002820 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002821}
2822
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002823/// TranslateIvarVisibility - Translate visibility from a token ID to an
2824/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002825static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002826TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002827 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002828 default: assert(0 && "Unknown visitibility kind");
2829 case tok::objc_private: return ObjCIvarDecl::Private;
2830 case tok::objc_public: return ObjCIvarDecl::Public;
2831 case tok::objc_protected: return ObjCIvarDecl::Protected;
2832 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002833 }
2834}
2835
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002836/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2837/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002838Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002839 SourceLocation DeclStart,
2840 Declarator &D, ExprTy *BitfieldWidth,
2841 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002842 IdentifierInfo *II = D.getIdentifier();
2843 Expr *BitWidth = (Expr*)BitfieldWidth;
2844 SourceLocation Loc = DeclStart;
2845 if (II) Loc = D.getIdentifierLoc();
2846
2847 // FIXME: Unnamed fields can be handled in various different ways, for
2848 // example, unnamed unions inject all members into the struct namespace!
2849
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002850 QualType T = GetTypeForDeclarator(D, S);
2851 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2852 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002853
2854 if (BitWidth) {
2855 // TODO: Validate.
2856 //printf("WARNING: BITFIELDS IGNORED!\n");
2857
2858 // 6.7.2.1p3
2859 // 6.7.2.1p4
2860
2861 } else {
2862 // Not a bitfield.
2863
2864 // validate II.
2865
2866 }
2867
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002868 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2869 // than a variably modified type.
2870 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002871 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002872 InvalidDecl = true;
2873 }
2874
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002875 // Get the visibility (access control) for this ivar.
2876 ObjCIvarDecl::AccessControl ac =
2877 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2878 : ObjCIvarDecl::None;
2879
2880 // Construct the decl.
2881 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002882 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002883
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002884 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002885 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002886
2887 if (D.getInvalidType() || InvalidDecl)
2888 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002889
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002890 return NewID;
2891}
2892
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002893void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002894 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002895 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002896 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002897 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002898 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2899 assert(EnclosingDecl && "missing record or interface decl");
2900 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2901
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002902 if (Record)
2903 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2904 // Diagnose code like:
2905 // struct S { struct S {} X; };
2906 // We discover this when we complete the outer S. Reject and ignore the
2907 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002908 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002909 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002910 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002911 Record->setInvalidDecl();
2912 return;
2913 }
2914
Reid Spencer5f016e22007-07-11 17:01:13 +00002915 // Verify that all the fields are okay.
2916 unsigned NumNamedMembers = 0;
2917 llvm::SmallVector<FieldDecl*, 32> RecFields;
2918 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002919
Reid Spencer5f016e22007-07-11 17:01:13 +00002920 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002921
Steve Naroff74216642007-09-14 22:20:54 +00002922 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2923 assert(FD && "missing field decl");
2924
2925 // Remember all fields.
2926 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002927
2928 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002929 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002930
Reid Spencer5f016e22007-07-11 17:01:13 +00002931 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002932 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002933 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002934 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002935 FD->setInvalidDecl();
2936 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 continue;
2938 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002939 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2940 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002941 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002942 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002943 FD->setInvalidDecl();
2944 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002945 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002946 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002947 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002948 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002949 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002950 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002951 FD->setInvalidDecl();
2952 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002953 continue;
2954 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002955 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002956 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002957 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002958 FD->setInvalidDecl();
2959 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002960 continue;
2961 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002962 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002963 if (Record)
2964 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002965 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002966 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2967 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002968 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002969 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2970 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002971 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002972 Record->setHasFlexibleArrayMember(true);
2973 } else {
2974 // If this is a struct/class and this is not the last element, reject
2975 // it. Note that GCC supports variable sized arrays in the middle of
2976 // structures.
2977 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002978 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002979 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002980 FD->setInvalidDecl();
2981 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002982 continue;
2983 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002984 // We support flexible arrays at the end of structs in other structs
2985 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002986 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002987 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002988 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002989 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002990 }
2991 }
2992 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002993 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002994 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002995 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00002996 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00002997 FD->setInvalidDecl();
2998 EnclosingDecl->setInvalidDecl();
2999 continue;
3000 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 // Keep track of the number of named members.
3002 if (IdentifierInfo *II = FD->getIdentifier()) {
3003 // Detect duplicate member names.
3004 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003005 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003006 // Find the previous decl.
3007 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003008 for (unsigned i = 0; ; ++i) {
3009 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003010 if (RecFields[i]->getIdentifier() == II) {
3011 PrevLoc = RecFields[i]->getLocation();
3012 break;
3013 }
3014 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003015 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003016 FD->setInvalidDecl();
3017 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 continue;
3019 }
3020 ++NumNamedMembers;
3021 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003022 }
3023
Reid Spencer5f016e22007-07-11 17:01:13 +00003024 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003025 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003026 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003027 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3028 // Sema::ActOnFinishCXXClassDef.
3029 if (!isa<CXXRecordDecl>(Record))
3030 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003031 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003032 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003033 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattnera91d3812008-02-05 22:40:55 +00003034 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003035 // Must enforce the rule that ivars in the base classes may not be
3036 // duplicates.
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003037 if (ID->getSuperClass()) {
3038 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3039 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3040 ObjCIvarDecl* Ivar = (*IVI);
3041 IdentifierInfo *II = Ivar->getIdentifier();
3042 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3043 if (prevIvar) {
3044 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3045 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003046 }
Fariborz Jahanian375d37c2008-12-17 22:21:44 +00003047 }
Fariborz Jahanian3281eff2008-12-16 01:08:35 +00003048 }
Fariborz Jahanian60f8c862008-12-13 20:28:25 +00003049 }
Chris Lattnera91d3812008-02-05 22:40:55 +00003050 else if (ObjCImplementationDecl *IMPDecl =
3051 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003052 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3053 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003054 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003055 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003056 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003057
3058 if (Attr)
3059 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003060}
3061
Steve Naroff08d92e42007-09-15 18:49:24 +00003062Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003063 DeclTy *lastEnumConst,
3064 SourceLocation IdLoc, IdentifierInfo *Id,
3065 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003066 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003067 EnumConstantDecl *LastEnumConst =
3068 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3069 Expr *Val = static_cast<Expr*>(val);
3070
Chris Lattner31e05722007-08-26 06:24:45 +00003071 // The scope passed in may not be a decl scope. Zip up the scope tree until
3072 // we find one that is.
3073 while ((S->getFlags() & Scope::DeclScope) == 0)
3074 S = S->getParent();
3075
Reid Spencer5f016e22007-07-11 17:01:13 +00003076 // Verify that there isn't already something declared with this name in this
3077 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003078 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003079 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003080 // Maybe we will complain about the shadowed template parameter.
3081 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3082 // Just pretend that we didn't see the previous declaration.
3083 PrevDecl = 0;
3084 }
3085
3086 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003087 // When in C++, we may get a TagDecl with the same name; in this case the
3088 // enum constant will 'hide' the tag.
3089 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3090 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003091 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003092 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003093 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003094 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003095 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003096 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003097 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003098 return 0;
3099 }
3100 }
3101
3102 llvm::APSInt EnumVal(32);
3103 QualType EltTy;
3104 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003105 // Make sure to promote the operand type to int.
3106 UsualUnaryConversions(Val);
3107
Reid Spencer5f016e22007-07-11 17:01:13 +00003108 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3109 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003110 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003111 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003112 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003113 } else {
3114 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003115 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003116 }
3117
3118 if (!Val) {
3119 if (LastEnumConst) {
3120 // Assign the last value + 1.
3121 EnumVal = LastEnumConst->getInitVal();
3122 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003123
3124 // Check for overflow on increment.
3125 if (EnumVal < LastEnumConst->getInitVal())
3126 Diag(IdLoc, diag::warn_enum_value_overflow);
3127
Chris Lattnerb7416f92007-08-27 17:37:24 +00003128 EltTy = LastEnumConst->getType();
3129 } else {
3130 // First value, set to zero.
3131 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003132 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003133 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003134 }
3135
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003136 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003137 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3138 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003139 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003140
3141 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003142 PushOnScopeChains(New, S);
Douglas Gregor45579f52008-12-17 02:04:30 +00003143
3144 // Add this enumerator into the enum itself.
3145 // FIXME: This means that the enumerator is stored in two
3146 // DeclContexts. This is not a long-term solution.
3147 New->setLexicalDeclContext(TheEnumDecl);
3148 TheEnumDecl->addDecl(Context, New, true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003149 return New;
3150}
3151
Steve Naroff02408c62008-08-07 14:08:16 +00003152// FIXME: For consistency with ActOnFields(), we should have the parser
3153// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003154void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003155 DeclTy **Elements, unsigned NumElements) {
3156 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00003157
Douglas Gregor7df7b6b2008-12-15 16:32:14 +00003158 if (Enum) {
3159 if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) {
3160 // Diagnose code like:
3161 // enum e0 {
3162 // E0 = sizeof(enum e0 { E1 })
3163 // };
3164 Diag(Def->getLocation(), diag::err_nested_redefinition)
3165 << Enum->getDeclName();
3166 Diag(Enum->getLocation(), diag::note_previous_definition);
3167 Enum->setInvalidDecl();
3168 return;
3169 }
Steve Naroff02408c62008-08-07 14:08:16 +00003170 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00003171 // TODO: If the result value doesn't fit in an int, it must be a long or long
3172 // long value. ISO C does not support this, but GCC does as an extension,
3173 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003174 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003175
Chris Lattnerac609682007-08-28 06:15:15 +00003176 // Verify that all the values are okay, compute the size of the values, and
3177 // reverse the list.
3178 unsigned NumNegativeBits = 0;
3179 unsigned NumPositiveBits = 0;
3180
3181 // Keep track of whether all elements have type int.
3182 bool AllElementsInt = true;
3183
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003184 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003185 EnumConstantDecl *EltList = 0;
3186 for (unsigned i = 0; i != NumElements; ++i) {
3187 EnumConstantDecl *ECD =
3188 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3189 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003190
3191 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003192 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003193 assert(InitVal.getBitWidth() >= IntWidth &&
3194 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003195 if (InitVal.getBitWidth() > IntWidth) {
3196 llvm::APSInt V(InitVal);
3197 V.trunc(IntWidth);
3198 V.extend(InitVal.getBitWidth());
3199 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003200 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3201 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003202 }
Chris Lattnerac609682007-08-28 06:15:15 +00003203
3204 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003205 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003206 NumPositiveBits = std::max(NumPositiveBits,
3207 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003208 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003209 NumNegativeBits = std::max(NumNegativeBits,
3210 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003211
Chris Lattnerac609682007-08-28 06:15:15 +00003212 // Keep track of whether every enum element has type int (very commmon).
3213 if (AllElementsInt)
3214 AllElementsInt = ECD->getType() == Context.IntTy;
3215
Reid Spencer5f016e22007-07-11 17:01:13 +00003216 ECD->setNextDeclarator(EltList);
3217 EltList = ECD;
3218 }
3219
Chris Lattnerac609682007-08-28 06:15:15 +00003220 // Figure out the type that should be used for this enum.
3221 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3222 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003223 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003224
3225 if (NumNegativeBits) {
3226 // If there is a negative value, figure out the smallest integer type (of
3227 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003228 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003229 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003230 BestWidth = IntWidth;
3231 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003232 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003233
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003234 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003235 BestType = Context.LongTy;
3236 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003237 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003238
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003239 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003240 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3241 BestType = Context.LongLongTy;
3242 }
3243 }
3244 } else {
3245 // If there is no negative value, figure out which of uint, ulong, ulonglong
3246 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003247 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003248 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003249 BestWidth = IntWidth;
3250 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003251 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003252 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003253 } else {
3254 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003255 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003256 "How could an initializer get larger than ULL?");
3257 BestType = Context.UnsignedLongLongTy;
3258 }
3259 }
3260
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003261 // Loop over all of the enumerator constants, changing their types to match
3262 // the type of the enum if needed.
3263 for (unsigned i = 0; i != NumElements; ++i) {
3264 EnumConstantDecl *ECD =
3265 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3266 if (!ECD) continue; // Already issued a diagnostic.
3267
3268 // Standard C says the enumerators have int type, but we allow, as an
3269 // extension, the enumerators to be larger than int size. If each
3270 // enumerator value fits in an int, type it as an int, otherwise type it the
3271 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3272 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003273 if (ECD->getType() == Context.IntTy) {
3274 // Make sure the init value is signed.
3275 llvm::APSInt IV = ECD->getInitVal();
3276 IV.setIsSigned(true);
3277 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003278
3279 if (getLangOptions().CPlusPlus)
3280 // C++ [dcl.enum]p4: Following the closing brace of an
3281 // enum-specifier, each enumerator has the type of its
3282 // enumeration.
3283 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003284 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003285 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003286
3287 // Determine whether the value fits into an int.
3288 llvm::APSInt InitVal = ECD->getInitVal();
3289 bool FitsInInt;
3290 if (InitVal.isUnsigned() || !InitVal.isNegative())
3291 FitsInInt = InitVal.getActiveBits() < IntWidth;
3292 else
3293 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3294
3295 // If it fits into an integer type, force it. Otherwise force it to match
3296 // the enum decl type.
3297 QualType NewTy;
3298 unsigned NewWidth;
3299 bool NewSign;
3300 if (FitsInInt) {
3301 NewTy = Context.IntTy;
3302 NewWidth = IntWidth;
3303 NewSign = true;
3304 } else if (ECD->getType() == BestType) {
3305 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003306 if (getLangOptions().CPlusPlus)
3307 // C++ [dcl.enum]p4: Following the closing brace of an
3308 // enum-specifier, each enumerator has the type of its
3309 // enumeration.
3310 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003311 continue;
3312 } else {
3313 NewTy = BestType;
3314 NewWidth = BestWidth;
3315 NewSign = BestType->isSignedIntegerType();
3316 }
3317
3318 // Adjust the APSInt value.
3319 InitVal.extOrTrunc(NewWidth);
3320 InitVal.setIsSigned(NewSign);
3321 ECD->setInitVal(InitVal);
3322
3323 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003324 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3325 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003326 if (getLangOptions().CPlusPlus)
3327 // C++ [dcl.enum]p4: Following the closing brace of an
3328 // enum-specifier, each enumerator has the type of its
3329 // enumeration.
3330 ECD->setType(EnumType);
3331 else
3332 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003333 }
Chris Lattnerac609682007-08-28 06:15:15 +00003334
Douglas Gregor44b43212008-12-11 16:49:14 +00003335 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003336 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003337}
3338
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003339Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl798d1192008-12-13 16:23:55 +00003340 ExprArg expr) {
3341 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3342
Chris Lattner8e25d862008-03-16 00:16:02 +00003343 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003344}
3345
Douglas Gregorf44515a2008-12-16 22:23:02 +00003346
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003347void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3348 ExprTy *alignment, SourceLocation PragmaLoc,
3349 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3350 Expr *Alignment = static_cast<Expr *>(alignment);
3351
3352 // If specified then alignment must be a "small" power of two.
3353 unsigned AlignmentVal = 0;
3354 if (Alignment) {
3355 llvm::APSInt Val;
3356 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3357 !Val.isPowerOf2() ||
3358 Val.getZExtValue() > 16) {
3359 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3360 delete Alignment;
3361 return; // Ignore
3362 }
3363
3364 AlignmentVal = (unsigned) Val.getZExtValue();
3365 }
3366
3367 switch (Kind) {
3368 case Action::PPK_Default: // pack([n])
3369 PackContext.setAlignment(AlignmentVal);
3370 break;
3371
3372 case Action::PPK_Show: // pack(show)
3373 // Show the current alignment, making sure to show the right value
3374 // for the default.
3375 AlignmentVal = PackContext.getAlignment();
3376 // FIXME: This should come from the target.
3377 if (AlignmentVal == 0)
3378 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003379 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003380 break;
3381
3382 case Action::PPK_Push: // pack(push [, id] [, [n])
3383 PackContext.push(Name);
3384 // Set the new alignment if specified.
3385 if (Alignment)
3386 PackContext.setAlignment(AlignmentVal);
3387 break;
3388
3389 case Action::PPK_Pop: // pack(pop [, id] [, n])
3390 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3391 // "#pragma pack(pop, identifier, n) is undefined"
3392 if (Alignment && Name)
3393 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3394
3395 // Do the pop.
3396 if (!PackContext.pop(Name)) {
3397 // If a name was specified then failure indicates the name
3398 // wasn't found. Otherwise failure indicates the stack was
3399 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003400 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3401 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003402
3403 // FIXME: Warn about popping named records as MSVC does.
3404 } else {
3405 // Pop succeeded, set the new alignment if specified.
3406 if (Alignment)
3407 PackContext.setAlignment(AlignmentVal);
3408 }
3409 break;
3410
3411 default:
3412 assert(0 && "Invalid #pragma pack kind.");
3413 }
3414}
3415
3416bool PragmaPackStack::pop(IdentifierInfo *Name) {
3417 if (Stack.empty())
3418 return false;
3419
3420 // If name is empty just pop top.
3421 if (!Name) {
3422 Alignment = Stack.back().first;
3423 Stack.pop_back();
3424 return true;
3425 }
3426
3427 // Otherwise, find the named record.
3428 for (unsigned i = Stack.size(); i != 0; ) {
3429 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003430 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003431 // Found it, pop up to and including this record.
3432 Alignment = Stack[i].first;
3433 Stack.erase(Stack.begin() + i, Stack.end());
3434 return true;
3435 }
3436 }
3437
3438 return false;
3439}