blob: 29d636fabdca48ffbd5f2c9aa0c9818a1282b7d6 [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 Gregore267ff32008-12-11 20:41:00 +0000141 // If there is an ame binding for the existing FunctionDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +0000142 // remove it.
143 for (IdentifierResolver::iterator I
144 = IdResolver.begin(FD->getDeclName(), FD->getDeclContext(),
Douglas Gregore267ff32008-12-11 20:41:00 +0000145 false/*LookInParentCtx*/),
146 E = IdResolver.end(); I != E; ++I) {
Douglas Gregor44b43212008-12-11 16:49:14 +0000147 if (*I == Prev) {
148 IdResolver.RemoveDecl(*I);
149 S->RemoveDecl(*I);
150 break;
151 }
152 }
153
154 // 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,
224 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 }
550 }
551
552 // (C++98 8.3.5p3):
553 // All declarations for a function shall agree exactly in both the
554 // return type and the parameter-type-list.
555 if (OldQType == NewQType) {
556 // We have a redeclaration.
557 MergeAttributes(New, Old);
558 Redeclaration = true;
559 return MergeCXXFunctionDecl(New, Old);
560 }
561
562 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregorf0097952008-04-21 02:02:58 +0000563 }
Chris Lattner04421082008-04-08 04:40:51 +0000564
565 // C: Function types need to be compatible, not identical. This handles
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000566 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner04421082008-04-08 04:40:51 +0000567 if (!getLangOptions().CPlusPlus &&
Eli Friedman3d815e72008-08-22 00:56:42 +0000568 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregorf0097952008-04-21 02:02:58 +0000569 MergeAttributes(New, Old);
570 Redeclaration = true;
Steve Naroffadbbd0c2008-01-14 20:51:29 +0000571 return New;
Chris Lattner04421082008-04-08 04:40:51 +0000572 }
Chris Lattnere3995fe2007-11-06 06:07:26 +0000573
Steve Naroff837618c2008-01-16 15:01:34 +0000574 // A function that has already been declared has been redeclared or defined
575 // with a different type- show appropriate diagnostic
Steve Naroff837618c2008-01-16 15:01:34 +0000576
Reid Spencer5f016e22007-07-11 17:01:13 +0000577 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
578 // TODO: This is totally simplistic. It should handle merging functions
579 // together etc, merging extern int X; int X; ...
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000580 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff837618c2008-01-16 15:01:34 +0000581 Diag(Old->getLocation(), PrevDiag);
Reid Spencer5f016e22007-07-11 17:01:13 +0000582 return New;
583}
584
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000585/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd4d46cd2008-08-10 15:28:06 +0000586static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000587 if (VD->isFileVarDecl())
588 return (!VD->getInit() &&
589 (VD->getStorageClass() == VarDecl::None ||
590 VD->getStorageClass() == VarDecl::Static));
591 return false;
592}
593
594/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
595/// when dealing with C "tentative" external object definitions (C99 6.9.2).
596void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
597 bool VDIsTentative = isTentativeDefinition(VD);
Steve Narofff855e6f2008-08-10 15:20:13 +0000598 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000599
600 for (IdentifierResolver::iterator
601 I = IdResolver.begin(VD->getIdentifier(),
602 VD->getDeclContext(), false/*LookInParentCtx*/),
603 E = IdResolver.end(); I != E; ++I) {
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +0000604 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000605 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
606
Steve Narofff855e6f2008-08-10 15:20:13 +0000607 // Handle the following case:
608 // int a[10];
609 // int a[]; - the code below makes sure we set the correct type.
610 // int a[11]; - this is an error, size isn't 10.
611 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
612 OldDecl->getType()->isConstantArrayType())
613 VD->setType(OldDecl->getType());
614
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000615 // Check for "tentative" definitions. We can't accomplish this in
616 // MergeVarDecl since the initializer hasn't been attached.
617 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
618 continue;
619
620 // Handle __private_extern__ just like extern.
621 if (OldDecl->getStorageClass() != VarDecl::Extern &&
622 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
623 VD->getStorageClass() != VarDecl::Extern &&
624 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner08631c52008-11-23 21:45:46 +0000625 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000626 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000627 }
628 }
629 }
630}
631
Reid Spencer5f016e22007-07-11 17:01:13 +0000632/// MergeVarDecl - We just parsed a variable 'New' which has the same name
633/// and scope as a previous declaration 'Old'. Figure out how to resolve this
634/// situation, merging decls or emitting diagnostics as appropriate.
635///
Steve Naroffff9eb1f2008-08-08 17:50:35 +0000636/// Tentative definition rules (C99 6.9.2p2) are checked by
637/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
638/// definitions here, since the initializer hasn't been attached.
Reid Spencer5f016e22007-07-11 17:01:13 +0000639///
Steve Naroffe8043c32008-04-01 23:04:06 +0000640VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000641 // Verify the old decl was also a variable.
642 VarDecl *Old = dyn_cast<VarDecl>(OldD);
643 if (!Old) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000644 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattner08631c52008-11-23 21:45:46 +0000645 << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000646 Diag(OldD->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000647 return New;
648 }
Chris Lattnerddee4232008-03-03 03:28:21 +0000649
650 MergeAttributes(New, Old);
651
Reid Spencer5f016e22007-07-11 17:01:13 +0000652 // Verify the types match.
Chris Lattner8bcfc5b2008-04-06 23:10:54 +0000653 QualType OldCType = Context.getCanonicalType(Old->getType());
654 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff907747b2008-08-09 16:04:40 +0000655 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattner08631c52008-11-23 21:45:46 +0000656 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000657 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 return New;
659 }
Steve Naroffb7b032e2008-01-30 00:44:01 +0000660 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
661 if (New->getStorageClass() == VarDecl::Static &&
662 (Old->getStorageClass() == VarDecl::None ||
663 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000664 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000665 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000666 return New;
667 }
668 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
669 if (New->getStorageClass() != VarDecl::Static &&
670 Old->getStorageClass() == VarDecl::Static) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000671 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000672 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb7b032e2008-01-30 00:44:01 +0000673 return New;
674 }
Steve Naroff094cefb2008-09-17 14:05:40 +0000675 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
676 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattner08631c52008-11-23 21:45:46 +0000677 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +0000678 Diag(Old->getLocation(), diag::note_previous_definition);
Reid Spencer5f016e22007-07-11 17:01:13 +0000679 }
680 return New;
681}
682
Chris Lattner04421082008-04-08 04:40:51 +0000683/// CheckParmsForFunctionDef - Check that the parameters of the given
684/// function are appropriate for the definition of a function. This
685/// takes care of any checks that cannot be performed on the
686/// declaration itself, e.g., that the types of each of the function
687/// parameters are complete.
688bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
689 bool HasInvalidParm = false;
690 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
691 ParmVarDecl *Param = FD->getParamDecl(p);
692
693 // C99 6.7.5.3p4: the parameters in a parameter type list in a
694 // function declarator that is part of a function definition of
695 // that function shall not have incomplete type.
696 if (Param->getType()->isIncompleteType() &&
697 !Param->isInvalidDecl()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +0000698 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000699 << Param->getType();
Chris Lattner04421082008-04-08 04:40:51 +0000700 Param->setInvalidDecl();
701 HasInvalidParm = true;
702 }
703 }
704
705 return HasInvalidParm;
706}
707
Reid Spencer5f016e22007-07-11 17:01:13 +0000708/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
709/// no declarator (e.g. "struct foo;") is parsed.
710Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
711 // TODO: emit error on 'int;' or 'const enum foo;'.
712 // TODO: emit error on 'typedef int;'
713 // if (!DS.isMissingDeclaratorOk()) Diag(...);
714
Steve Naroff92199282007-11-17 21:37:36 +0000715 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000716}
717
Steve Naroffd0091aa2008-01-10 22:15:12 +0000718bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Narofff0090632007-09-02 02:04:30 +0000719 // Get the type before calling CheckSingleAssignmentConstraints(), since
720 // it can promote the expression.
Chris Lattner5cf216b2008-01-04 18:04:52 +0000721 QualType InitType = Init->getType();
Steve Narofff0090632007-09-02 02:04:30 +0000722
Chris Lattner5cf216b2008-01-04 18:04:52 +0000723 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
724 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
725 InitType, Init, "initializing");
Steve Narofff0090632007-09-02 02:04:30 +0000726}
727
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000728bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000729 const ArrayType *AT = Context.getAsArrayType(DeclT);
730
731 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000732 // C99 6.7.8p14. We have an array of character type with unknown size
733 // being initialized to a string literal.
734 llvm::APSInt ConstVal(32);
735 ConstVal = strLiteral->getByteLength() + 1;
736 // Return a new array type (C99 6.7.8p22).
Eli Friedmanc5773c42008-02-15 18:16:39 +0000737 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000738 ArrayType::Normal, 0);
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000739 } else {
740 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000741 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000742 // FIXME: Avoid truncation for 64-bit length strings.
743 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000744 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000745 diag::warn_initializer_string_for_char_array_too_long)
746 << strLiteral->getSourceRange();
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000747 }
748 // Set type from "char *" to "constant array of char".
749 strLiteral->setType(DeclT);
750 // For now, we always return false (meaning success).
751 return false;
752}
753
754StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000755 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Naroffa9960332008-01-25 00:51:06 +0000756 if (AT && AT->getElementType()->isCharType()) {
757 return dyn_cast<StringLiteral>(Init);
758 }
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000759 return 0;
760}
761
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000762bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
763 SourceLocation InitLoc,
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000764 DeclarationName InitEntity) {
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000765 // C++ [dcl.init.ref]p1:
Sebastian Redld14094d2008-11-24 20:06:50 +0000766 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor27c8dc02008-10-29 00:13:59 +0000767 // (8.3.2), shall be initialized by an object, or function, of
768 // type T or by an object that can be converted into a T.
769 if (DeclType->isReferenceType())
770 return CheckReferenceInit(Init, DeclType);
771
Steve Naroffca107302008-01-21 23:53:58 +0000772 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
773 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnerc63a1f22008-08-04 07:31:14 +0000774 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000775 return Diag(InitLoc, diag::err_variable_object_no_init)
776 << VAT->getSizeExpr()->getSourceRange();
Steve Naroffca107302008-01-21 23:53:58 +0000777
Steve Naroff2fdc3742007-12-10 22:44:33 +0000778 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
779 if (!InitList) {
Steve Naroffa49e1fa2008-01-22 00:55:40 +0000780 // FIXME: Handle wide strings
781 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
782 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedmana312ce22008-02-08 00:48:24 +0000783
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000784 // C++ [dcl.init]p14:
785 // -- If the destination type is a (possibly cv-qualified) class
786 // type:
787 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
788 QualType DeclTypeC = Context.getCanonicalType(DeclType);
789 QualType InitTypeC = Context.getCanonicalType(Init->getType());
790
791 // -- If the initialization is direct-initialization, or if it is
792 // copy-initialization where the cv-unqualified version of the
793 // source type is the same class as, or a derived class of, the
794 // class of the destination, constructors are considered.
795 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
796 IsDerivedFrom(InitTypeC, DeclTypeC)) {
797 CXXConstructorDecl *Constructor
798 = PerformInitializationByConstructor(DeclType, &Init, 1,
799 InitLoc, Init->getSourceRange(),
800 InitEntity, IK_Copy);
801 return Constructor == 0;
802 }
803
804 // -- Otherwise (i.e., for the remaining copy-initialization
805 // cases), user-defined conversion sequences that can
806 // convert from the source type to the destination type or
807 // (when a conversion function is used) to a derived class
808 // thereof are enumerated as described in 13.3.1.4, and the
809 // best one is chosen through overload resolution
810 // (13.3). If the conversion cannot be done or is
811 // ambiguous, the initialization is ill-formed. The
812 // function selected is called with the initializer
813 // expression as its argument; if the function is a
814 // constructor, the call initializes a temporary of the
815 // destination type.
816 // FIXME: We're pretending to do copy elision here; return to
817 // this when we have ASTs for such things.
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000818 if (!PerformImplicitConversion(Init, DeclType))
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000819 return false;
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000820
821 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000822 << DeclType << InitEntity << "initializing"
Chris Lattnerc9c7c4e2008-11-18 22:52:51 +0000823 << Init->getSourceRange();
Douglas Gregorf03d7c72008-11-05 15:29:30 +0000824 }
825
Steve Naroff1ac6fdd2008-09-29 20:07:05 +0000826 // C99 6.7.8p16.
Eli Friedmana312ce22008-02-08 00:48:24 +0000827 if (DeclType->isArrayType())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000828 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
829 << Init->getSourceRange();
Eli Friedmana312ce22008-02-08 00:48:24 +0000830
Steve Naroffd0091aa2008-01-10 22:15:12 +0000831 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor64bffa92008-11-05 16:20:31 +0000832 } else if (getLangOptions().CPlusPlus) {
833 // C++ [dcl.init]p14:
834 // [...] If the class is an aggregate (8.5.1), and the initializer
835 // is a brace-enclosed list, see 8.5.1.
836 //
837 // Note: 8.5.1 is handled below; here, we diagnose the case where
838 // we have an initializer list and a destination type that is not
839 // an aggregate.
840 // FIXME: In C++0x, this is yet another form of initialization.
841 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
842 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
843 if (!ClassDecl->isAggregate())
Chris Lattnerdcd5ef12008-11-19 05:27:50 +0000844 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattnerd1625842008-11-24 06:25:27 +0000845 << DeclType << Init->getSourceRange();
Douglas Gregor64bffa92008-11-05 16:20:31 +0000846 }
Steve Naroff2fdc3742007-12-10 22:44:33 +0000847 }
Eli Friedmane6f058f2008-06-06 19:40:52 +0000848
Steve Naroff0cca7492008-05-01 22:18:59 +0000849 InitListChecker CheckInitList(this, InitList, DeclType);
850 return CheckInitList.HadError();
Steve Narofff0090632007-09-02 02:04:30 +0000851}
852
Douglas Gregor10bd3682008-11-17 22:58:34 +0000853/// GetNameForDeclarator - Determine the full declaration name for the
854/// given Declarator.
855DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
856 switch (D.getKind()) {
857 case Declarator::DK_Abstract:
858 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
859 return DeclarationName();
860
861 case Declarator::DK_Normal:
862 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
863 return DeclarationName(D.getIdentifier());
864
865 case Declarator::DK_Constructor: {
866 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
867 Ty = Context.getCanonicalType(Ty);
868 return Context.DeclarationNames.getCXXConstructorName(Ty);
869 }
870
871 case Declarator::DK_Destructor: {
872 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
873 Ty = Context.getCanonicalType(Ty);
874 return Context.DeclarationNames.getCXXDestructorName(Ty);
875 }
876
877 case Declarator::DK_Conversion: {
878 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
879 Ty = Context.getCanonicalType(Ty);
880 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
881 }
Douglas Gregore94ca9e42008-11-18 14:39:36 +0000882
883 case Declarator::DK_Operator:
884 assert(D.getIdentifier() == 0 && "operator names have no identifier");
885 return Context.DeclarationNames.getCXXOperatorName(
886 D.getOverloadedOperator());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000887 }
888
889 assert(false && "Unknown name kind");
890 return DeclarationName();
891}
892
Fariborz Jahanian306d68f2007-11-08 23:49:49 +0000893Sema::DeclTy *
Daniel Dunbar914701e2008-08-05 16:28:08 +0000894Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl) {
Steve Naroff94745042007-09-13 23:52:58 +0000895 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor10bd3682008-11-17 22:58:34 +0000896 DeclarationName Name = GetNameForDeclarator(D);
897
Chris Lattnere80a59c2007-07-25 00:24:17 +0000898 // All of these full declarators require an identifier. If it doesn't have
899 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor10bd3682008-11-17 22:58:34 +0000900 if (!Name) {
Chris Lattner1f6f54b2008-11-11 06:13:16 +0000901 if (!D.getInvalidType()) // Reject this if we think it is valid.
902 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattnerfa25bbb2008-11-19 05:08:23 +0000903 diag::err_declarator_need_ident)
904 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattnere80a59c2007-07-25 00:24:17 +0000905 return 0;
906 }
907
Chris Lattner31e05722007-08-26 06:24:45 +0000908 // The scope passed in may not be a decl scope. Zip up the scope tree until
909 // we find one that is.
Douglas Gregor44b43212008-12-11 16:49:14 +0000910 while ((S->getFlags() & Scope::DeclScope) == 0 ||
911 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattner31e05722007-08-26 06:24:45 +0000912 S = S->getParent();
913
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000914 DeclContext *DC;
915 Decl *PrevDecl;
Steve Naroffc752d042007-09-13 18:10:37 +0000916 ScopedDecl *New;
Steve Naroff5912a352007-08-28 20:14:24 +0000917 bool InvalidDecl = false;
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000918
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000919 // See if this is a redefinition of a variable in the same scope.
920 if (!D.getCXXScopeSpec().isSet()) {
921 DC = CurContext;
Douglas Gregor10bd3682008-11-17 22:58:34 +0000922 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000923 } else { // Something like "int foo::x;"
924 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor10bd3682008-11-17 22:58:34 +0000925 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000926
927 // C++ 7.3.1.2p2:
928 // Members (including explicit specializations of templates) of a named
929 // namespace can also be defined outside that namespace by explicit
930 // qualification of the name being defined, provided that the entity being
931 // defined was already declared in the namespace and the definition appears
932 // after the point of declaration in a namespace that encloses the
933 // declarations namespace.
934 //
935 if (PrevDecl == 0) {
936 // No previous declaration in the qualifying scope.
Chris Lattnerd3a94e22008-11-20 06:06:08 +0000937 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
Chris Lattner08631c52008-11-23 21:45:46 +0000938 << Name << D.getCXXScopeSpec().getRange();
Douglas Gregor44b43212008-12-11 16:49:14 +0000939 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000940 } else if (!CurContext->Encloses(DC)) {
941 // The qualifying scope doesn't enclose the original declaration.
942 // Emit diagnostic based on current scope.
943 SourceLocation L = D.getIdentifierLoc();
944 SourceRange R = D.getCXXScopeSpec().getRange();
945 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner011bb4e2008-11-23 20:28:15 +0000946 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000947 } else {
Chris Lattner011bb4e2008-11-23 20:28:15 +0000948 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000949 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000950 }
Douglas Gregor44b43212008-12-11 16:49:14 +0000951 InvalidDecl = true;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000952 }
953 }
954
Douglas Gregorf57172b2008-12-08 18:40:42 +0000955 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +0000956 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor898574e2008-12-05 23:32:09 +0000957 InvalidDecl = InvalidDecl
958 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregor72c3f312008-12-05 18:15:24 +0000959 // Just pretend that we didn't see the previous declaration.
960 PrevDecl = 0;
961 }
962
Douglas Gregor2ce52f32008-04-13 21:07:44 +0000963 // In C++, the previous declaration we find might be a tag type
964 // (class or enum). In this case, the new declaration will hide the
965 // tag type.
966 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
967 PrevDecl = 0;
968
Chris Lattner41af0932007-11-14 06:34:38 +0000969 QualType R = GetTypeForDeclarator(D, S);
970 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
971
Reid Spencer5f016e22007-07-11 17:01:13 +0000972 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregor6d6eb572008-05-07 04:49:29 +0000973 // Check that there are no default arguments (C++ only).
974 if (getLangOptions().CPlusPlus)
975 CheckExtraCXXDefaultArguments(D);
976
Chris Lattner41af0932007-11-14 06:34:38 +0000977 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Reid Spencer5f016e22007-07-11 17:01:13 +0000978 if (!NewTD) return 0;
979
980 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +0000981 ProcessDeclAttributes(NewTD, D);
Steve Naroffffce4d52008-01-09 23:34:55 +0000982 // Merge the decl with the existing one if appropriate. If the decl is
983 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +0000984 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000985 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
986 if (NewTD == 0) return 0;
987 }
988 New = NewTD;
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +0000989 if (S->getFnParent() == 0) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000990 // C99 6.7.7p2: If a typedef name specifies a variably modified type
991 // then it shall have block scope.
Eli Friedman9db13972008-02-15 12:53:51 +0000992 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +0000993 if (NewTD->getUnderlyingType()->isVariableArrayType())
994 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
995 else
996 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
997
Steve Naroffd7444aa2007-08-31 17:20:07 +0000998 InvalidDecl = true;
Reid Spencer5f016e22007-07-11 17:01:13 +0000999 }
1000 }
Chris Lattner41af0932007-11-14 06:34:38 +00001001 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner271f1a62007-09-27 15:15:46 +00001002 FunctionDecl::StorageClass SC = FunctionDecl::None;
Reid Spencer5f016e22007-07-11 17:01:13 +00001003 switch (D.getDeclSpec().getStorageClassSpec()) {
1004 default: assert(0 && "Unknown storage class!");
1005 case DeclSpec::SCS_auto:
1006 case DeclSpec::SCS_register:
Sebastian Redl669d5d72008-11-14 23:42:31 +00001007 case DeclSpec::SCS_mutable:
Chris Lattnerd1625842008-11-24 06:25:27 +00001008 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroff5912a352007-08-28 20:14:24 +00001009 InvalidDecl = true;
1010 break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001011 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1012 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1013 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroff7dd0bd42008-01-28 21:57:15 +00001014 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Reid Spencer5f016e22007-07-11 17:01:13 +00001015 }
1016
Chris Lattnera98e58d2008-03-15 21:24:04 +00001017 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor42a552f2008-11-05 20:51:48 +00001018 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorb48fe382008-10-31 09:07:45 +00001019 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1020
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001021 FunctionDecl *NewFD;
Douglas Gregor42a552f2008-11-05 20:51:48 +00001022 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorb48fe382008-10-31 09:07:45 +00001023 // This is a C++ constructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001024 assert(DC->isCXXRecord() &&
Douglas Gregorb48fe382008-10-31 09:07:45 +00001025 "Constructors can only be declared in a member context");
1026
Douglas Gregor42a552f2008-11-05 20:51:48 +00001027 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001028
1029 // Create the new declaration
1030 NewFD = CXXConstructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001031 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001032 D.getIdentifierLoc(), Name, R,
Douglas Gregorb48fe382008-10-31 09:07:45 +00001033 isExplicit, isInline,
1034 /*isImplicitlyDeclared=*/false);
1035
Douglas Gregor42a552f2008-11-05 20:51:48 +00001036 if (isInvalidDecl)
1037 NewFD->setInvalidDecl();
1038 } else if (D.getKind() == Declarator::DK_Destructor) {
1039 // This is a C++ destructor declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001040 if (DC->isCXXRecord()) {
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001041 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001042
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001043 NewFD = CXXDestructorDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001044 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001045 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001046 isInline,
1047 /*isImplicitlyDeclared=*/false);
Douglas Gregor42a552f2008-11-05 20:51:48 +00001048
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001049 if (isInvalidDecl)
1050 NewFD->setInvalidDecl();
1051 } else {
1052 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1053 // Create a FunctionDecl to satisfy the function definition parsing
1054 // code path.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001055 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001056 Name, R, SC, isInline, LastDeclarator,
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001057 // FIXME: Move to DeclGroup...
1058 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor42a552f2008-11-05 20:51:48 +00001059 NewFD->setInvalidDecl();
Argyrios Kyrtzidisc7ed9c62008-11-07 22:02:30 +00001060 }
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001061 } else if (D.getKind() == Declarator::DK_Conversion) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001062 if (!DC->isCXXRecord()) {
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001063 Diag(D.getIdentifierLoc(),
1064 diag::err_conv_function_not_member);
1065 return 0;
1066 } else {
1067 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1068
1069 NewFD = CXXConversionDecl::Create(Context,
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001070 cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001071 D.getIdentifierLoc(), Name, R,
Douglas Gregor2f1bc522008-11-07 20:08:42 +00001072 isInline, isExplicit);
1073
1074 if (isInvalidDecl)
1075 NewFD->setInvalidDecl();
1076 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001077 } else if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001078 // This is a C++ method declaration.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001079 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001080 D.getIdentifierLoc(), Name, R,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001081 (SC == FunctionDecl::Static), isInline,
1082 LastDeclarator);
1083 } else {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001084 NewFD = FunctionDecl::Create(Context, DC,
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001085 D.getIdentifierLoc(),
Douglas Gregor10bd3682008-11-17 22:58:34 +00001086 Name, R, SC, isInline, LastDeclarator,
Steve Naroff0eb07bf2008-10-03 00:02:03 +00001087 // FIXME: Move to DeclGroup...
1088 D.getDeclSpec().getSourceRange().getBegin());
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001089 }
Ted Kremenekf5c93c12008-02-27 22:18:07 +00001090 // Handle attributes.
Chris Lattner3ff30c82008-06-29 00:02:00 +00001091 ProcessDeclAttributes(NewFD, D);
Chris Lattner04421082008-04-08 04:40:51 +00001092
Daniel Dunbara80f8742008-08-05 01:35:17 +00001093 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar914701e2008-08-05 16:28:08 +00001094 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbara80f8742008-08-05 01:35:17 +00001095 // The parser guarantees this is a string.
1096 StringLiteral *SE = cast<StringLiteral>(E);
1097 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1098 SE->getByteLength())));
1099 }
1100
Chris Lattner04421082008-04-08 04:40:51 +00001101 // Copy the parameter declarations from the declarator D to
1102 // the function declaration NewFD, if they are available.
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001103 if (D.getNumTypeObjects() > 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001104 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1105
1106 // Create Decl objects for each parameter, adding them to the
1107 // FunctionDecl.
1108 llvm::SmallVector<ParmVarDecl*, 16> Params;
1109
1110 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1111 // function that takes no arguments, not a function that takes a
Chris Lattner8123a952008-04-10 02:22:51 +00001112 // single void argument.
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001113 // We let through "const void" here because Sema::GetTypeForDeclarator
1114 // already checks for that case.
Chris Lattner04421082008-04-08 04:40:51 +00001115 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1116 FTI.ArgInfo[0].Param &&
Chris Lattner04421082008-04-08 04:40:51 +00001117 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1118 // empty arg list, don't push any params.
Chris Lattner8123a952008-04-10 02:22:51 +00001119 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1120
Chris Lattnerdef026a2008-04-10 02:26:16 +00001121 // In C++, the empty parameter-type-list must be spelled "void"; a
1122 // typedef of void is not permitted.
1123 if (getLangOptions().CPlusPlus &&
Eli Friedman6d1e4b52008-05-22 08:54:03 +00001124 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner8123a952008-04-10 02:22:51 +00001125 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1126 }
Eli Friedmaneb4b7052008-08-25 21:31:01 +00001127 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner04421082008-04-08 04:40:51 +00001128 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1129 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1130 }
1131
1132 NewFD->setParams(&Params[0], Params.size());
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001133 } else if (R->getAsTypedefType()) {
1134 // When we're declaring a function with a typedef, as in the
1135 // following example, we'll need to synthesize (unnamed)
1136 // parameters for use in the declaration.
1137 //
1138 // @code
1139 // typedef void fn(int);
1140 // fn f;
1141 // @endcode
1142 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1143 if (!FT) {
1144 // This is a typedef of a function with no prototype, so we
1145 // don't need to do anything.
1146 } else if ((FT->getNumArgs() == 0) ||
1147 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1148 FT->getArgType(0)->isVoidType())) {
1149 // This is a zero-argument function. We don't need to do anything.
1150 } else {
1151 // Synthesize a parameter for each argument type.
1152 llvm::SmallVector<ParmVarDecl*, 16> Params;
1153 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1154 ArgType != FT->arg_type_end(); ++ArgType) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001155 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregor6cbd3df2008-10-24 18:09:54 +00001156 SourceLocation(), 0,
1157 *ArgType, VarDecl::None,
1158 0, 0));
1159 }
1160
1161 NewFD->setParams(&Params[0], Params.size());
1162 }
Chris Lattner04421082008-04-08 04:40:51 +00001163 }
1164
Douglas Gregor42a552f2008-11-05 20:51:48 +00001165 // C++ constructors and destructors are handled by separate
1166 // routines, since they don't require any declaration merging (C++
1167 // [class.mfct]p2) and they aren't ever pushed into scope, because
1168 // they can't be found by name lookup anyway (C++ [class.ctor]p2).
1169 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1170 return ActOnConstructorDeclarator(Constructor);
1171 else if (CXXDestructorDecl *Destructor = dyn_cast<CXXDestructorDecl>(NewFD))
1172 return ActOnDestructorDeclarator(Destructor);
Douglas Gregor2def4832008-11-17 20:34:05 +00001173
1174 // Extra checking for conversion functions, including recording
1175 // the conversion function in its class.
1176 if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
1177 ActOnConversionDeclarator(Conversion);
Douglas Gregorb48fe382008-10-31 09:07:45 +00001178
Douglas Gregor1cd1b1e2008-11-06 22:13:31 +00001179 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1180 if (NewFD->isOverloadedOperator() &&
1181 CheckOverloadedOperatorDeclaration(NewFD))
1182 NewFD->setInvalidDecl();
1183
Steve Naroffffce4d52008-01-09 23:34:55 +00001184 // Merge the decl with the existing one if appropriate. Since C functions
1185 // are in a flat namespace, make sure we consider decls in outer scopes.
Argyrios Kyrtzidis00bc6452008-05-09 23:39:43 +00001186 if (PrevDecl &&
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001187 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregorf0097952008-04-21 02:02:58 +00001188 bool Redeclaration = false;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001189
1190 // If C++, determine whether NewFD is an overload of PrevDecl or
1191 // a declaration that requires merging. If it's an overload,
1192 // there's no more work to do here; we'll just add the new
1193 // function to the scope.
1194 OverloadedFunctionDecl::function_iterator MatchedDecl;
1195 if (!getLangOptions().CPlusPlus ||
1196 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1197 Decl *OldDecl = PrevDecl;
1198
1199 // If PrevDecl was an overloaded function, extract the
1200 // FunctionDecl that matched.
1201 if (isa<OverloadedFunctionDecl>(PrevDecl))
1202 OldDecl = *MatchedDecl;
1203
1204 // NewFD and PrevDecl represent declarations that need to be
1205 // merged.
1206 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1207
1208 if (NewFD == 0) return 0;
1209 if (Redeclaration) {
1210 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1211
1212 if (OldDecl == PrevDecl) {
1213 // Remove the name binding for the previous
Douglas Gregor44b43212008-12-11 16:49:14 +00001214 // declaration.
1215 if (S->isDeclScope(PrevDecl)) {
1216 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1217 S->RemoveDecl(PrevDecl);
1218 }
1219
1220 // Introduce the new binding for this declaration.
1221 IdResolver.AddDecl(NewFD);
1222 if (getLangOptions().CPlusPlus && NewFD->getParent())
1223 NewFD->getParent()->insert(Context, NewFD);
1224
1225 // Add the redeclaration to the current scope, since we'll
1226 // be skipping PushOnScopeChains.
1227 S->AddDecl(NewFD);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001228 } else {
1229 // We need to update the OverloadedFunctionDecl with the
1230 // latest declaration of this function, so that name
1231 // lookup will always refer to the latest declaration of
1232 // this function.
1233 *MatchedDecl = NewFD;
Douglas Gregor44b43212008-12-11 16:49:14 +00001234 }
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001235
Douglas Gregor44b43212008-12-11 16:49:14 +00001236 if (getLangOptions().CPlusPlus) {
1237 // Add this declaration to the current context.
1238 CurContext->addDecl(Context, NewFD, false);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001239
Douglas Gregor44b43212008-12-11 16:49:14 +00001240 // Check default arguments now that we have merged decls.
1241 CheckCXXDefaultArguments(NewFD);
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001242 }
Douglas Gregor44b43212008-12-11 16:49:14 +00001243
1244 // Set the lexical context. If the declarator has a C++
1245 // scope specifier, the lexical context will be different
1246 // from the semantic context.
1247 NewFD->setLexicalDeclContext(CurContext);
1248
1249 return NewFD;
Douglas Gregor8e9bebd2008-10-21 16:13:35 +00001250 }
Douglas Gregorf0097952008-04-21 02:02:58 +00001251 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001252 }
1253 New = NewFD;
Chris Lattner04421082008-04-08 04:40:51 +00001254
1255 // In C++, check default arguments now that we have merged decls.
1256 if (getLangOptions().CPlusPlus)
1257 CheckCXXDefaultArguments(NewFD);
Reid Spencer5f016e22007-07-11 17:01:13 +00001258 } else {
Douglas Gregor6d6eb572008-05-07 04:49:29 +00001259 // Check that there are no default arguments (C++ only).
1260 if (getLangOptions().CPlusPlus)
1261 CheckExtraCXXDefaultArguments(D);
1262
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001263 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00001264 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1265 << D.getIdentifier();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00001266 InvalidDecl = true;
1267 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001268
1269 VarDecl *NewVD;
1270 VarDecl::StorageClass SC;
1271 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner9e151e12008-03-15 21:10:16 +00001272 default: assert(0 && "Unknown storage class!");
1273 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1274 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1275 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1276 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1277 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1278 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001279 case DeclSpec::SCS_mutable:
1280 // mutable can only appear on non-static class members, so it's always
1281 // an error here
1282 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1283 InvalidDecl = true;
Douglas Gregore89b0282008-12-01 22:46:22 +00001284 SC = VarDecl::None;
Sebastian Redla11f42f2008-11-17 23:24:37 +00001285 break;
Sebastian Redl669d5d72008-11-14 23:42:31 +00001286 }
Douglas Gregor10bd3682008-11-17 22:58:34 +00001287
1288 IdentifierInfo *II = Name.getAsIdentifierInfo();
1289 if (!II) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001290 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1291 << Name.getAsString();
Douglas Gregor10bd3682008-11-17 22:58:34 +00001292 return 0;
1293 }
1294
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001295 if (DC->isCXXRecord()) {
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001296 assert(SC == VarDecl::Static && "Invalid storage class for member!");
1297 // This is a static data member for a C++ class.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001298 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001299 D.getIdentifierLoc(), II,
1300 R, LastDeclarator);
Steve Narofff0090632007-09-02 02:04:30 +00001301 } else {
Daniel Dunbar6f0200e2008-09-08 20:05:47 +00001302 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001303 if (S->getFnParent() == 0) {
1304 // C99 6.9p2: The storage-class specifiers auto and register shall not
1305 // appear in the declaration specifiers in an external declaration.
1306 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattnerd1625842008-11-24 06:25:27 +00001307 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001308 InvalidDecl = true;
1309 }
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00001310 }
Sebastian Redl669d5d72008-11-14 23:42:31 +00001311 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1312 II, R, SC, LastDeclarator,
1313 // FIXME: Move to DeclGroup...
1314 D.getDeclSpec().getSourceRange().getBegin());
1315 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroff53a32342007-08-28 18:45:29 +00001316 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001317 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner3ff30c82008-06-29 00:02:00 +00001318 ProcessDeclAttributes(NewVD, D);
Nate Begemanc8e89a82008-03-14 18:07:10 +00001319
Daniel Dunbara735ad82008-08-06 00:03:29 +00001320 // Handle GNU asm-label extension (encoded as an attribute).
1321 if (Expr *E = (Expr*) D.getAsmLabel()) {
1322 // The parser guarantees this is a string.
1323 StringLiteral *SE = cast<StringLiteral>(E);
1324 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1325 SE->getByteLength())));
1326 }
1327
Nate Begemanc8e89a82008-03-14 18:07:10 +00001328 // Emit an error if an address space was applied to decl with local storage.
1329 // This includes arrays of objects with address space qualifiers, but not
1330 // automatic variables that point to other address spaces.
1331 // ISO/IEC TR 18037 S5.1.2
Nate Begeman8e7dafe2008-03-25 18:36:32 +00001332 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1333 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1334 InvalidDecl = true;
Nate Begeman5af27e02008-03-14 00:22:18 +00001335 }
Steve Naroffffce4d52008-01-09 23:34:55 +00001336 // Merge the decl with the existing one if appropriate. If the decl is
1337 // in an outer scope, it isn't the same thing.
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00001338 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00001339 NewVD = MergeVarDecl(NewVD, PrevDecl);
1340 if (NewVD == 0) return 0;
1341 }
Reid Spencer5f016e22007-07-11 17:01:13 +00001342 New = NewVD;
1343 }
1344
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00001345 // Set the lexical context. If the declarator has a C++ scope specifier, the
1346 // lexical context will be different from the semantic context.
1347 New->setLexicalDeclContext(CurContext);
1348
Reid Spencer5f016e22007-07-11 17:01:13 +00001349 // If this has an identifier, add it to the scope stack.
Douglas Gregor10bd3682008-11-17 22:58:34 +00001350 if (Name)
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00001351 PushOnScopeChains(New, S);
Steve Naroff5912a352007-08-28 20:14:24 +00001352 // If any semantic error occurred, mark the decl as invalid.
1353 if (D.getInvalidType() || InvalidDecl)
1354 New->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00001355
1356 return New;
1357}
1358
Steve Naroff6594a702008-10-27 11:34:16 +00001359void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001360 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1361 << Init->getSourceRange();
Steve Naroff6594a702008-10-27 11:34:16 +00001362}
1363
Eli Friedmanc594b322008-05-20 13:48:25 +00001364bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1365 switch (Init->getStmtClass()) {
1366 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001367 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001368 return true;
1369 case Expr::ParenExprClass: {
1370 const ParenExpr* PE = cast<ParenExpr>(Init);
1371 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1372 }
1373 case Expr::CompoundLiteralExprClass:
1374 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1375 case Expr::DeclRefExprClass: {
1376 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman97c0a392008-05-21 03:39:11 +00001377 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1378 if (VD->hasGlobalStorage())
1379 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001380 InitializerElementNotConstant(Init);
Eli Friedman97c0a392008-05-21 03:39:11 +00001381 return true;
1382 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001383 if (isa<FunctionDecl>(D))
1384 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001385 InitializerElementNotConstant(Init);
Steve Naroffd0091aa2008-01-10 22:15:12 +00001386 return true;
1387 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001388 case Expr::MemberExprClass: {
1389 const MemberExpr *M = cast<MemberExpr>(Init);
1390 if (M->isArrow())
1391 return CheckAddressConstantExpression(M->getBase());
1392 return CheckAddressConstantExpressionLValue(M->getBase());
1393 }
1394 case Expr::ArraySubscriptExprClass: {
1395 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1396 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1397 return CheckAddressConstantExpression(ASE->getBase()) ||
1398 CheckArithmeticConstantExpression(ASE->getIdx());
1399 }
1400 case Expr::StringLiteralClass:
Chris Lattnerd9f69102008-08-10 01:53:14 +00001401 case Expr::PredefinedExprClass:
Eli Friedmanc594b322008-05-20 13:48:25 +00001402 return false;
1403 case Expr::UnaryOperatorClass: {
1404 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1405
1406 // C99 6.6p9
1407 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman97c0a392008-05-21 03:39:11 +00001408 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001409
Steve Naroff6594a702008-10-27 11:34:16 +00001410 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001411 return true;
1412 }
1413 }
1414}
1415
1416bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1417 switch (Init->getStmtClass()) {
1418 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001419 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001420 return true;
Chris Lattner506ff882008-10-06 07:26:43 +00001421 case Expr::ParenExprClass:
1422 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedmanc594b322008-05-20 13:48:25 +00001423 case Expr::StringLiteralClass:
1424 case Expr::ObjCStringLiteralClass:
1425 return false;
Chris Lattner506ff882008-10-06 07:26:43 +00001426 case Expr::CallExprClass:
Douglas Gregorb4609802008-11-14 16:09:21 +00001427 case Expr::CXXOperatorCallExprClass:
Chris Lattner506ff882008-10-06 07:26:43 +00001428 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1429 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1430 Builtin::BI__builtin___CFStringMakeConstantString)
1431 return false;
1432
Steve Naroff6594a702008-10-27 11:34:16 +00001433 InitializerElementNotConstant(Init);
Chris Lattner506ff882008-10-06 07:26:43 +00001434 return true;
1435
Eli Friedmanc594b322008-05-20 13:48:25 +00001436 case Expr::UnaryOperatorClass: {
1437 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1438
1439 // C99 6.6p9
1440 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1441 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1442
1443 if (Exp->getOpcode() == UnaryOperator::Extension)
1444 return CheckAddressConstantExpression(Exp->getSubExpr());
1445
Steve Naroff6594a702008-10-27 11:34:16 +00001446 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001447 return true;
1448 }
1449 case Expr::BinaryOperatorClass: {
1450 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1451 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1452
1453 Expr *PExp = Exp->getLHS();
1454 Expr *IExp = Exp->getRHS();
1455 if (IExp->getType()->isPointerType())
1456 std::swap(PExp, IExp);
1457
1458 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1459 return CheckAddressConstantExpression(PExp) ||
1460 CheckArithmeticConstantExpression(IExp);
1461 }
Eli Friedmanc3f07642008-08-25 20:46:57 +00001462 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001463 case Expr::CStyleCastExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001464 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmanc3f07642008-08-25 20:46:57 +00001465 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1466 // Check for implicit promotion
1467 if (SubExpr->getType()->isFunctionType() ||
1468 SubExpr->getType()->isArrayType())
1469 return CheckAddressConstantExpressionLValue(SubExpr);
1470 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001471
1472 // Check for pointer->pointer cast
1473 if (SubExpr->getType()->isPointerType())
1474 return CheckAddressConstantExpression(SubExpr);
1475
Eli Friedmanc3f07642008-08-25 20:46:57 +00001476 if (SubExpr->getType()->isIntegralType()) {
1477 // Check for the special-case of a pointer->int->pointer cast;
1478 // this isn't standard, but some code requires it. See
1479 // PR2720 for an example.
1480 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1481 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1482 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1483 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1484 if (IntWidth >= PointerWidth) {
1485 return CheckAddressConstantExpression(SubCast->getSubExpr());
1486 }
1487 }
1488 }
1489 }
1490 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001491 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedmanc3f07642008-08-25 20:46:57 +00001492 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001493
Steve Naroff6594a702008-10-27 11:34:16 +00001494 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001495 return true;
1496 }
1497 case Expr::ConditionalOperatorClass: {
1498 // FIXME: Should we pedwarn here?
1499 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1500 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001501 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001502 return true;
1503 }
1504 if (CheckArithmeticConstantExpression(Exp->getCond()))
1505 return true;
1506 if (Exp->getLHS() &&
1507 CheckAddressConstantExpression(Exp->getLHS()))
1508 return true;
1509 return CheckAddressConstantExpression(Exp->getRHS());
1510 }
1511 case Expr::AddrLabelExprClass:
1512 return false;
1513 }
1514}
1515
Eli Friedman4caf0552008-06-09 05:05:07 +00001516static const Expr* FindExpressionBaseAddress(const Expr* E);
1517
1518static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1519 switch (E->getStmtClass()) {
1520 default:
1521 return E;
1522 case Expr::ParenExprClass: {
1523 const ParenExpr* PE = cast<ParenExpr>(E);
1524 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1525 }
1526 case Expr::MemberExprClass: {
1527 const MemberExpr *M = cast<MemberExpr>(E);
1528 if (M->isArrow())
1529 return FindExpressionBaseAddress(M->getBase());
1530 return FindExpressionBaseAddressLValue(M->getBase());
1531 }
1532 case Expr::ArraySubscriptExprClass: {
1533 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1534 return FindExpressionBaseAddress(ASE->getBase());
1535 }
1536 case Expr::UnaryOperatorClass: {
1537 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1538
1539 if (Exp->getOpcode() == UnaryOperator::Deref)
1540 return FindExpressionBaseAddress(Exp->getSubExpr());
1541
1542 return E;
1543 }
1544 }
1545}
1546
1547static const Expr* FindExpressionBaseAddress(const Expr* E) {
1548 switch (E->getStmtClass()) {
1549 default:
1550 return E;
1551 case Expr::ParenExprClass: {
1552 const ParenExpr* PE = cast<ParenExpr>(E);
1553 return FindExpressionBaseAddress(PE->getSubExpr());
1554 }
1555 case Expr::UnaryOperatorClass: {
1556 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1557
1558 // C99 6.6p9
1559 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1560 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1561
1562 if (Exp->getOpcode() == UnaryOperator::Extension)
1563 return FindExpressionBaseAddress(Exp->getSubExpr());
1564
1565 return E;
1566 }
1567 case Expr::BinaryOperatorClass: {
1568 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1569
1570 Expr *PExp = Exp->getLHS();
1571 Expr *IExp = Exp->getRHS();
1572 if (IExp->getType()->isPointerType())
1573 std::swap(PExp, IExp);
1574
1575 return FindExpressionBaseAddress(PExp);
1576 }
1577 case Expr::ImplicitCastExprClass: {
1578 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1579
1580 // Check for implicit promotion
1581 if (SubExpr->getType()->isFunctionType() ||
1582 SubExpr->getType()->isArrayType())
1583 return FindExpressionBaseAddressLValue(SubExpr);
1584
1585 // Check for pointer->pointer cast
1586 if (SubExpr->getType()->isPointerType())
1587 return FindExpressionBaseAddress(SubExpr);
1588
1589 // We assume that we have an arithmetic expression here;
1590 // if we don't, we'll figure it out later
1591 return 0;
1592 }
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001593 case Expr::CStyleCastExprClass: {
Eli Friedman4caf0552008-06-09 05:05:07 +00001594 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1595
1596 // Check for pointer->pointer cast
1597 if (SubExpr->getType()->isPointerType())
1598 return FindExpressionBaseAddress(SubExpr);
1599
1600 // We assume that we have an arithmetic expression here;
1601 // if we don't, we'll figure it out later
1602 return 0;
1603 }
1604 }
1605}
1606
Anders Carlsson51fe9962008-11-22 21:04:56 +00001607bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedmanc594b322008-05-20 13:48:25 +00001608 switch (Init->getStmtClass()) {
1609 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001610 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001611 return true;
1612 case Expr::ParenExprClass: {
1613 const ParenExpr* PE = cast<ParenExpr>(Init);
1614 return CheckArithmeticConstantExpression(PE->getSubExpr());
1615 }
1616 case Expr::FloatingLiteralClass:
1617 case Expr::IntegerLiteralClass:
1618 case Expr::CharacterLiteralClass:
1619 case Expr::ImaginaryLiteralClass:
1620 case Expr::TypesCompatibleExprClass:
1621 case Expr::CXXBoolLiteralExprClass:
1622 return false;
Douglas Gregorb4609802008-11-14 16:09:21 +00001623 case Expr::CallExprClass:
1624 case Expr::CXXOperatorCallExprClass: {
Eli Friedmanc594b322008-05-20 13:48:25 +00001625 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001626
1627 // Allow any constant foldable calls to builtins.
1628 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedmanc594b322008-05-20 13:48:25 +00001629 return false;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001630
Steve Naroff6594a702008-10-27 11:34:16 +00001631 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001632 return true;
1633 }
1634 case Expr::DeclRefExprClass: {
1635 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1636 if (isa<EnumConstantDecl>(D))
1637 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001638 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001639 return true;
1640 }
1641 case Expr::CompoundLiteralExprClass:
1642 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1643 // but vectors are allowed to be magic.
1644 if (Init->getType()->isVectorType())
1645 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001646 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001647 return true;
1648 case Expr::UnaryOperatorClass: {
1649 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1650
1651 switch (Exp->getOpcode()) {
1652 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1653 // See C99 6.6p3.
1654 default:
Steve Naroff6594a702008-10-27 11:34:16 +00001655 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001656 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001657 case UnaryOperator::OffsetOf:
Eli Friedmanc594b322008-05-20 13:48:25 +00001658 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1659 return false;
Steve Naroff6594a702008-10-27 11:34:16 +00001660 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001661 return true;
1662 case UnaryOperator::Extension:
1663 case UnaryOperator::LNot:
1664 case UnaryOperator::Plus:
1665 case UnaryOperator::Minus:
1666 case UnaryOperator::Not:
1667 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1668 }
1669 }
Sebastian Redl05189992008-11-11 17:56:53 +00001670 case Expr::SizeOfAlignOfExprClass: {
1671 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001672 // Special check for void types, which are allowed as an extension
Sebastian Redl05189992008-11-11 17:56:53 +00001673 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedmanc594b322008-05-20 13:48:25 +00001674 return false;
1675 // alignof always evaluates to a constant.
1676 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl05189992008-11-11 17:56:53 +00001677 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Naroff6594a702008-10-27 11:34:16 +00001678 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001679 return true;
1680 }
1681 return false;
1682 }
1683 case Expr::BinaryOperatorClass: {
1684 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1685
1686 if (Exp->getLHS()->getType()->isArithmeticType() &&
1687 Exp->getRHS()->getType()->isArithmeticType()) {
1688 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1689 CheckArithmeticConstantExpression(Exp->getRHS());
1690 }
1691
Eli Friedman4caf0552008-06-09 05:05:07 +00001692 if (Exp->getLHS()->getType()->isPointerType() &&
1693 Exp->getRHS()->getType()->isPointerType()) {
1694 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1695 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1696
1697 // Only allow a null (constant integer) base; we could
1698 // allow some additional cases if necessary, but this
1699 // is sufficient to cover offsetof-like constructs.
1700 if (!LHSBase && !RHSBase) {
1701 return CheckAddressConstantExpression(Exp->getLHS()) ||
1702 CheckAddressConstantExpression(Exp->getRHS());
1703 }
1704 }
1705
Steve Naroff6594a702008-10-27 11:34:16 +00001706 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001707 return true;
1708 }
1709 case Expr::ImplicitCastExprClass:
Douglas Gregor6eec8e82008-10-28 15:36:24 +00001710 case Expr::CStyleCastExprClass: {
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001711 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman6d4abe12008-09-01 22:08:17 +00001712 if (SubExpr->getType()->isArithmeticType())
1713 return CheckArithmeticConstantExpression(SubExpr);
1714
Eli Friedmanb529d832008-09-02 09:37:00 +00001715 if (SubExpr->getType()->isPointerType()) {
1716 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1717 // If the pointer has a null base, this is an offsetof-like construct
1718 if (!Base)
1719 return CheckAddressConstantExpression(SubExpr);
1720 }
1721
Steve Naroff6594a702008-10-27 11:34:16 +00001722 InitializerElementNotConstant(Init);
Eli Friedman6d4abe12008-09-01 22:08:17 +00001723 return true;
Eli Friedmanc594b322008-05-20 13:48:25 +00001724 }
1725 case Expr::ConditionalOperatorClass: {
1726 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner46cfefa2008-10-06 05:42:39 +00001727
1728 // If GNU extensions are disabled, we require all operands to be arithmetic
1729 // constant expressions.
1730 if (getLangOptions().NoExtensions) {
1731 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1732 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1733 CheckArithmeticConstantExpression(Exp->getRHS());
1734 }
1735
1736 // Otherwise, we have to emulate some of the behavior of fold here.
1737 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1738 // because it can constant fold things away. To retain compatibility with
1739 // GCC code, we see if we can fold the condition to a constant (which we
1740 // should always be able to do in theory). If so, we only require the
1741 // specified arm of the conditional to be a constant. This is a horrible
1742 // hack, but is require by real world code that uses __builtin_constant_p.
1743 APValue Val;
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001744 if (!Exp->getCond()->Evaluate(Val, Context)) {
1745 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner46cfefa2008-10-06 05:42:39 +00001746 // won't be able to either. Use it to emit the diagnostic though.
1747 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattner6ee7aa12008-11-16 21:24:15 +00001748 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner46cfefa2008-10-06 05:42:39 +00001749 return Res;
1750 }
1751
1752 // Verify that the side following the condition is also a constant.
1753 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
1754 if (Val.getInt() == 0)
1755 std::swap(TrueSide, FalseSide);
1756
1757 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedmanc594b322008-05-20 13:48:25 +00001758 return true;
Chris Lattner46cfefa2008-10-06 05:42:39 +00001759
1760 // Okay, the evaluated side evaluates to a constant, so we accept this.
1761 // Check to see if the other side is obviously not a constant. If so,
1762 // emit a warning that this is a GNU extension.
Chris Lattner45b6b9d2008-10-06 06:49:02 +00001763 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner46cfefa2008-10-06 05:42:39 +00001764 Diag(Init->getExprLoc(),
Chris Lattnerdcd5ef12008-11-19 05:27:50 +00001765 diag::ext_typecheck_expression_not_constant_but_accepted)
1766 << FalseSide->getSourceRange();
Chris Lattner46cfefa2008-10-06 05:42:39 +00001767 return false;
Eli Friedmanc594b322008-05-20 13:48:25 +00001768 }
1769 }
1770}
1771
1772bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001773 Expr::EvalResult Result;
1774
Nuno Lopes9a979c32008-07-07 16:46:50 +00001775 Init = Init->IgnoreParens();
1776
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001777 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1778 return false;
1779
Eli Friedmanc594b322008-05-20 13:48:25 +00001780 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1781 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1782 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1783
Nuno Lopes9a979c32008-07-07 16:46:50 +00001784 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1785 return CheckForConstantInitializer(e->getInitializer(), DclT);
1786
Eli Friedmanc594b322008-05-20 13:48:25 +00001787 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1788 unsigned numInits = Exp->getNumInits();
1789 for (unsigned i = 0; i < numInits; i++) {
1790 // FIXME: Need to get the type of the declaration for C++,
1791 // because it could be a reference?
1792 if (CheckForConstantInitializer(Exp->getInit(i),
1793 Exp->getInit(i)->getType()))
1794 return true;
1795 }
1796 return false;
1797 }
1798
Anders Carlsson9e09f5d2008-12-05 05:09:56 +00001799 // FIXME: We can probably remove some of this code below, now that
1800 // Expr::Evaluate is doing the heavy lifting for scalars.
1801
Eli Friedmanc594b322008-05-20 13:48:25 +00001802 if (Init->isNullPointerConstant(Context))
1803 return false;
1804 if (Init->getType()->isArithmeticType()) {
Chris Lattnerb77792e2008-07-26 22:17:49 +00001805 QualType InitTy = Context.getCanonicalType(Init->getType())
1806 .getUnqualifiedType();
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001807 if (InitTy == Context.BoolTy) {
1808 // Special handling for pointers implicitly cast to bool;
1809 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1810 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1811 Expr* SubE = ICE->getSubExpr();
1812 if (SubE->getType()->isPointerType() ||
1813 SubE->getType()->isArrayType() ||
1814 SubE->getType()->isFunctionType()) {
1815 return CheckAddressConstantExpression(Init);
1816 }
1817 }
1818 } else if (InitTy->isIntegralType()) {
1819 Expr* SubE = 0;
Argyrios Kyrtzidis0835a3c2008-08-18 23:01:59 +00001820 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001821 SubE = CE->getSubExpr();
1822 // Special check for pointer cast to int; we allow as an extension
1823 // an address constant cast to an integer if the integer
1824 // is of an appropriate width (this sort of code is apparently used
1825 // in some places).
1826 // FIXME: Add pedwarn?
1827 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1828 if (SubE && (SubE->getType()->isPointerType() ||
1829 SubE->getType()->isArrayType() ||
1830 SubE->getType()->isFunctionType())) {
1831 unsigned IntWidth = Context.getTypeSize(Init->getType());
1832 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1833 if (IntWidth >= PointerWidth)
1834 return CheckAddressConstantExpression(Init);
1835 }
Eli Friedmanc594b322008-05-20 13:48:25 +00001836 }
1837
1838 return CheckArithmeticConstantExpression(Init);
1839 }
1840
1841 if (Init->getType()->isPointerType())
1842 return CheckAddressConstantExpression(Init);
1843
Eli Friedmanc1cc6dc2008-05-30 18:14:48 +00001844 // An array type at the top level that isn't an init-list must
1845 // be a string literal
Eli Friedmanc594b322008-05-20 13:48:25 +00001846 if (Init->getType()->isArrayType())
1847 return false;
1848
Nuno Lopes73419bf2008-09-01 18:42:41 +00001849 if (Init->getType()->isFunctionType())
1850 return false;
1851
Steve Naroff8af6a452008-10-02 17:12:56 +00001852 // Allow block exprs at top level.
1853 if (Init->getType()->isBlockPointerType())
1854 return false;
1855
Steve Naroff6594a702008-10-27 11:34:16 +00001856 InitializerElementNotConstant(Init);
Eli Friedmanc594b322008-05-20 13:48:25 +00001857 return true;
Steve Naroffd0091aa2008-01-10 22:15:12 +00001858}
1859
Steve Naroffbb204692007-09-12 14:07:44 +00001860void Sema::AddInitializerToDecl(DeclTy *dcl, ExprTy *init) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001861 Decl *RealDecl = static_cast<Decl *>(dcl);
Steve Naroffbb204692007-09-12 14:07:44 +00001862 Expr *Init = static_cast<Expr *>(init);
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001863 assert(Init && "missing initializer");
Steve Naroffbb204692007-09-12 14:07:44 +00001864
Chris Lattner9a11b9a2007-10-19 20:10:30 +00001865 // If there is no declaration, there was an error parsing it. Just ignore
1866 // the initializer.
1867 if (RealDecl == 0) {
1868 delete Init;
1869 return;
1870 }
Steve Naroffbb204692007-09-12 14:07:44 +00001871
Steve Naroff410e3e22007-09-12 20:13:48 +00001872 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
1873 if (!VDecl) {
Steve Naroff8e74c932007-09-13 21:41:19 +00001874 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
1875 diag::err_illegal_initializer);
Steve Naroff410e3e22007-09-12 20:13:48 +00001876 RealDecl->setInvalidDecl();
1877 return;
1878 }
Steve Naroffbb204692007-09-12 14:07:44 +00001879 // Get the decls type and save a reference for later, since
Steve Naroffd0091aa2008-01-10 22:15:12 +00001880 // CheckInitializerTypes may change it.
Steve Naroff410e3e22007-09-12 20:13:48 +00001881 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff248a7532008-04-15 22:42:06 +00001882 if (VDecl->isBlockVarDecl()) {
1883 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroffbb204692007-09-12 14:07:44 +00001884 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff410e3e22007-09-12 20:13:48 +00001885 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001886 VDecl->setInvalidDecl();
1887 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001888 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001889 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001890 VDecl->setInvalidDecl();
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001891
1892 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1893 if (!getLangOptions().CPlusPlus) {
1894 if (SC == VarDecl::Static) // C99 6.7.8p4.
1895 CheckForConstantInitializer(Init, DclT);
1896 }
Steve Naroffbb204692007-09-12 14:07:44 +00001897 }
Steve Naroff248a7532008-04-15 22:42:06 +00001898 } else if (VDecl->isFileVarDecl()) {
1899 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff410e3e22007-09-12 20:13:48 +00001900 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff248a7532008-04-15 22:42:06 +00001901 if (!VDecl->isInvalidDecl())
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001902 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001903 VDecl->getDeclName()))
Steve Naroff248a7532008-04-15 22:42:06 +00001904 VDecl->setInvalidDecl();
Steve Naroffd0091aa2008-01-10 22:15:12 +00001905
Anders Carlssonc5eb7312008-08-22 05:00:02 +00001906 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
1907 if (!getLangOptions().CPlusPlus) {
1908 // C99 6.7.8p4. All file scoped initializers need to be constant.
1909 CheckForConstantInitializer(Init, DclT);
1910 }
Steve Naroffbb204692007-09-12 14:07:44 +00001911 }
1912 // If the type changed, it means we had an incomplete type that was
1913 // completed by the initializer. For example:
1914 // int ary[] = { 1, 3, 5 };
1915 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb48b12392007-11-29 19:09:19 +00001916 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff410e3e22007-09-12 20:13:48 +00001917 VDecl->setType(DclT);
Christopher Lamb48b12392007-11-29 19:09:19 +00001918 Init->setType(DclT);
1919 }
Steve Naroffbb204692007-09-12 14:07:44 +00001920
1921 // Attach the initializer to the decl.
Steve Naroff410e3e22007-09-12 20:13:48 +00001922 VDecl->setInit(Init);
Steve Naroffbb204692007-09-12 14:07:44 +00001923 return;
1924}
1925
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001926void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
1927 Decl *RealDecl = static_cast<Decl *>(dcl);
1928
Argyrios Kyrtzidis48c2e902008-11-07 13:01:22 +00001929 // If there is no declaration, there was an error parsing it. Just ignore it.
1930 if (RealDecl == 0)
1931 return;
1932
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001933 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
1934 QualType Type = Var->getType();
1935 // C++ [dcl.init.ref]p3:
1936 // The initializer can be omitted for a reference only in a
1937 // parameter declaration (8.3.5), in the declaration of a
1938 // function return type, in the declaration of a class member
1939 // within its class declaration (9.2), and where the extern
1940 // specifier is explicitly used.
Douglas Gregor18fe5682008-11-03 20:45:27 +00001941 if (Type->isReferenceType() && Var->getStorageClass() != VarDecl::Extern) {
Chris Lattnerd3a94e22008-11-20 06:06:08 +00001942 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001943 << Var->getDeclName()
1944 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor18fe5682008-11-03 20:45:27 +00001945 Var->setInvalidDecl();
1946 return;
1947 }
1948
1949 // C++ [dcl.init]p9:
1950 //
1951 // If no initializer is specified for an object, and the object
1952 // is of (possibly cv-qualified) non-POD class type (or array
1953 // thereof), the object shall be default-initialized; if the
1954 // object is of const-qualified type, the underlying class type
1955 // shall have a user-declared default constructor.
1956 if (getLangOptions().CPlusPlus) {
1957 QualType InitType = Type;
1958 if (const ArrayType *Array = Context.getAsArrayType(Type))
1959 InitType = Array->getElementType();
1960 if (InitType->isRecordType()) {
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001961 const CXXConstructorDecl *Constructor
1962 = PerformInitializationByConstructor(InitType, 0, 0,
1963 Var->getLocation(),
1964 SourceRange(Var->getLocation(),
1965 Var->getLocation()),
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001966 Var->getDeclName(),
Douglas Gregorf03d7c72008-11-05 15:29:30 +00001967 IK_Default);
Douglas Gregor18fe5682008-11-03 20:45:27 +00001968 if (!Constructor)
1969 Var->setInvalidDecl();
1970 }
1971 }
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001972
Douglas Gregor818ce482008-10-29 13:50:18 +00001973#if 0
1974 // FIXME: Temporarily disabled because we are not properly parsing
1975 // linkage specifications on declarations, e.g.,
1976 //
1977 // extern "C" const CGPoint CGPointerZero;
1978 //
Douglas Gregor27c8dc02008-10-29 00:13:59 +00001979 // C++ [dcl.init]p9:
1980 //
1981 // If no initializer is specified for an object, and the
1982 // object is of (possibly cv-qualified) non-POD class type (or
1983 // array thereof), the object shall be default-initialized; if
1984 // the object is of const-qualified type, the underlying class
1985 // type shall have a user-declared default
1986 // constructor. Otherwise, if no initializer is specified for
1987 // an object, the object and its subobjects, if any, have an
1988 // indeterminate initial value; if the object or any of its
1989 // subobjects are of const-qualified type, the program is
1990 // ill-formed.
1991 //
1992 // This isn't technically an error in C, so we don't diagnose it.
1993 //
1994 // FIXME: Actually perform the POD/user-defined default
1995 // constructor check.
1996 if (getLangOptions().CPlusPlus &&
Douglas Gregor818ce482008-10-29 13:50:18 +00001997 Context.getCanonicalType(Type).isConstQualified() &&
1998 Var->getStorageClass() != VarDecl::Extern)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00001999 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2000 << Var->getName()
2001 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor818ce482008-10-29 13:50:18 +00002002#endif
Douglas Gregor27c8dc02008-10-29 00:13:59 +00002003 }
2004}
2005
Reid Spencer5f016e22007-07-11 17:01:13 +00002006/// The declarators are chained together backwards, reverse the list.
2007Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2008 // Often we have single declarators, handle them quickly.
Steve Naroff94745042007-09-13 23:52:58 +00002009 Decl *GroupDecl = static_cast<Decl*>(group);
2010 if (GroupDecl == 0)
Steve Naroffbb204692007-09-12 14:07:44 +00002011 return 0;
Steve Naroff94745042007-09-13 23:52:58 +00002012
2013 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2014 ScopedDecl *NewGroup = 0;
Steve Naroffbb204692007-09-12 14:07:44 +00002015 if (Group->getNextDeclarator() == 0)
Reid Spencer5f016e22007-07-11 17:01:13 +00002016 NewGroup = Group;
Steve Naroffbb204692007-09-12 14:07:44 +00002017 else { // reverse the list.
2018 while (Group) {
Steve Naroff94745042007-09-13 23:52:58 +00002019 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroffbb204692007-09-12 14:07:44 +00002020 Group->setNextDeclarator(NewGroup);
2021 NewGroup = Group;
2022 Group = Next;
2023 }
2024 }
2025 // Perform semantic analysis that depends on having fully processed both
2026 // the declarator and initializer.
Steve Naroff94745042007-09-13 23:52:58 +00002027 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroffbb204692007-09-12 14:07:44 +00002028 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2029 if (!IDecl)
2030 continue;
Steve Naroffbb204692007-09-12 14:07:44 +00002031 QualType T = IDecl->getType();
2032
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002033 if (T->isVariableArrayType()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002034 const VariableArrayType *VAT =
2035 cast<VariableArrayType>(T.getUnqualifiedType());
2036
2037 // FIXME: This won't give the correct result for
2038 // int a[10][n];
2039 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002040 if (IDecl->isFileVarDecl()) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002041 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2042 SizeRange;
2043
Eli Friedmanc5773c42008-02-15 18:16:39 +00002044 IDecl->setInvalidDecl();
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002045 } else {
2046 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2047 // static storage duration, it shall not have a variable length array.
2048 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002049 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2050 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002051 IDecl->setInvalidDecl();
2052 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlsson7fd1df22008-12-07 00:49:48 +00002053 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2054 << SizeRange;
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002055 IDecl->setInvalidDecl();
2056 }
2057 }
2058 } else if (T->isVariablyModifiedType()) {
2059 if (IDecl->isFileVarDecl()) {
2060 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2061 IDecl->setInvalidDecl();
2062 } else {
2063 if (IDecl->getStorageClass() == VarDecl::Extern) {
2064 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2065 IDecl->setInvalidDecl();
2066 }
Steve Naroffbb204692007-09-12 14:07:44 +00002067 }
2068 }
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002069
Steve Naroffbb204692007-09-12 14:07:44 +00002070 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2071 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff248a7532008-04-15 22:42:06 +00002072 if (IDecl->isBlockVarDecl() &&
2073 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002074 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002075 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002076 IDecl->setInvalidDecl();
2077 }
2078 }
2079 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2080 // object that has file scope without an initializer, and without a
2081 // storage-class specifier or with the storage-class specifier "static",
2082 // constitutes a tentative definition. Note: A tentative definition with
2083 // external linkage is valid (C99 6.2.2p5).
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002084 if (isTentativeDefinition(IDecl)) {
Eli Friedman9db13972008-02-15 12:53:51 +00002085 if (T->isIncompleteArrayType()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002086 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2087 // array to be completed. Don't issue a diagnostic.
Chris Lattnerfd89bc82008-04-02 01:05:10 +00002088 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff9a75f8a2008-01-18 20:40:52 +00002089 // C99 6.9.2p3: If the declaration of an identifier for an object is
2090 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2091 // declared type shall not be an incomplete type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002092 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroffbb204692007-09-12 14:07:44 +00002093 IDecl->setInvalidDecl();
2094 }
2095 }
Steve Naroffff9eb1f2008-08-08 17:50:35 +00002096 if (IDecl->isFileVarDecl())
2097 CheckForFileScopedRedefinitions(S, IDecl);
Reid Spencer5f016e22007-07-11 17:01:13 +00002098 }
2099 return NewGroup;
2100}
Steve Naroffe1223f72007-08-28 03:03:08 +00002101
Chris Lattner04421082008-04-08 04:40:51 +00002102/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2103/// to introduce parameters into function prototype scope.
2104Sema::DeclTy *
2105Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002106 // FIXME: disallow CXXScopeSpec for param declarators.
Chris Lattner985abd92008-06-26 06:49:43 +00002107 const DeclSpec &DS = D.getDeclSpec();
Chris Lattner04421082008-04-08 04:40:51 +00002108
2109 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002110 VarDecl::StorageClass StorageClass = VarDecl::None;
2111 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2112 StorageClass = VarDecl::Register;
2113 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner04421082008-04-08 04:40:51 +00002114 Diag(DS.getStorageClassSpecLoc(),
2115 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002116 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002117 }
2118 if (DS.isThreadSpecified()) {
2119 Diag(DS.getThreadSpecLoc(),
2120 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner985abd92008-06-26 06:49:43 +00002121 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner04421082008-04-08 04:40:51 +00002122 }
2123
Douglas Gregor6d6eb572008-05-07 04:49:29 +00002124 // Check that there are no default arguments inside the type of this
2125 // parameter (C++ only).
2126 if (getLangOptions().CPlusPlus)
2127 CheckExtraCXXDefaultArguments(D);
2128
Chris Lattner04421082008-04-08 04:40:51 +00002129 // In this context, we *do not* check D.getInvalidType(). If the declarator
2130 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2131 // though it will not reflect the user specified type.
2132 QualType parmDeclType = GetTypeForDeclarator(D, S);
2133
2134 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2135
Reid Spencer5f016e22007-07-11 17:01:13 +00002136 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2137 // Can this happen for params? We already checked that they don't conflict
2138 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner04421082008-04-08 04:40:51 +00002139 IdentifierInfo *II = D.getIdentifier();
2140 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregorf57172b2008-12-08 18:40:42 +00002141 if (PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002142 // Maybe we will complain about the shadowed template parameter.
2143 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2144 // Just pretend that we didn't see the previous declaration.
2145 PrevDecl = 0;
2146 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002147 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner04421082008-04-08 04:40:51 +00002148
2149 // Recover by removing the name
2150 II = 0;
2151 D.SetIdentifier(0, D.getIdentifierLoc());
2152 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002153 }
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002154
2155 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2156 // Doing the promotion here has a win and a loss. The win is the type for
2157 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2158 // code generator). The loss is the orginal type isn't preserved. For example:
2159 //
2160 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2161 // int blockvardecl[5];
2162 // sizeof(parmvardecl); // size == 4
2163 // sizeof(blockvardecl); // size == 20
2164 // }
2165 //
2166 // For expressions, all implicit conversions are captured using the
2167 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2168 //
2169 // FIXME: If a source translation tool needs to see the original type, then
2170 // we need to consider storing both types (in ParmVarDecl)...
2171 //
Chris Lattnere6327742008-04-02 05:18:44 +00002172 if (parmDeclType->isArrayType()) {
Chris Lattner529bd022008-01-02 22:50:48 +00002173 // int x[restrict 4] -> int *restrict
Chris Lattnere6327742008-04-02 05:18:44 +00002174 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattner529bd022008-01-02 22:50:48 +00002175 } else if (parmDeclType->isFunctionType())
Steve Naroff6a9f3e32007-08-07 22:44:21 +00002176 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor44b43212008-12-11 16:49:14 +00002177
Chris Lattner04421082008-04-08 04:40:51 +00002178 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2179 D.getIdentifierLoc(), II,
Daniel Dunbar33ad0122008-09-03 21:54:21 +00002180 parmDeclType, StorageClass,
Chris Lattner04421082008-04-08 04:40:51 +00002181 0, 0);
Anders Carlssonf78915f2008-02-15 07:04:12 +00002182
Chris Lattner04421082008-04-08 04:40:51 +00002183 if (D.getInvalidType())
Steve Naroff53a32342007-08-28 18:45:29 +00002184 New->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002185
2186 // Add the parameter declaration into this scope.
2187 S->AddDecl(New);
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002188 if (II)
Douglas Gregor44b43212008-12-11 16:49:14 +00002189 IdResolver.AddDecl(New);
Nate Begemanb7894b52008-02-17 21:20:31 +00002190
Chris Lattner3ff30c82008-06-29 00:02:00 +00002191 ProcessDeclAttributes(New, D);
Reid Spencer5f016e22007-07-11 17:01:13 +00002192 return New;
Chris Lattner04421082008-04-08 04:40:51 +00002193
Reid Spencer5f016e22007-07-11 17:01:13 +00002194}
Fariborz Jahanian306d68f2007-11-08 23:49:49 +00002195
Chris Lattnerb652cea2007-10-09 17:14:05 +00002196Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002197 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Reid Spencer5f016e22007-07-11 17:01:13 +00002198 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2199 "Not a function declarator!");
2200 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner04421082008-04-08 04:40:51 +00002201
Reid Spencer5f016e22007-07-11 17:01:13 +00002202 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2203 // for a K&R function.
2204 if (!FTI.hasPrototype) {
2205 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner04421082008-04-08 04:40:51 +00002206 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002207 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2208 << FTI.ArgInfo[i].Ident;
Reid Spencer5f016e22007-07-11 17:01:13 +00002209 // Implicitly declare the argument as type 'int' for lack of a better
2210 // type.
Chris Lattner04421082008-04-08 04:40:51 +00002211 DeclSpec DS;
2212 const char* PrevSpec; // unused
2213 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2214 PrevSpec);
2215 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2216 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2217 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002218 }
2219 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002220 } else {
Chris Lattner04421082008-04-08 04:40:51 +00002221 // FIXME: Diagnose arguments without names in C.
Reid Spencer5f016e22007-07-11 17:01:13 +00002222 }
2223
2224 Scope *GlobalScope = FnBodyScope->getParent();
Steve Naroffadbbd0c2008-01-14 20:51:29 +00002225
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002226 return ActOnStartOfFunctionDef(FnBodyScope,
Daniel Dunbar914701e2008-08-05 16:28:08 +00002227 ActOnDeclarator(GlobalScope, D, 0));
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002228}
2229
2230Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2231 Decl *decl = static_cast<Decl*>(D);
Chris Lattnere9ba3232008-02-16 01:20:36 +00002232 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002233
2234 // See if this is a redefinition.
2235 const FunctionDecl *Definition;
2236 if (FD->getBody(Definition)) {
Chris Lattner08631c52008-11-23 21:45:46 +00002237 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002238 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor6fc17ff2008-10-29 15:10:40 +00002239 }
2240
Douglas Gregor44b43212008-12-11 16:49:14 +00002241 PushDeclContext(FnBodyScope, FD);
Chris Lattner04421082008-04-08 04:40:51 +00002242
2243 // Check the validity of our function parameters
2244 CheckParmsForFunctionDef(FD);
2245
2246 // Introduce our parameters into the function scope
2247 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2248 ParmVarDecl *Param = FD->getParamDecl(p);
2249 // If this has an identifier, add it to the scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002250 if (Param->getIdentifier())
2251 PushOnScopeChains(Param, FnBodyScope);
Reid Spencer5f016e22007-07-11 17:01:13 +00002252 }
Chris Lattner04421082008-04-08 04:40:51 +00002253
Reid Spencer5f016e22007-07-11 17:01:13 +00002254 return FD;
2255}
2256
Steve Naroffd6d054d2007-11-11 23:20:51 +00002257Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtTy *Body) {
2258 Decl *dcl = static_cast<Decl *>(D);
Steve Naroff394f3f42008-07-25 17:57:26 +00002259 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002260 FD->setBody((Stmt*)Body);
Argyrios Kyrtzidis53d0ea52008-06-28 06:07:14 +00002261 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff394f3f42008-07-25 17:57:26 +00002262 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroffd6d054d2007-11-11 23:20:51 +00002263 MD->setBody((Stmt*)Body);
Steve Naroff394f3f42008-07-25 17:57:26 +00002264 } else
2265 return 0;
Chris Lattnerb048c982008-04-06 04:47:34 +00002266 PopDeclContext();
Reid Spencer5f016e22007-07-11 17:01:13 +00002267 // Verify and clean out per-function state.
2268
2269 // Check goto/label use.
2270 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2271 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2272 // Verify that we have no forward references left. If so, there was a goto
2273 // or address of a label taken, but no definition of it. Label fwd
2274 // definitions are indicated with a null substmt.
2275 if (I->second->getSubStmt() == 0) {
2276 LabelStmt *L = I->second;
2277 // Emit error.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002278 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Reid Spencer5f016e22007-07-11 17:01:13 +00002279
2280 // At this point, we have gotos that use the bogus label. Stitch it into
2281 // the function body so that they aren't leaked and that the AST is well
2282 // formed.
Chris Lattner0cbc2152008-01-25 00:01:10 +00002283 if (Body) {
2284 L->setSubStmt(new NullStmt(L->getIdentLoc()));
2285 cast<CompoundStmt>((Stmt*)Body)->push_back(L);
2286 } else {
2287 // The whole function wasn't parsed correctly, just delete this.
2288 delete L;
2289 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002290 }
2291 }
2292 LabelMap.clear();
2293
Steve Naroffd6d054d2007-11-11 23:20:51 +00002294 return D;
Fariborz Jahanian60fbca02007-11-10 16:31:34 +00002295}
2296
Reid Spencer5f016e22007-07-11 17:01:13 +00002297/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2298/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Naroff8c9f13e2007-09-16 16:16:00 +00002299ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2300 IdentifierInfo &II, Scope *S) {
Chris Lattner37d10842008-05-05 21:18:06 +00002301 // Extension in C99. Legal in C90, but warn about it.
2302 if (getLangOptions().C99)
Chris Lattner3c73c412008-11-19 08:23:25 +00002303 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattner37d10842008-05-05 21:18:06 +00002304 else
Chris Lattner3c73c412008-11-19 08:23:25 +00002305 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Reid Spencer5f016e22007-07-11 17:01:13 +00002306
2307 // FIXME: handle stuff like:
2308 // void foo() { extern float X(); }
2309 // void bar() { X(); } <-- implicit decl for X in another scope.
2310
2311 // Set a Declarator for the implicit definition: int foo();
2312 const char *Dummy;
2313 DeclSpec DS;
2314 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2315 Error = Error; // Silence warning.
2316 assert(!Error && "Error setting up implicit decl!");
2317 Declarator D(DS, Declarator::BlockContext);
Argyrios Kyrtzidis971c4fa2008-10-24 21:46:40 +00002318 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Reid Spencer5f016e22007-07-11 17:01:13 +00002319 D.SetIdentifier(&II, Loc);
2320
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002321 // Insert this function into translation-unit scope.
2322
2323 DeclContext *PrevDC = CurContext;
2324 CurContext = Context.getTranslationUnitDecl();
2325
Steve Naroffe2ef8152008-04-04 14:32:09 +00002326 FunctionDecl *FD =
Daniel Dunbar914701e2008-08-05 16:28:08 +00002327 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroffe2ef8152008-04-04 14:32:09 +00002328 FD->setImplicit();
Argyrios Kyrtzidis93213bb2008-05-01 21:04:16 +00002329
2330 CurContext = PrevDC;
2331
Steve Naroffe2ef8152008-04-04 14:32:09 +00002332 return FD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002333}
2334
2335
Chris Lattner41af0932007-11-14 06:34:38 +00002336TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff94745042007-09-13 23:52:58 +00002337 ScopedDecl *LastDeclarator) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002338 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroff5912a352007-08-28 20:14:24 +00002339 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Reid Spencer5f016e22007-07-11 17:01:13 +00002340
2341 // Scope manipulation handled by caller.
Chris Lattner0ed844b2008-04-04 06:12:32 +00002342 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2343 D.getIdentifierLoc(),
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00002344 D.getIdentifier(),
Chris Lattnerc63e6602008-03-15 21:32:50 +00002345 T, LastDeclarator);
Steve Naroff5912a352007-08-28 20:14:24 +00002346 if (D.getInvalidType())
2347 NewTD->setInvalidDecl();
2348 return NewTD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002349}
2350
Steve Naroff08d92e42007-09-15 18:49:24 +00002351/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Reid Spencer5f016e22007-07-11 17:01:13 +00002352/// former case, Name will be non-null. In the later case, Name will be null.
2353/// TagType indicates what kind of tag this is. TK indicates whether this is a
2354/// reference/declaration/definition of a tag.
Steve Naroff08d92e42007-09-15 18:49:24 +00002355Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argyrios Kyrtzidiseb83ecd2008-11-08 16:45:02 +00002356 SourceLocation KWLoc, const CXXScopeSpec &SS,
2357 IdentifierInfo *Name, SourceLocation NameLoc,
2358 AttributeList *Attr) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002359 // If this is a use of an existing tag, it must have a name.
2360 assert((Name != 0 || TK == TK_Definition) &&
2361 "Nameless record must be a definition!");
2362
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002363 TagDecl::TagKind Kind;
Reid Spencer5f016e22007-07-11 17:01:13 +00002364 switch (TagType) {
2365 default: assert(0 && "Unknown tag type!");
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002366 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2367 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2368 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2369 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Reid Spencer5f016e22007-07-11 17:01:13 +00002370 }
2371
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002372 // Two code paths: a new one for structs/unions/classes where we create
2373 // separate decls for forward declarations, and an old (eventually to
2374 // be removed) code path for enums.
2375 if (Kind != TagDecl::TK_enum)
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002376 return ActOnTagStruct(S, Kind, TK, KWLoc, SS, Name, NameLoc, Attr);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002377
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002378 DeclContext *DC = CurContext;
2379 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002380
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002381 if (Name && SS.isNotEmpty()) {
2382 // We have a nested-name tag ('struct foo::bar').
2383
2384 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002385 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002386 Name = 0;
2387 goto CreateNewDecl;
2388 }
2389
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002390 DC = static_cast<DeclContext*>(SS.getScopeRep());
2391 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002392 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2393
2394 // A tag 'foo::bar' must already exist.
2395 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002396 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002397 Name = 0;
2398 goto CreateNewDecl;
2399 }
2400 } else {
2401 // If this is a named struct, check to see if there was a previous forward
2402 // declaration or definition.
2403 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2404 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2405 }
2406
Douglas Gregorf57172b2008-12-08 18:40:42 +00002407 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002408 // Maybe we will complain about the shadowed template parameter.
2409 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2410 // Just pretend that we didn't see the previous declaration.
2411 PrevDecl = 0;
2412 }
2413
Ted Kremenek7e8cc572008-09-02 21:26:19 +00002414 if (PrevDecl) {
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002415 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2416 "unexpected Decl type");
2417 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002418 // If this is a use of a previous tag, or if the tag is already declared
2419 // in the same scope (so that the definition/declaration completes or
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002420 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002421 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner14943b92008-07-03 03:30:58 +00002422 // Make sure that this wasn't declared as an enum and now used as a
2423 // struct or something similar.
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002424 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002425 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002426 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner14943b92008-07-03 03:30:58 +00002427 // Recover by making this an anonymous redefinition.
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002428 Name = 0;
Chris Lattner14943b92008-07-03 03:30:58 +00002429 PrevDecl = 0;
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002430 } else {
Chris Lattner14943b92008-07-03 03:30:58 +00002431 // If this is a use or a forward declaration, we're good.
2432 if (TK != TK_Definition)
2433 return PrevDecl;
2434
2435 // Diagnose attempts to redefine a tag.
2436 if (PrevTagDecl->isDefinition()) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002437 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002438 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner14943b92008-07-03 03:30:58 +00002439 // If this is a redefinition, recover by making this struct be
2440 // anonymous, which will make any later references get the previous
2441 // definition.
2442 Name = 0;
2443 } else {
2444 // Okay, this is definition of a previously declared or referenced
2445 // tag. Move the location of the decl to be the definition site.
2446 PrevDecl->setLocation(NameLoc);
2447 return PrevDecl;
2448 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002449 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002450 }
Argyrios Kyrtzidis2d1c5d32008-04-27 13:50:30 +00002451 // If we get here, this is a definition of a new struct type in a nested
2452 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a new
2453 // type.
2454 } else {
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002455 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002456 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremeneka89d1972008-09-03 18:03:35 +00002457 // The tag name clashes with a namespace name, issue an error and
2458 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002459 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002460 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argyrios Kyrtzidisb02ef242008-07-16 07:45:46 +00002461 Name = 0;
2462 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002463 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002464 }
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002465
Argyrios Kyrtzidisef6e6472008-11-08 17:17:31 +00002466 CreateNewDecl:
Reid Spencer5f016e22007-07-11 17:01:13 +00002467
2468 // If there is an identifier, use the location of the identifier as the
2469 // location of the decl, otherwise use the location of the struct/union
2470 // keyword.
2471 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2472
2473 // Otherwise, if this is the first time we've seen this tag, create the decl.
2474 TagDecl *New;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002475 if (Kind == TagDecl::TK_enum) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002476 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2477 // enum X { A, B, C } D; D should chain to X.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002478 New = EnumDecl::Create(Context, DC, Loc, Name, 0);
Reid Spencer5f016e22007-07-11 17:01:13 +00002479 // If this is an undefined enum, warn.
2480 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002481 } else {
2482 // struct/union/class
2483
Reid Spencer5f016e22007-07-11 17:01:13 +00002484 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2485 // struct X { int A; } D; D should chain to X.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002486 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002487 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002488 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002489 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002490 New = RecordDecl::Create(Context, Kind, DC, Loc, Name);
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002491 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002492
2493 // If this has an identifier, add it to the scope stack.
2494 if (Name) {
Chris Lattner31e05722007-08-26 06:24:45 +00002495 // The scope passed in may not be a decl scope. Zip up the scope tree until
2496 // we find one that is.
2497 while ((S->getFlags() & Scope::DeclScope) == 0)
2498 S = S->getParent();
2499
2500 // Add it to the decl chain.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00002501 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00002502 }
Chris Lattnere1e79852008-02-06 00:51:33 +00002503
Chris Lattnerf2e4bd52008-06-28 23:58:55 +00002504 if (Attr)
2505 ProcessDeclAttributeList(New, Attr);
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002506
2507 // Set the lexical context. If the tag has a C++ scope specifier, the
2508 // lexical context will be different from the semantic context.
2509 New->setLexicalDeclContext(CurContext);
2510
Reid Spencer5f016e22007-07-11 17:01:13 +00002511 return New;
2512}
2513
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002514/// ActOnTagStruct - New "ActOnTag" logic for structs/unions/classes. Unlike
2515/// the logic for enums, we create separate decls for forward declarations.
2516/// This is called by ActOnTag, but eventually will replace its logic.
2517Sema::DeclTy *Sema::ActOnTagStruct(Scope *S, TagDecl::TagKind Kind, TagKind TK,
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002518 SourceLocation KWLoc, const CXXScopeSpec &SS,
2519 IdentifierInfo *Name, SourceLocation NameLoc,
2520 AttributeList *Attr) {
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002521 DeclContext *DC = CurContext;
2522 ScopedDecl *PrevDecl = 0;
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002523
2524 if (Name && SS.isNotEmpty()) {
2525 // We have a nested-name tag ('struct foo::bar').
2526
2527 // Check for invalid 'foo::'.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002528 if (SS.isInvalid()) {
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002529 Name = 0;
2530 goto CreateNewDecl;
2531 }
2532
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002533 DC = static_cast<DeclContext*>(SS.getScopeRep());
2534 // Look-up name inside 'foo::'.
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002535 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2536
2537 // A tag 'foo::bar' must already exist.
2538 if (PrevDecl == 0) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002539 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002540 Name = 0;
2541 goto CreateNewDecl;
2542 }
2543 } else {
2544 // If this is a named struct, check to see if there was a previous forward
2545 // declaration or definition.
2546 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2547 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2548 }
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002549
Douglas Gregorf57172b2008-12-08 18:40:42 +00002550 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00002551 // Maybe we will complain about the shadowed template parameter.
2552 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2553 // Just pretend that we didn't see the previous declaration.
2554 PrevDecl = 0;
2555 }
2556
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002557 if (PrevDecl) {
2558 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2559 "unexpected Decl type");
2560
2561 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
2562 // If this is a use of a previous tag, or if the tag is already declared
2563 // in the same scope (so that the definition/declaration completes or
2564 // rementions the tag), reuse the decl.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002565 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002566 // Make sure that this wasn't declared as an enum and now used as a
2567 // struct or something similar.
2568 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002569 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002570 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002571 // Recover by making this an anonymous redefinition.
2572 Name = 0;
2573 PrevDecl = 0;
2574 } else {
2575 // If this is a use, return the original decl.
2576
2577 // FIXME: In the future, return a variant or some other clue
2578 // for the consumer of this Decl to know it doesn't own it.
2579 // For our current ASTs this shouldn't be a problem, but will
2580 // need to be changed with DeclGroups.
2581 if (TK == TK_Reference)
2582 return PrevDecl;
2583
2584 // The new decl is a definition?
2585 if (TK == TK_Definition) {
2586 // Diagnose attempts to redefine a tag.
2587 if (RecordDecl* DefRecord =
2588 cast<RecordDecl>(PrevTagDecl)->getDefinition(Context)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002589 Diag(NameLoc, diag::err_redefinition) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002590 Diag(DefRecord->getLocation(), diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002591 // If this is a redefinition, recover by making this struct be
2592 // anonymous, which will make any later references get the previous
2593 // definition.
2594 Name = 0;
2595 PrevDecl = 0;
2596 }
2597 // Okay, this is definition of a previously declared or referenced
2598 // tag. We're going to create a new Decl.
2599 }
2600 }
2601 // If we get here we have (another) forward declaration. Just create
2602 // a new decl.
2603 }
2604 else {
2605 // If we get here, this is a definition of a new struct type in a nested
2606 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2607 // new decl/type. We set PrevDecl to NULL so that the Records
2608 // have distinct types.
2609 PrevDecl = 0;
2610 }
2611 } else {
2612 // PrevDecl is a namespace.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002613 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002614 // The tag name clashes with a namespace name, issue an error and
2615 // recover by making this tag be anonymous.
Chris Lattner3c73c412008-11-19 08:23:25 +00002616 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner5f4a6822008-11-23 23:12:31 +00002617 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002618 Name = 0;
2619 }
2620 }
2621 }
Argyrios Kyrtzidis630c81b2008-11-09 22:09:58 +00002622
2623 CreateNewDecl:
2624
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002625 // If there is an identifier, use the location of the identifier as the
2626 // location of the decl, otherwise use the location of the struct/union
2627 // keyword.
2628 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2629
2630 // Otherwise, if this is the first time we've seen this tag, create the decl.
2631 TagDecl *New;
2632
2633 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2634 // struct X { int A; } D; D should chain to X.
2635 if (getLangOptions().CPlusPlus)
Ted Kremenek2b345eb2008-09-05 17:39:33 +00002636 // FIXME: Look for a way to use RecordDecl for simple structs.
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002637 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002638 dyn_cast_or_null<CXXRecordDecl>(PrevDecl));
2639 else
Argyrios Kyrtzidis0f84a232008-11-09 22:53:32 +00002640 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002641 dyn_cast_or_null<RecordDecl>(PrevDecl));
2642
2643 // If this has an identifier, add it to the scope stack.
2644 if ((TK == TK_Definition || !PrevDecl) && Name) {
2645 // The scope passed in may not be a decl scope. Zip up the scope tree until
2646 // we find one that is.
2647 while ((S->getFlags() & Scope::DeclScope) == 0)
2648 S = S->getParent();
2649
2650 // Add it to the decl chain.
2651 PushOnScopeChains(New, S);
2652 }
Daniel Dunbar3b0db902008-10-16 02:34:03 +00002653
2654 // Handle #pragma pack: if the #pragma pack stack has non-default
2655 // alignment, make up a packed attribute for this decl. These
2656 // attributes are checked when the ASTContext lays out the
2657 // structure.
2658 //
2659 // It is important for implementing the correct semantics that this
2660 // happen here (in act on tag decl). The #pragma pack stack is
2661 // maintained as a result of parser callbacks which can occur at
2662 // many points during the parsing of a struct declaration (because
2663 // the #pragma tokens are effectively skipped over during the
2664 // parsing of the struct).
2665 if (unsigned Alignment = PackContext.getAlignment())
2666 New->addAttr(new PackedAttr(Alignment * 8));
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002667
2668 if (Attr)
2669 ProcessDeclAttributeList(New, Attr);
2670
Argyrios Kyrtzidis52393042008-11-09 23:41:00 +00002671 // Set the lexical context. If the tag has a C++ scope specifier, the
2672 // lexical context will be different from the semantic context.
2673 New->setLexicalDeclContext(CurContext);
2674
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002675 return New;
2676}
2677
2678
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002679/// Collect the instance variables declared in an Objective-C object. Used in
2680/// the creation of structures from objects using the @defs directive.
Douglas Gregor44b43212008-12-11 16:49:14 +00002681static void CollectIvars(ObjCInterfaceDecl *Class, RecordDecl *Record,
2682 ASTContext& Ctx,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002683 llvm::SmallVectorImpl<Sema::DeclTy*> &ivars) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002684 if (Class->getSuperClass())
Douglas Gregor44b43212008-12-11 16:49:14 +00002685 CollectIvars(Class->getSuperClass(), Record, Ctx, ivars);
Ted Kremenek01e67792008-08-20 03:26:33 +00002686
2687 // For each ivar, create a fresh ObjCAtDefsFieldDecl.
Ted Kremeneka89d1972008-09-03 18:03:35 +00002688 for (ObjCInterfaceDecl::ivar_iterator
2689 I=Class->ivar_begin(), E=Class->ivar_end(); I!=E; ++I) {
2690
Ted Kremenek01e67792008-08-20 03:26:33 +00002691 ObjCIvarDecl* ID = *I;
Douglas Gregor44b43212008-12-11 16:49:14 +00002692 ivars.push_back(ObjCAtDefsFieldDecl::Create(Ctx, Record,
2693 ID->getLocation(),
Ted Kremenek01e67792008-08-20 03:26:33 +00002694 ID->getIdentifier(),
2695 ID->getType(),
2696 ID->getBitWidth()));
2697 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002698}
2699
2700/// Called whenever @defs(ClassName) is encountered in the source. Inserts the
2701/// instance variables of ClassName into Decls.
Douglas Gregor44b43212008-12-11 16:49:14 +00002702void Sema::ActOnDefs(Scope *S, DeclTy *TagD, SourceLocation DeclStart,
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002703 IdentifierInfo *ClassName,
Chris Lattner7caeabd2008-07-21 22:17:28 +00002704 llvm::SmallVectorImpl<DeclTy*> &Decls) {
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002705 // Check that ClassName is a valid class
2706 ObjCInterfaceDecl *Class = getObjCInterfaceDecl(ClassName);
2707 if (!Class) {
Chris Lattner3c73c412008-11-19 08:23:25 +00002708 Diag(DeclStart, diag::err_undef_interface) << ClassName;
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002709 return;
2710 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002711 // Collect the instance variables
Douglas Gregor44b43212008-12-11 16:49:14 +00002712 CollectIvars(Class, dyn_cast<RecordDecl>((Decl*)TagD), Context, Decls);
2713
2714 // Introduce all of these fields into the appropriate scope.
2715 for (llvm::SmallVectorImpl<DeclTy*>::iterator D = Decls.begin();
2716 D != Decls.end(); ++D) {
2717 FieldDecl *FD = cast<FieldDecl>((Decl*)*D);
2718 if (getLangOptions().CPlusPlus)
2719 PushOnScopeChains(cast<FieldDecl>(FD), S);
2720 else if (RecordDecl *Record = dyn_cast<RecordDecl>((Decl*)TagD))
2721 Record->addDecl(Context, FD);
2722 }
Chris Lattner5a6ddbf2008-06-21 19:39:06 +00002723}
2724
Chris Lattner1d353ba2008-11-12 21:17:48 +00002725/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2726/// types into constant array types in certain situations which would otherwise
2727/// be errors (for GCC compatibility).
2728static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2729 ASTContext &Context) {
Eli Friedman1b76ada2008-06-03 21:01:11 +00002730 // This method tries to turn a variable array into a constant
2731 // array even when the size isn't an ICE. This is necessary
2732 // for compatibility with code that depends on gcc's buggy
2733 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattner57d57882008-11-12 19:48:13 +00002734 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2735 if (!VLATy) return QualType();
2736
2737 APValue Result;
2738 if (!VLATy->getSizeExpr() ||
Chris Lattner6ee7aa12008-11-16 21:24:15 +00002739 !VLATy->getSizeExpr()->Evaluate(Result, Context))
Chris Lattner57d57882008-11-12 19:48:13 +00002740 return QualType();
2741
2742 assert(Result.isInt() && "Size expressions must be integers!");
2743 llvm::APSInt &Res = Result.getInt();
2744 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2745 return Context.getConstantArrayType(VLATy->getElementType(),
2746 Res, ArrayType::Normal, 0);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002747 return QualType();
2748}
2749
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002750bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattnercd087072008-12-12 04:56:04 +00002751 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002752 // FIXME: 6.7.2.1p4 - verify the field type.
2753
2754 llvm::APSInt Value;
2755 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2756 return true;
2757
Chris Lattnercd087072008-12-12 04:56:04 +00002758 // Zero-width bitfield is ok for anonymous field.
2759 if (Value == 0 && FieldName)
2760 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2761
2762 if (Value.isNegative())
2763 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002764
2765 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2766 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattnercd087072008-12-12 04:56:04 +00002767 if (TypeSize && Value.getZExtValue() > TypeSize)
2768 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2769 << FieldName << (unsigned)TypeSize;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002770
2771 return false;
2772}
2773
Steve Naroff08d92e42007-09-15 18:49:24 +00002774/// ActOnField - Each field of a struct/union/class is passed into this in order
Reid Spencer5f016e22007-07-11 17:01:13 +00002775/// to create a FieldDecl object for it.
Douglas Gregor44b43212008-12-11 16:49:14 +00002776Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Reid Spencer5f016e22007-07-11 17:01:13 +00002777 SourceLocation DeclStart,
2778 Declarator &D, ExprTy *BitfieldWidth) {
2779 IdentifierInfo *II = D.getIdentifier();
2780 Expr *BitWidth = (Expr*)BitfieldWidth;
Reid Spencer5f016e22007-07-11 17:01:13 +00002781 SourceLocation Loc = DeclStart;
Douglas Gregor44b43212008-12-11 16:49:14 +00002782 RecordDecl *Record = (RecordDecl *)TagD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002783 if (II) Loc = D.getIdentifierLoc();
2784
2785 // FIXME: Unnamed fields can be handled in various different ways, for
2786 // example, unnamed unions inject all members into the struct namespace!
Reid Spencer5f016e22007-07-11 17:01:13 +00002787
Reid Spencer5f016e22007-07-11 17:01:13 +00002788 QualType T = GetTypeForDeclarator(D, S);
Steve Naroff5912a352007-08-28 20:14:24 +00002789 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2790 bool InvalidDecl = false;
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002791
Reid Spencer5f016e22007-07-11 17:01:13 +00002792 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2793 // than a variably modified type.
Eli Friedman9db13972008-02-15 12:53:51 +00002794 if (T->isVariablyModifiedType()) {
Chris Lattner1d353ba2008-11-12 21:17:48 +00002795 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002796 if (!FixedTy.isNull()) {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002797 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman1b76ada2008-06-03 21:01:11 +00002798 T = FixedTy;
2799 } else {
Chris Lattner23cd0d92008-11-13 18:49:38 +00002800 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner3ab55432008-11-12 19:45:49 +00002801 T = Context.IntTy;
Eli Friedman1b76ada2008-06-03 21:01:11 +00002802 InvalidDecl = true;
2803 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002804 }
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002805
2806 if (BitWidth) {
2807 if (VerifyBitField(Loc, II, T, BitWidth))
2808 InvalidDecl = true;
2809 } else {
2810 // Not a bitfield.
2811
2812 // validate II.
2813
2814 }
2815
Reid Spencer5f016e22007-07-11 17:01:13 +00002816 // FIXME: Chain fielddecls together.
Argyrios Kyrtzidis07952322008-07-01 10:37:29 +00002817 FieldDecl *NewFD;
2818
Douglas Gregor44b43212008-12-11 16:49:14 +00002819 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2820 // other way to determine the current RecordDecl.
2821 NewFD = FieldDecl::Create(Context, Record,
2822 Loc, II, T, BitWidth,
2823 D.getDeclSpec().getStorageClassSpec() ==
2824 DeclSpec::SCS_mutable,
2825 /*PrevDecl=*/0);
2826
Chris Lattner3ff30c82008-06-29 00:02:00 +00002827 ProcessDeclAttributes(NewFD, D);
Anders Carlssonad148062008-02-16 00:29:18 +00002828
Steve Naroff5912a352007-08-28 20:14:24 +00002829 if (D.getInvalidType() || InvalidDecl)
2830 NewFD->setInvalidDecl();
Douglas Gregor44b43212008-12-11 16:49:14 +00002831
2832 if (II && getLangOptions().CPlusPlus)
2833 PushOnScopeChains(NewFD, S);
2834 else
2835 Record->addDecl(Context, NewFD);
2836
Steve Naroff5912a352007-08-28 20:14:24 +00002837 return NewFD;
Reid Spencer5f016e22007-07-11 17:01:13 +00002838}
2839
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002840/// TranslateIvarVisibility - Translate visibility from a token ID to an
2841/// AST enum value.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002842static ObjCIvarDecl::AccessControl
Fariborz Jahanian89204a12007-10-01 16:53:59 +00002843TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Narofff13271f2007-09-14 23:09:53 +00002844 switch (ivarVisibility) {
Chris Lattner33d34a62008-10-12 00:28:42 +00002845 default: assert(0 && "Unknown visitibility kind");
2846 case tok::objc_private: return ObjCIvarDecl::Private;
2847 case tok::objc_public: return ObjCIvarDecl::Public;
2848 case tok::objc_protected: return ObjCIvarDecl::Protected;
2849 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Narofff13271f2007-09-14 23:09:53 +00002850 }
2851}
2852
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002853/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2854/// in order to create an IvarDecl object for it.
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002855Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian45bc03f2008-04-11 16:55:42 +00002856 SourceLocation DeclStart,
2857 Declarator &D, ExprTy *BitfieldWidth,
2858 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002859 IdentifierInfo *II = D.getIdentifier();
2860 Expr *BitWidth = (Expr*)BitfieldWidth;
2861 SourceLocation Loc = DeclStart;
2862 if (II) Loc = D.getIdentifierLoc();
2863
2864 // FIXME: Unnamed fields can be handled in various different ways, for
2865 // example, unnamed unions inject all members into the struct namespace!
2866
Anders Carlsson9f1e5722008-12-06 20:33:04 +00002867 QualType T = GetTypeForDeclarator(D, S);
2868 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2869 bool InvalidDecl = false;
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002870
2871 if (BitWidth) {
2872 // TODO: Validate.
2873 //printf("WARNING: BITFIELDS IGNORED!\n");
2874
2875 // 6.7.2.1p3
2876 // 6.7.2.1p4
2877
2878 } else {
2879 // Not a bitfield.
2880
2881 // validate II.
2882
2883 }
2884
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002885 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2886 // than a variably modified type.
2887 if (T->isVariablyModifiedType()) {
Anders Carlsson96e05bc2008-12-07 00:20:55 +00002888 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002889 InvalidDecl = true;
2890 }
2891
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002892 // Get the visibility (access control) for this ivar.
2893 ObjCIvarDecl::AccessControl ac =
2894 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2895 : ObjCIvarDecl::None;
2896
2897 // Construct the decl.
2898 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroff8f3b2652008-07-16 18:22:22 +00002899 (Expr *)BitfieldWidth);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002900
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002901 // Process attributes attached to the ivar.
Chris Lattner3ff30c82008-06-29 00:02:00 +00002902 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002903
2904 if (D.getInvalidType() || InvalidDecl)
2905 NewID->setInvalidDecl();
Ted Kremenekb8db21d2008-07-23 18:04:17 +00002906
Fariborz Jahanian1d78cc42008-04-10 23:32:45 +00002907 return NewID;
2908}
2909
Fariborz Jahanian9d048ff2007-09-29 00:54:24 +00002910void Sema::ActOnFields(Scope* S,
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002911 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff08d92e42007-09-15 18:49:24 +00002912 DeclTy **Fields, unsigned NumFields,
Daniel Dunbar1bfe1c22008-10-03 02:03:53 +00002913 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar7d076642008-10-03 17:33:35 +00002914 AttributeList *Attr) {
Steve Naroff74216642007-09-14 22:20:54 +00002915 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2916 assert(EnclosingDecl && "missing record or interface decl");
2917 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2918
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002919 if (Record)
2920 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2921 // Diagnose code like:
2922 // struct S { struct S {} X; };
2923 // We discover this when we complete the outer S. Reject and ignore the
2924 // outer S.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002925 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002926 << DefRecord->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00002927 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek4b7c9832008-09-05 17:16:31 +00002928 Record->setInvalidDecl();
2929 return;
2930 }
2931
Reid Spencer5f016e22007-07-11 17:01:13 +00002932 // Verify that all the fields are okay.
2933 unsigned NumNamedMembers = 0;
2934 llvm::SmallVector<FieldDecl*, 32> RecFields;
2935 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff74216642007-09-14 22:20:54 +00002936
Reid Spencer5f016e22007-07-11 17:01:13 +00002937 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002938
Steve Naroff74216642007-09-14 22:20:54 +00002939 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2940 assert(FD && "missing field decl");
2941
2942 // Remember all fields.
2943 RecFields.push_back(FD);
Reid Spencer5f016e22007-07-11 17:01:13 +00002944
2945 // Get the type for the field.
Chris Lattner02c642e2007-07-31 21:33:24 +00002946 Type *FDTy = FD->getType().getTypePtr();
Steve Narofff13271f2007-09-14 23:09:53 +00002947
Reid Spencer5f016e22007-07-11 17:01:13 +00002948 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner02c642e2007-07-31 21:33:24 +00002949 if (FDTy->isFunctionType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002950 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002951 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002952 FD->setInvalidDecl();
2953 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002954 continue;
2955 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002956 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2957 if (FDTy->isIncompleteType()) {
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002958 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002959 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002960 FD->setInvalidDecl();
2961 EnclosingDecl->setInvalidDecl();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00002962 continue;
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002963 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002964 if (i != NumFields-1 || // ... that the last member ...
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002965 !Record->isStruct() || // ... of a structure ...
Chris Lattner02c642e2007-07-31 21:33:24 +00002966 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002967 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002968 FD->setInvalidDecl();
2969 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002970 continue;
2971 }
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002972 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002973 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002974 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002975 FD->setInvalidDecl();
2976 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002977 continue;
2978 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002979 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00002980 if (Record)
2981 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00002982 }
Reid Spencer5f016e22007-07-11 17:01:13 +00002983 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2984 /// field of another structure or the element of an array.
Chris Lattner02c642e2007-07-31 21:33:24 +00002985 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002986 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2987 // If this is a member of a union, then entire union becomes "flexible".
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002988 if (Record && Record->isUnion()) {
Reid Spencer5f016e22007-07-11 17:01:13 +00002989 Record->setHasFlexibleArrayMember(true);
2990 } else {
2991 // If this is a struct/class and this is not the last element, reject
2992 // it. Note that GCC supports variable sized arrays in the middle of
2993 // structures.
2994 if (i != NumFields-1) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00002995 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002996 << FD->getDeclName();
Steve Naroff74216642007-09-14 22:20:54 +00002997 FD->setInvalidDecl();
2998 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00002999 continue;
3000 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003001 // We support flexible arrays at the end of structs in other structs
3002 // as an extension.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003003 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003004 << FD->getDeclName();
Fariborz Jahanian3f5faf72007-10-04 00:45:27 +00003005 if (Record)
Fariborz Jahaniane267ab62007-09-14 16:27:55 +00003006 Record->setHasFlexibleArrayMember(true);
Reid Spencer5f016e22007-07-11 17:01:13 +00003007 }
3008 }
3009 }
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003010 /// A field cannot be an Objective-c object
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003011 if (FDTy->isObjCInterfaceType()) {
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003012 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattner08631c52008-11-23 21:45:46 +00003013 << FD->getDeclName();
Fariborz Jahaniane7f64cc2007-10-12 22:10:42 +00003014 FD->setInvalidDecl();
3015 EnclosingDecl->setInvalidDecl();
3016 continue;
3017 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003018 // Keep track of the number of named members.
3019 if (IdentifierInfo *II = FD->getIdentifier()) {
3020 // Detect duplicate member names.
3021 if (!FieldIDs.insert(II)) {
Chris Lattner3c73c412008-11-19 08:23:25 +00003022 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Reid Spencer5f016e22007-07-11 17:01:13 +00003023 // Find the previous decl.
3024 SourceLocation PrevLoc;
Chris Lattner33d34a62008-10-12 00:28:42 +00003025 for (unsigned i = 0; ; ++i) {
3026 assert(i != RecFields.size() && "Didn't find previous def!");
Reid Spencer5f016e22007-07-11 17:01:13 +00003027 if (RecFields[i]->getIdentifier() == II) {
3028 PrevLoc = RecFields[i]->getLocation();
3029 break;
3030 }
3031 }
Chris Lattner5f4a6822008-11-23 23:12:31 +00003032 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff74216642007-09-14 22:20:54 +00003033 FD->setInvalidDecl();
3034 EnclosingDecl->setInvalidDecl();
Reid Spencer5f016e22007-07-11 17:01:13 +00003035 continue;
3036 }
3037 ++NumNamedMembers;
3038 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003039 }
3040
Reid Spencer5f016e22007-07-11 17:01:13 +00003041 // Okay, we successfully defined 'Record'.
Chris Lattnere1e79852008-02-06 00:51:33 +00003042 if (Record) {
Douglas Gregor44b43212008-12-11 16:49:14 +00003043 Record->completeDefinition(Context);
Argyrios Kyrtzidisa4755c62008-08-09 00:58:37 +00003044 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3045 // Sema::ActOnFinishCXXClassDef.
3046 if (!isa<CXXRecordDecl>(Record))
3047 Consumer.HandleTagDeclDefinition(Record);
Chris Lattnere1e79852008-02-06 00:51:33 +00003048 } else {
Chris Lattnera91d3812008-02-05 22:40:55 +00003049 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
3050 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl))
3051 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
3052 else if (ObjCImplementationDecl *IMPDecl =
3053 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003054 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3055 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian3a3ca1b2007-10-31 18:48:14 +00003056 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand0b90bf2007-09-26 18:27:25 +00003057 }
Fariborz Jahanianb04a0212007-09-14 21:08:27 +00003058 }
Daniel Dunbar7d076642008-10-03 17:33:35 +00003059
3060 if (Attr)
3061 ProcessDeclAttributeList(Record, Attr);
Reid Spencer5f016e22007-07-11 17:01:13 +00003062}
3063
Steve Naroff08d92e42007-09-15 18:49:24 +00003064Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Reid Spencer5f016e22007-07-11 17:01:13 +00003065 DeclTy *lastEnumConst,
3066 SourceLocation IdLoc, IdentifierInfo *Id,
3067 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattner0ed844b2008-04-04 06:12:32 +00003068 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Reid Spencer5f016e22007-07-11 17:01:13 +00003069 EnumConstantDecl *LastEnumConst =
3070 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3071 Expr *Val = static_cast<Expr*>(val);
3072
Chris Lattner31e05722007-08-26 06:24:45 +00003073 // The scope passed in may not be a decl scope. Zip up the scope tree until
3074 // we find one that is.
3075 while ((S->getFlags() & Scope::DeclScope) == 0)
3076 S = S->getParent();
3077
Reid Spencer5f016e22007-07-11 17:01:13 +00003078 // Verify that there isn't already something declared with this name in this
3079 // scope.
Douglas Gregor72c3f312008-12-05 18:15:24 +00003080 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregorf57172b2008-12-08 18:40:42 +00003081 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregor72c3f312008-12-05 18:15:24 +00003082 // Maybe we will complain about the shadowed template parameter.
3083 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3084 // Just pretend that we didn't see the previous declaration.
3085 PrevDecl = 0;
3086 }
3087
3088 if (PrevDecl) {
Argyrios Kyrtzidis0ff12f02008-07-16 21:01:53 +00003089 // When in C++, we may get a TagDecl with the same name; in this case the
3090 // enum constant will 'hide' the tag.
3091 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3092 "Received TagDecl when not in C++!");
Argyrios Kyrtzidis15a12d02008-09-09 21:18:04 +00003093 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Reid Spencer5f016e22007-07-11 17:01:13 +00003094 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner3c73c412008-11-19 08:23:25 +00003095 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Reid Spencer5f016e22007-07-11 17:01:13 +00003096 else
Chris Lattner3c73c412008-11-19 08:23:25 +00003097 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner5f4a6822008-11-23 23:12:31 +00003098 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattnera73349d2008-02-26 00:33:57 +00003099 delete Val;
Reid Spencer5f016e22007-07-11 17:01:13 +00003100 return 0;
3101 }
3102 }
3103
3104 llvm::APSInt EnumVal(32);
3105 QualType EltTy;
3106 if (Val) {
Chris Lattner421a23d2007-08-27 21:16:18 +00003107 // Make sure to promote the operand type to int.
3108 UsualUnaryConversions(Val);
3109
Reid Spencer5f016e22007-07-11 17:01:13 +00003110 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3111 SourceLocation ExpLoc;
Anders Carlsson49184b22008-12-05 16:33:57 +00003112 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattnera73349d2008-02-26 00:33:57 +00003113 delete Val;
Chris Lattnerb7416f92007-08-27 17:37:24 +00003114 Val = 0; // Just forget about it.
Chris Lattnere9ca8512007-08-29 16:03:41 +00003115 } else {
3116 EltTy = Val->getType();
Reid Spencer5f016e22007-07-11 17:01:13 +00003117 }
Chris Lattnerb7416f92007-08-27 17:37:24 +00003118 }
3119
3120 if (!Val) {
3121 if (LastEnumConst) {
3122 // Assign the last value + 1.
3123 EnumVal = LastEnumConst->getInitVal();
3124 ++EnumVal;
Chris Lattner421a23d2007-08-27 21:16:18 +00003125
3126 // Check for overflow on increment.
3127 if (EnumVal < LastEnumConst->getInitVal())
3128 Diag(IdLoc, diag::warn_enum_value_overflow);
3129
Chris Lattnerb7416f92007-08-27 17:37:24 +00003130 EltTy = LastEnumConst->getType();
3131 } else {
3132 // First value, set to zero.
3133 EltTy = Context.IntTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003134 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnerb7416f92007-08-27 17:37:24 +00003135 }
Reid Spencer5f016e22007-07-11 17:01:13 +00003136 }
3137
Chris Lattner6c2b6eb2008-03-15 06:12:44 +00003138 EnumConstantDecl *New =
Chris Lattner0ed844b2008-04-04 06:12:32 +00003139 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3140 Val, EnumVal,
Chris Lattnerc63e6602008-03-15 21:32:50 +00003141 LastEnumConst);
Reid Spencer5f016e22007-07-11 17:01:13 +00003142
3143 // Register this decl in the current scope stack.
Argyrios Kyrtzidis87f3ff02008-04-12 00:47:19 +00003144 PushOnScopeChains(New, S);
Reid Spencer5f016e22007-07-11 17:01:13 +00003145 return New;
3146}
3147
Steve Naroff02408c62008-08-07 14:08:16 +00003148// FIXME: For consistency with ActOnFields(), we should have the parser
3149// pass in the source location for the left/right braces.
Steve Naroff08d92e42007-09-15 18:49:24 +00003150void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Reid Spencer5f016e22007-07-11 17:01:13 +00003151 DeclTy **Elements, unsigned NumElements) {
3152 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Reid Spencer5f016e22007-07-11 17:01:13 +00003153
Steve Naroff02408c62008-08-07 14:08:16 +00003154 if (Enum && Enum->isDefinition()) {
3155 // Diagnose code like:
3156 // enum e0 {
3157 // E0 = sizeof(enum e0 { E1 })
3158 // };
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003159 Diag(Enum->getLocation(), diag::err_nested_redefinition)
3160 << Enum->getDeclName();
Chris Lattner5f4a6822008-11-23 23:12:31 +00003161 Diag(EnumLoc, diag::note_previous_definition);
Steve Naroff02408c62008-08-07 14:08:16 +00003162 Enum->setInvalidDecl();
3163 return;
3164 }
Chris Lattnere37f0be2007-08-28 05:10:31 +00003165 // TODO: If the result value doesn't fit in an int, it must be a long or long
3166 // long value. ISO C does not support this, but GCC does as an extension,
3167 // emit a warning.
Chris Lattner98be4942008-03-05 18:54:05 +00003168 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattnere37f0be2007-08-28 05:10:31 +00003169
Chris Lattnerac609682007-08-28 06:15:15 +00003170 // Verify that all the values are okay, compute the size of the values, and
3171 // reverse the list.
3172 unsigned NumNegativeBits = 0;
3173 unsigned NumPositiveBits = 0;
3174
3175 // Keep track of whether all elements have type int.
3176 bool AllElementsInt = true;
3177
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003178 QualType EnumType = Context.getTypeDeclType(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003179 EnumConstantDecl *EltList = 0;
3180 for (unsigned i = 0; i != NumElements; ++i) {
3181 EnumConstantDecl *ECD =
3182 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3183 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattner211a30e2007-08-28 05:27:00 +00003184
3185 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattner211a30e2007-08-28 05:27:00 +00003186 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattnera73349d2008-02-26 00:33:57 +00003187 assert(InitVal.getBitWidth() >= IntWidth &&
3188 "Should have promoted value to int");
Chris Lattner211a30e2007-08-28 05:27:00 +00003189 if (InitVal.getBitWidth() > IntWidth) {
3190 llvm::APSInt V(InitVal);
3191 V.trunc(IntWidth);
3192 V.extend(InitVal.getBitWidth());
3193 if (V != InitVal)
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003194 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3195 << InitVal.toString(10);
Chris Lattner211a30e2007-08-28 05:27:00 +00003196 }
Chris Lattnerac609682007-08-28 06:15:15 +00003197
3198 // Keep track of the size of positive and negative values.
Chris Lattnera73349d2008-02-26 00:33:57 +00003199 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattner21dd8212008-01-14 21:47:29 +00003200 NumPositiveBits = std::max(NumPositiveBits,
3201 (unsigned)InitVal.getActiveBits());
Chris Lattnerac609682007-08-28 06:15:15 +00003202 else
Chris Lattner21dd8212008-01-14 21:47:29 +00003203 NumNegativeBits = std::max(NumNegativeBits,
3204 (unsigned)InitVal.getMinSignedBits());
Reid Spencer5f016e22007-07-11 17:01:13 +00003205
Chris Lattnerac609682007-08-28 06:15:15 +00003206 // Keep track of whether every enum element has type int (very commmon).
3207 if (AllElementsInt)
3208 AllElementsInt = ECD->getType() == Context.IntTy;
3209
Reid Spencer5f016e22007-07-11 17:01:13 +00003210 ECD->setNextDeclarator(EltList);
3211 EltList = ECD;
3212 }
3213
Chris Lattnerac609682007-08-28 06:15:15 +00003214 // Figure out the type that should be used for this enum.
3215 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3216 QualType BestType;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003217 unsigned BestWidth;
Chris Lattnerac609682007-08-28 06:15:15 +00003218
3219 if (NumNegativeBits) {
3220 // If there is a negative value, figure out the smallest integer type (of
3221 // int/long/longlong) that fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003222 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003223 BestType = Context.IntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003224 BestWidth = IntWidth;
3225 } else {
Chris Lattner98be4942008-03-05 18:54:05 +00003226 BestWidth = Context.Target.getLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003227
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003228 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003229 BestType = Context.LongTy;
3230 else {
Chris Lattner98be4942008-03-05 18:54:05 +00003231 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenek9c728dc2007-12-12 22:39:36 +00003232
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003233 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattnerac609682007-08-28 06:15:15 +00003234 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3235 BestType = Context.LongLongTy;
3236 }
3237 }
3238 } else {
3239 // If there is no negative value, figure out which of uint, ulong, ulonglong
3240 // fits.
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003241 if (NumPositiveBits <= IntWidth) {
Chris Lattnerac609682007-08-28 06:15:15 +00003242 BestType = Context.UnsignedIntTy;
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003243 BestWidth = IntWidth;
3244 } else if (NumPositiveBits <=
Chris Lattner98be4942008-03-05 18:54:05 +00003245 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattnerac609682007-08-28 06:15:15 +00003246 BestType = Context.UnsignedLongTy;
Chris Lattner98be4942008-03-05 18:54:05 +00003247 } else {
3248 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003249 assert(NumPositiveBits <= BestWidth &&
Chris Lattnerac609682007-08-28 06:15:15 +00003250 "How could an initializer get larger than ULL?");
3251 BestType = Context.UnsignedLongLongTy;
3252 }
3253 }
3254
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003255 // Loop over all of the enumerator constants, changing their types to match
3256 // the type of the enum if needed.
3257 for (unsigned i = 0; i != NumElements; ++i) {
3258 EnumConstantDecl *ECD =
3259 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3260 if (!ECD) continue; // Already issued a diagnostic.
3261
3262 // Standard C says the enumerators have int type, but we allow, as an
3263 // extension, the enumerators to be larger than int size. If each
3264 // enumerator value fits in an int, type it as an int, otherwise type it the
3265 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3266 // that X has type 'int', not 'unsigned'.
Chris Lattnera73349d2008-02-26 00:33:57 +00003267 if (ECD->getType() == Context.IntTy) {
3268 // Make sure the init value is signed.
3269 llvm::APSInt IV = ECD->getInitVal();
3270 IV.setIsSigned(true);
3271 ECD->setInitVal(IV);
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003272
3273 if (getLangOptions().CPlusPlus)
3274 // C++ [dcl.enum]p4: Following the closing brace of an
3275 // enum-specifier, each enumerator has the type of its
3276 // enumeration.
3277 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003278 continue; // Already int type.
Chris Lattnera73349d2008-02-26 00:33:57 +00003279 }
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003280
3281 // Determine whether the value fits into an int.
3282 llvm::APSInt InitVal = ECD->getInitVal();
3283 bool FitsInInt;
3284 if (InitVal.isUnsigned() || !InitVal.isNegative())
3285 FitsInInt = InitVal.getActiveBits() < IntWidth;
3286 else
3287 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3288
3289 // If it fits into an integer type, force it. Otherwise force it to match
3290 // the enum decl type.
3291 QualType NewTy;
3292 unsigned NewWidth;
3293 bool NewSign;
3294 if (FitsInInt) {
3295 NewTy = Context.IntTy;
3296 NewWidth = IntWidth;
3297 NewSign = true;
3298 } else if (ECD->getType() == BestType) {
3299 // Already the right type!
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003300 if (getLangOptions().CPlusPlus)
3301 // C++ [dcl.enum]p4: Following the closing brace of an
3302 // enum-specifier, each enumerator has the type of its
3303 // enumeration.
3304 ECD->setType(EnumType);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003305 continue;
3306 } else {
3307 NewTy = BestType;
3308 NewWidth = BestWidth;
3309 NewSign = BestType->isSignedIntegerType();
3310 }
3311
3312 // Adjust the APSInt value.
3313 InitVal.extOrTrunc(NewWidth);
3314 InitVal.setIsSigned(NewSign);
3315 ECD->setInitVal(InitVal);
3316
3317 // Adjust the Expr initializer and type.
Douglas Gregoreb8f3062008-11-12 17:17:38 +00003318 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3319 /*isLvalue=*/false));
Douglas Gregorc9467cf2008-12-12 02:00:36 +00003320 if (getLangOptions().CPlusPlus)
3321 // C++ [dcl.enum]p4: Following the closing brace of an
3322 // enum-specifier, each enumerator has the type of its
3323 // enumeration.
3324 ECD->setType(EnumType);
3325 else
3326 ECD->setType(NewTy);
Chris Lattnerb7f6e082007-08-29 17:31:48 +00003327 }
Chris Lattnerac609682007-08-28 06:15:15 +00003328
Douglas Gregor44b43212008-12-11 16:49:14 +00003329 Enum->completeDefinition(Context, BestType);
Chris Lattnere1e79852008-02-06 00:51:33 +00003330 Consumer.HandleTagDeclDefinition(Enum);
Reid Spencer5f016e22007-07-11 17:01:13 +00003331}
3332
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003333Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
3334 ExprTy *expr) {
3335 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr);
3336
Chris Lattner8e25d862008-03-16 00:16:02 +00003337 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlssondfab6cb2008-02-08 00:33:21 +00003338}
3339
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003340Sema::DeclTy* Sema::ActOnLinkageSpec(SourceLocation Loc,
Chris Lattnerc81c8142008-02-25 21:04:36 +00003341 SourceLocation LBrace,
3342 SourceLocation RBrace,
3343 const char *Lang,
3344 unsigned StrSize,
3345 DeclTy *D) {
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003346 LinkageSpecDecl::LanguageIDs Language;
3347 Decl *dcl = static_cast<Decl *>(D);
3348 if (strncmp(Lang, "\"C\"", StrSize) == 0)
3349 Language = LinkageSpecDecl::lang_c;
3350 else if (strncmp(Lang, "\"C++\"", StrSize) == 0)
3351 Language = LinkageSpecDecl::lang_cxx;
3352 else {
3353 Diag(Loc, diag::err_bad_language);
3354 return 0;
3355 }
3356
3357 // FIXME: Add all the various semantics of linkage specifications
Chris Lattner8e25d862008-03-16 00:16:02 +00003358 return LinkageSpecDecl::Create(Context, Loc, Language, dcl);
Chris Lattnerc6fdc342008-01-12 07:05:38 +00003359}
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003360
3361void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3362 ExprTy *alignment, SourceLocation PragmaLoc,
3363 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3364 Expr *Alignment = static_cast<Expr *>(alignment);
3365
3366 // If specified then alignment must be a "small" power of two.
3367 unsigned AlignmentVal = 0;
3368 if (Alignment) {
3369 llvm::APSInt Val;
3370 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3371 !Val.isPowerOf2() ||
3372 Val.getZExtValue() > 16) {
3373 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3374 delete Alignment;
3375 return; // Ignore
3376 }
3377
3378 AlignmentVal = (unsigned) Val.getZExtValue();
3379 }
3380
3381 switch (Kind) {
3382 case Action::PPK_Default: // pack([n])
3383 PackContext.setAlignment(AlignmentVal);
3384 break;
3385
3386 case Action::PPK_Show: // pack(show)
3387 // Show the current alignment, making sure to show the right value
3388 // for the default.
3389 AlignmentVal = PackContext.getAlignment();
3390 // FIXME: This should come from the target.
3391 if (AlignmentVal == 0)
3392 AlignmentVal = 8;
Chris Lattner83652232008-11-19 07:25:44 +00003393 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003394 break;
3395
3396 case Action::PPK_Push: // pack(push [, id] [, [n])
3397 PackContext.push(Name);
3398 // Set the new alignment if specified.
3399 if (Alignment)
3400 PackContext.setAlignment(AlignmentVal);
3401 break;
3402
3403 case Action::PPK_Pop: // pack(pop [, id] [, n])
3404 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3405 // "#pragma pack(pop, identifier, n) is undefined"
3406 if (Alignment && Name)
3407 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3408
3409 // Do the pop.
3410 if (!PackContext.pop(Name)) {
3411 // If a name was specified then failure indicates the name
3412 // wasn't found. Otherwise failure indicates the stack was
3413 // empty.
Chris Lattnerf3a41af2008-11-20 06:38:18 +00003414 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3415 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003416
3417 // FIXME: Warn about popping named records as MSVC does.
3418 } else {
3419 // Pop succeeded, set the new alignment if specified.
3420 if (Alignment)
3421 PackContext.setAlignment(AlignmentVal);
3422 }
3423 break;
3424
3425 default:
3426 assert(0 && "Invalid #pragma pack kind.");
3427 }
3428}
3429
3430bool PragmaPackStack::pop(IdentifierInfo *Name) {
3431 if (Stack.empty())
3432 return false;
3433
3434 // If name is empty just pop top.
3435 if (!Name) {
3436 Alignment = Stack.back().first;
3437 Stack.pop_back();
3438 return true;
3439 }
3440
3441 // Otherwise, find the named record.
3442 for (unsigned i = Stack.size(); i != 0; ) {
3443 --i;
Daniel Dunbar06550392008-11-19 10:32:38 +00003444 if (Stack[i].second == Name) {
Daniel Dunbar4cde9272008-10-14 05:35:18 +00003445 // Found it, pop up to and including this record.
3446 Alignment = Stack[i].first;
3447 Stack.erase(Stack.begin() + i, Stack.end());
3448 return true;
3449 }
3450 }
3451
3452 return false;
3453}