blob: 86af21024b636cfd0cde473181cfe8849cb53021 [file] [log] [blame]
Chris Lattner4b009652007-07-25 00:24:17 +00001//===--- SemaDecl.cpp - Semantic Analysis for Declarations ----------------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner959e5be2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner4b009652007-07-25 00:24:17 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements semantic analysis for declarations.
11//
12//===----------------------------------------------------------------------===//
13
14#include "Sema.h"
Anders Carlssonc7436af2008-07-03 04:20:39 +000015#include "clang/AST/APValue.h"
Chris Lattner33aad6e2008-02-06 00:51:33 +000016#include "clang/AST/ASTConsumer.h"
Chris Lattner4b009652007-07-25 00:24:17 +000017#include "clang/AST/ASTContext.h"
Daniel Dunbar64789f82008-08-11 05:35:13 +000018#include "clang/AST/DeclObjC.h"
Chris Lattner6953a072008-06-26 18:38:35 +000019#include "clang/AST/ExprCXX.h"
Chris Lattner4b009652007-07-25 00:24:17 +000020#include "clang/Parse/DeclSpec.h"
Daniel Dunbarcc7b1602008-08-11 03:45:03 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner4b009652007-07-25 00:24:17 +000022#include "clang/Basic/TargetInfo.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000023#include "clang/Basic/SourceManager.h"
24// FIXME: layering (ideally, Sema shouldn't be dependent on Lex API's)
Chris Lattner33aad6e2008-02-06 00:51:33 +000025#include "clang/Lex/Preprocessor.h"
Steve Naroffa9eae582008-01-30 23:46:05 +000026#include "clang/Lex/HeaderSearch.h"
Chris Lattner4b009652007-07-25 00:24:17 +000027#include "llvm/ADT/SmallSet.h"
Douglas Gregor39677622008-12-11 20:41:00 +000028#include "llvm/ADT/STLExtras.h"
29
Chris Lattner4b009652007-07-25 00:24:17 +000030using namespace clang;
31
Douglas Gregorb0212bd2008-11-17 20:34:05 +000032Sema::TypeTy *Sema::isTypeName(IdentifierInfo &II, Scope *S,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +000033 const CXXScopeSpec *SS) {
Argiris Kirtzidis054a2632008-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 Naroff6384a012008-04-02 14:35:35 +000041
Douglas Gregor1d661552008-04-13 21:07:44 +000042 if (IIDecl && (isa<TypedefDecl>(IIDecl) ||
43 isa<ObjCInterfaceDecl>(IIDecl) ||
Douglas Gregordd861062008-12-05 18:15:24 +000044 isa<TagDecl>(IIDecl) ||
45 isa<TemplateTypeParmDecl>(IIDecl)))
Fariborz Jahanian23f968b2007-10-12 16:34:10 +000046 return IIDecl;
Steve Naroff81f1bba2007-09-06 21:24:23 +000047 return 0;
Chris Lattner4b009652007-07-25 00:24:17 +000048}
49
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000050DeclContext *Sema::getContainingDC(DeclContext *DC) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000051 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000052 // A C++ out-of-line method will return to the file declaration context.
Argiris Kirtzidis881964b2008-11-09 23:41:00 +000053 if (MD->isOutOfLineDefinition())
54 return MD->getLexicalDeclContext();
Argiris Kirtzidis054a2632008-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
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000059 // the topmost (non-nested) class it is lexically declared in.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000060 assert(isa<CXXRecordDecl>(MD->getParent()) && "C++ method not in Record.");
61 DC = MD->getParent();
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000062 while (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC->getLexicalParent()))
Argiris Kirtzidis38f16712008-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
Argiris Kirtzidis881964b2008-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();
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000075
Argiris Kirtzidis9cd599b2008-11-19 18:01:13 +000076 return DC->getLexicalParent();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +000077}
78
Douglas Gregor8acb7272008-12-11 16:49:14 +000079void Sema::PushDeclContext(Scope *S, DeclContext *DC) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000080 assert(getContainingDC(DC) == CurContext &&
Zhongxing Xu2c9b8102008-12-08 07:14:51 +000081 "The next DeclContext should be lexically contained in the current one.");
Chris Lattneref87a202008-04-22 18:39:57 +000082 CurContext = DC;
Douglas Gregor8acb7272008-12-11 16:49:14 +000083 S->setEntity(DC);
Chris Lattnereee57c02008-04-04 06:12:32 +000084}
85
Chris Lattnerf3874bc2008-04-06 04:47:34 +000086void Sema::PopDeclContext() {
87 assert(CurContext && "DeclContext imbalance!");
Douglas Gregor8acb7272008-12-11 16:49:14 +000088
Argiris Kirtzidis054a2632008-11-08 17:17:31 +000089 CurContext = getContainingDC(CurContext);
Chris Lattnereee57c02008-04-04 06:12:32 +000090}
91
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000092/// Add this decl to the scope shadowed decl chains.
93void Sema::PushOnScopeChains(NamedDecl *D, Scope *S) {
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +000094 S->AddDecl(D);
Argiris Kirtzidis59a9afb2008-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 Gregor8acb7272008-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);
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000115
Douglas Gregor8acb7272008-12-11 16:49:14 +0000116 // Add this declaration to the current context.
117 CurContext->addDecl(Context, TD);
118
119 return;
120 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000121 }
Argiris Kirtzidis81a5feb2008-10-22 23:08:24 +0000122 } else if (getLangOptions().CPlusPlus && isa<FunctionDecl>(D)) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000123 // We are pushing the name of a function, which might be an
124 // overloaded name.
Douglas Gregor8acb7272008-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 Gregord2baafd2008-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 Gregorb0212bd2008-11-17 20:34:05 +0000138 FD->getDeclName());
Douglas Gregor39677622008-12-11 20:41:00 +0000139 Ovl->addOverload(cast<FunctionDecl>(Prev));
Douglas Gregord2baafd2008-10-21 16:13:35 +0000140
Douglas Gregorb9213832008-12-15 21:24:18 +0000141 // If there is a name binding for the existing FunctionDecl,
142 // remove it.
143 for (IdentifierResolver::iterator I
144 = IdResolver.begin(FD->getDeclName(), FD->getDeclContext(),
145 false/*LookInParentCtx*/),
146 E = IdResolver.end(); I != E; ++I) {
147 if (*I == Prev) {
148 IdResolver.RemoveDecl(*I);
149 S->RemoveDecl(*I);
150 break;
151 }
152 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000153
Douglas Gregorb9213832008-12-15 21:24:18 +0000154 // Add the name binding for the OverloadedFunctionDecl.
Douglas Gregord2baafd2008-10-21 16:13:35 +0000155 IdResolver.AddDecl(Ovl);
Douglas Gregor8acb7272008-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 Gregord2baafd2008-10-21 16:13:35 +0000162 }
163
Douglas Gregor8acb7272008-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 Gregord2baafd2008-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 Gregor8acb7272008-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 Gregord2baafd2008-10-21 16:13:35 +0000177 }
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000178 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000179
Douglas Gregor39677622008-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 Gregor8acb7272008-12-11 16:49:14 +0000183 if (ScopedDecl *SD = dyn_cast<ScopedDecl>(D))
184 CurContext->addDecl(Context, SD);
Douglas Gregor8acb7272008-12-11 16:49:14 +0000185
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000186 IdResolver.AddDecl(D);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +0000187}
188
Steve Naroff9637a9b2007-10-09 22:01:59 +0000189void Sema::ActOnPopScope(SourceLocation Loc, Scope *S) {
Chris Lattnera7549902007-08-26 06:24:45 +0000190 if (S->decl_empty()) return;
Douglas Gregordd861062008-12-05 18:15:24 +0000191 assert((S->getFlags() & (Scope::DeclScope | Scope::TemplateParamScope)) &&
192 "Scope shouldn't contain decls!");
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000193
Chris Lattner4b009652007-07-25 00:24:17 +0000194 for (Scope::decl_iterator I = S->decl_begin(), E = S->decl_end();
195 I != E; ++I) {
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000196 Decl *TmpD = static_cast<Decl*>(*I);
197 assert(TmpD && "This decl didn't get pushed??");
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000198
Douglas Gregor8acb7272008-12-11 16:49:14 +0000199 assert(isa<NamedDecl>(TmpD) && "Decl isn't NamedDecl?");
200 NamedDecl *D = cast<NamedDecl>(TmpD);
Argiris Kirtzidisa5c14b22008-06-10 01:32:09 +0000201
Douglas Gregor8acb7272008-12-11 16:49:14 +0000202 if (!D->getDeclName()) continue;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000203
Douglas Gregor8acb7272008-12-11 16:49:14 +0000204 // Remove this name from our lexical scope.
205 IdResolver.RemoveDecl(D);
Chris Lattner4b009652007-07-25 00:24:17 +0000206 }
207}
208
Steve Naroffe57c21a2008-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 Naroffe57c21a2008-04-01 23:04:06 +0000211ObjCInterfaceDecl *Sema::getObjCInterfaceDecl(IdentifierInfo *Id) {
Steve Naroff15208162008-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 Jahaniandc36dc12007-10-12 19:38:20 +0000215
Steve Naroff6384a012008-04-02 14:35:35 +0000216 return dyn_cast_or_null<ObjCInterfaceDecl>(IDecl);
Fariborz Jahaniandc36dc12007-10-12 19:38:20 +0000217}
218
Steve Naroffe57c21a2008-04-01 23:04:06 +0000219/// LookupDecl - Look up the inner-most declaration in the specified
Chris Lattner4b009652007-07-25 00:24:17 +0000220/// namespace.
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000221Decl *Sema::LookupDecl(DeclarationName Name, unsigned NSI, Scope *S,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000222 const DeclContext *LookupCtx,
Douglas Gregor8acb7272008-12-11 16:49:14 +0000223 bool enableLazyBuiltinCreation,
Douglas Gregor24effa82008-12-16 00:38:16 +0000224 bool LookInParent) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000225 if (!Name) return 0;
Douglas Gregor1d661552008-04-13 21:07:44 +0000226 unsigned NS = NSI;
227 if (getLangOptions().CPlusPlus && (NS & Decl::IDNS_Ordinary))
228 NS |= Decl::IDNS_Tag;
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000229
Douglas Gregor39677622008-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 Gregor8acb7272008-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 Gregor39677622008-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 Gregor8acb7272008-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 Gregor39677622008-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 Gregor8acb7272008-12-11 16:49:14 +0000280 // FIXME: Cache this result in the IdResolver
Douglas Gregor39677622008-12-11 20:41:00 +0000281 if ((*I)->getIdentifierNamespace() & NS)
282 return *I;
Douglas Gregor8acb7272008-12-11 16:49:14 +0000283 }
284
285 Ctx = Ctx->getParent();
286 }
287
288 if (!LookInParent)
289 return 0;
290 }
Douglas Gregor8acb7272008-12-11 16:49:14 +0000291 }
Chris Lattner2a1e2ed2008-04-11 07:00:53 +0000292
Chris Lattner4b009652007-07-25 00:24:17 +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 Gregor1d661552008-04-13 21:07:44 +0000296 if (NS & Decl::IDNS_Ordinary) {
Douglas Gregorb0212bd2008-11-17 20:34:05 +0000297 IdentifierInfo *II = Name.getAsIdentifierInfo();
298 if (enableLazyBuiltinCreation && II &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000299 (LookupCtx == 0 || isa<TranslationUnitDecl>(LookupCtx))) {
Steve Naroff6384a012008-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 Gregorb0212bd2008-11-17 20:34:05 +0000304 if (getLangOptions().ObjC1 && II) {
Steve Naroffe57c21a2008-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 Naroff64334ea2008-04-02 00:39:51 +0000307 // therefore not scoped decls). They can, however, be shadowed by
Steve Naroffe57c21a2008-04-01 23:04:06 +0000308 // other names in IDNS_Ordinary.
Steve Naroff15208162008-04-02 18:30:49 +0000309 ObjCInterfaceDeclsTy::iterator IDI = ObjCInterfaceDecls.find(II);
310 if (IDI != ObjCInterfaceDecls.end())
311 return IDI->second;
Steve Naroffe57c21a2008-04-01 23:04:06 +0000312 ObjCAliasTy::iterator I = ObjCAliasDecls.find(II);
313 if (I != ObjCAliasDecls.end())
314 return I->second->getClassInterface();
315 }
Chris Lattner4b009652007-07-25 00:24:17 +0000316 }
317 return 0;
318}
319
Chris Lattnera9c87f22008-05-05 22:18:14 +0000320void Sema::InitBuiltinVaListType() {
Anders Carlsson36760332007-10-15 20:28:48 +0000321 if (!Context.getBuiltinVaListType().isNull())
322 return;
323
324 IdentifierInfo *VaIdent = &Context.Idents.get("__builtin_va_list");
Steve Naroff6384a012008-04-02 14:35:35 +0000325 Decl *VaDecl = LookupDecl(VaIdent, Decl::IDNS_Ordinary, TUScope);
Steve Naroffbc8c52e2007-10-18 22:17:45 +0000326 TypedefDecl *VaTypedef = cast<TypedefDecl>(VaDecl);
Anders Carlsson36760332007-10-15 20:28:48 +0000327 Context.setBuiltinVaListType(Context.getTypedefType(VaTypedef));
328}
329
Chris Lattner4b009652007-07-25 00:24:17 +0000330/// LazilyCreateBuiltin - The specified Builtin-ID was first used at file scope.
331/// lazily create a decl for it.
Chris Lattner71c01112007-10-10 23:42:28 +0000332ScopedDecl *Sema::LazilyCreateBuiltin(IdentifierInfo *II, unsigned bid,
333 Scope *S) {
Chris Lattner4b009652007-07-25 00:24:17 +0000334 Builtin::ID BID = (Builtin::ID)bid;
335
Chris Lattnerb23469f2008-09-28 05:54:29 +0000336 if (Context.BuiltinInfo.hasVAListUse(BID))
Anders Carlsson36760332007-10-15 20:28:48 +0000337 InitBuiltinVaListType();
338
Anders Carlssonfb5b1e82007-10-11 01:00:40 +0000339 QualType R = Context.BuiltinInfo.GetBuiltinType(BID, Context);
Argiris Kirtzidis9d0d8bf2008-04-17 14:47:13 +0000340 FunctionDecl *New = FunctionDecl::Create(Context,
341 Context.getTranslationUnitDecl(),
Chris Lattnereee57c02008-04-04 06:12:32 +0000342 SourceLocation(), II, R,
Chris Lattner4c7802b2008-03-15 21:24:04 +0000343 FunctionDecl::Extern, false, 0);
Chris Lattner4b009652007-07-25 00:24:17 +0000344
Chris Lattnera9c87f22008-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 Lattner2a1e2ed2008-04-11 07:00:53 +0000358 // TUScope is the translation-unit scope to insert this function into.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +0000359 PushOnScopeChains(New, TUScope);
Chris Lattner4b009652007-07-25 00:24:17 +0000360 return New;
361}
362
Sebastian Redlb93b49c2008-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 Lattnerf0939602008-11-20 05:45:14 +0000367 IdentifierInfo *StdIdent = &PP.getIdentifierTable().get("std");
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000368 DeclContext *Global = Context.getTranslationUnitDecl();
Chris Lattnerf0939602008-11-20 05:45:14 +0000369 Decl *Std = LookupDecl(StdIdent, Decl::IDNS_Tag | Decl::IDNS_Ordinary,
Sebastian Redlb93b49c2008-11-11 11:37:55 +0000370 0, Global, /*enableLazyBuiltinCreation=*/false);
371 StdNamespace = dyn_cast_or_null<NamespaceDecl>(Std);
372 }
373 return StdNamespace;
374}
375
Chris Lattner4b009652007-07-25 00:24:17 +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 Naroffe57c21a2008-04-01 23:04:06 +0000380TypedefDecl *Sema::MergeTypeDefDecl(TypedefDecl *New, Decl *OldD) {
Steve Naroff453a8782008-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 Lattner6d16b052008-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 Naroff453a8782008-09-09 14:32:20 +0000390 Context.setObjCIdType(New);
391 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000392 case 5:
393 if (!TypeID->isStr("Class"))
394 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000395 Context.setObjCClassType(New);
396 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000397 case 3:
398 if (!TypeID->isStr("SEL"))
399 break;
Steve Naroff453a8782008-09-09 14:32:20 +0000400 Context.setObjCSelType(New);
401 return New;
Chris Lattner6d16b052008-11-20 05:41:43 +0000402 case 8:
403 if (!TypeID->isStr("Protocol"))
404 break;
Steve Naroff453a8782008-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 }
Chris Lattner4b009652007-07-25 00:24:17 +0000410 // Verify the old decl was also a typedef.
411 TypedefDecl *Old = dyn_cast<TypedefDecl>(OldD);
412 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000413 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000414 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000415 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000416 return New;
417 }
418
Chris Lattnerbef8d622008-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 Lattner8d756812008-11-20 06:13:02 +0000424 Diag(New->getLocation(), diag::err_redefinition_different_typedef)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000425 << New->getUnderlyingType() << Old->getUnderlyingType();
Chris Lattner1336cab2008-11-23 23:12:31 +0000426 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattnerbef8d622008-07-25 18:44:27 +0000427 return Old;
428 }
429
Eli Friedman324d5032008-06-11 06:20:39 +0000430 if (getLangOptions().Microsoft) return New;
431
Douglas Gregor49ba1b72008-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 Naroffa9eae582008-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 Dunbar4dbd8572008-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 Friedman324d5032008-06-11 06:20:39 +0000451
Chris Lattnerb1753422008-11-23 21:45:46 +0000452 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000453 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000454 return New;
455}
456
Chris Lattner6953a072008-06-26 18:38:35 +0000457/// DeclhasAttr - returns true if decl Declaration already has the target
458/// attribute.
Chris Lattner402b3372008-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 Lattner402b3372008-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 Lopes77654342008-06-01 22:53:53 +0000482
483 Old->invalidateAttrs();
Chris Lattner402b3372008-03-03 03:28:21 +0000484}
485
Chris Lattner3e254fb2008-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 Gregord2baafd2008-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 Gregor42214c52008-04-21 02:02:58 +0000496FunctionDecl *
497Sema::MergeFunctionDecl(FunctionDecl *New, Decl *OldD, bool &Redeclaration) {
Douglas Gregord2baafd2008-10-21 16:13:35 +0000498 assert(!isa<OverloadedFunctionDecl>(OldD) &&
499 "Cannot merge with an overloaded function declaration");
500
Douglas Gregor42214c52008-04-21 02:02:58 +0000501 Redeclaration = false;
Chris Lattner4b009652007-07-25 00:24:17 +0000502 // Verify the old decl was also a function.
503 FunctionDecl *Old = dyn_cast<FunctionDecl>(OldD);
504 if (!Old) {
Chris Lattner8d756812008-11-20 06:13:02 +0000505 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000506 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000507 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000508 return New;
509 }
Douglas Gregord2baafd2008-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 Lattner1336cab2008-11-23 23:12:31 +0000515 PrevDiag = diag::note_previous_definition;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000516 else if (Old->isImplicit())
Chris Lattner1336cab2008-11-23 23:12:31 +0000517 PrevDiag = diag::note_previous_implicit_declaration;
Douglas Gregord2baafd2008-10-21 16:13:35 +0000518 else
Chris Lattner1336cab2008-11-23 23:12:31 +0000519 PrevDiag = diag::note_previous_declaration;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000520
Chris Lattner42a21742008-04-06 23:10:54 +0000521 QualType OldQType = Context.getCanonicalType(Old->getType());
522 QualType NewQType = Context.getCanonicalType(New->getType());
Chris Lattner60476ff2007-11-20 19:04:50 +0000523
Douglas Gregord2baafd2008-10-21 16:13:35 +0000524 if (getLangOptions().CPlusPlus) {
525 // (C++98 13.1p2):
526 // Certain function declarations cannot be overloaded:
527 // -- Function declarations that differ only in the return type
528 // cannot be overloaded.
529 QualType OldReturnType
530 = cast<FunctionType>(OldQType.getTypePtr())->getResultType();
531 QualType NewReturnType
532 = cast<FunctionType>(NewQType.getTypePtr())->getResultType();
533 if (OldReturnType != NewReturnType) {
534 Diag(New->getLocation(), diag::err_ovl_diff_return_type);
535 Diag(Old->getLocation(), PrevDiag);
536 return New;
537 }
538
539 const CXXMethodDecl* OldMethod = dyn_cast<CXXMethodDecl>(Old);
540 const CXXMethodDecl* NewMethod = dyn_cast<CXXMethodDecl>(New);
541 if (OldMethod && NewMethod) {
542 // -- Member function declarations with the same name and the
543 // same parameter types cannot be overloaded if any of them
544 // is a static member function declaration.
545 if (OldMethod->isStatic() || NewMethod->isStatic()) {
546 Diag(New->getLocation(), diag::err_ovl_static_nonstatic_member);
547 Diag(Old->getLocation(), PrevDiag);
548 return New;
549 }
Douglas Gregorb9213832008-12-15 21:24:18 +0000550
551 // C++ [class.mem]p1:
552 // [...] A member shall not be declared twice in the
553 // member-specification, except that a nested class or member
554 // class template can be declared and then later defined.
555 if (OldMethod->getLexicalDeclContext() ==
556 NewMethod->getLexicalDeclContext()) {
557 unsigned NewDiag;
558 if (isa<CXXConstructorDecl>(OldMethod))
559 NewDiag = diag::err_constructor_redeclared;
560 else if (isa<CXXDestructorDecl>(NewMethod))
561 NewDiag = diag::err_destructor_redeclared;
562 else if (isa<CXXConversionDecl>(NewMethod))
563 NewDiag = diag::err_conv_function_redeclared;
564 else
565 NewDiag = diag::err_member_redeclared;
566
567 Diag(New->getLocation(), NewDiag);
568 Diag(Old->getLocation(), PrevDiag);
569 }
Douglas Gregord2baafd2008-10-21 16:13:35 +0000570 }
571
572 // (C++98 8.3.5p3):
573 // All declarations for a function shall agree exactly in both the
574 // return type and the parameter-type-list.
575 if (OldQType == NewQType) {
576 // We have a redeclaration.
577 MergeAttributes(New, Old);
578 Redeclaration = true;
579 return MergeCXXFunctionDecl(New, Old);
580 }
581
582 // Fall through for conflicting redeclarations and redefinitions.
Douglas Gregor42214c52008-04-21 02:02:58 +0000583 }
Chris Lattner3e254fb2008-04-08 04:40:51 +0000584
585 // C: Function types need to be compatible, not identical. This handles
Steve Naroff1d5bd642008-01-14 20:51:29 +0000586 // duplicate function decls like "void f(int); void f(enum X);" properly.
Chris Lattner3e254fb2008-04-08 04:40:51 +0000587 if (!getLangOptions().CPlusPlus &&
Eli Friedman0d9549b2008-08-22 00:56:42 +0000588 Context.typesAreCompatible(OldQType, NewQType)) {
Douglas Gregor42214c52008-04-21 02:02:58 +0000589 MergeAttributes(New, Old);
590 Redeclaration = true;
Steve Naroff1d5bd642008-01-14 20:51:29 +0000591 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +0000592 }
Chris Lattner1470b072007-11-06 06:07:26 +0000593
Steve Naroff6c9e7922008-01-16 15:01:34 +0000594 // A function that has already been declared has been redeclared or defined
595 // with a different type- show appropriate diagnostic
Steve Naroff6c9e7922008-01-16 15:01:34 +0000596
Chris Lattner4b009652007-07-25 00:24:17 +0000597 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
598 // TODO: This is totally simplistic. It should handle merging functions
599 // together etc, merging extern int X; int X; ...
Chris Lattner271d4c22008-11-24 05:29:24 +0000600 Diag(New->getLocation(), diag::err_conflicting_types) << New->getDeclName();
Steve Naroff6c9e7922008-01-16 15:01:34 +0000601 Diag(Old->getLocation(), PrevDiag);
Chris Lattner4b009652007-07-25 00:24:17 +0000602 return New;
603}
604
Steve Naroffb5e78152008-08-08 17:50:35 +0000605/// Predicate for C "tentative" external object definitions (C99 6.9.2).
Steve Naroffd5802092008-08-10 15:28:06 +0000606static bool isTentativeDefinition(VarDecl *VD) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000607 if (VD->isFileVarDecl())
608 return (!VD->getInit() &&
609 (VD->getStorageClass() == VarDecl::None ||
610 VD->getStorageClass() == VarDecl::Static));
611 return false;
612}
613
614/// CheckForFileScopedRedefinitions - Make sure we forgo redefinition errors
615/// when dealing with C "tentative" external object definitions (C99 6.9.2).
616void Sema::CheckForFileScopedRedefinitions(Scope *S, VarDecl *VD) {
617 bool VDIsTentative = isTentativeDefinition(VD);
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000618 bool VDIsIncompleteArray = VD->getType()->isIncompleteArrayType();
Steve Naroffb5e78152008-08-08 17:50:35 +0000619
620 for (IdentifierResolver::iterator
621 I = IdResolver.begin(VD->getIdentifier(),
622 VD->getDeclContext(), false/*LookInParentCtx*/),
623 E = IdResolver.end(); I != E; ++I) {
Argiris Kirtzidis90842b62008-09-09 21:18:04 +0000624 if (*I != VD && isDeclInScope(*I, VD->getDeclContext(), S)) {
Steve Naroffb5e78152008-08-08 17:50:35 +0000625 VarDecl *OldDecl = dyn_cast<VarDecl>(*I);
626
Steve Naroff4b6bd3c2008-08-10 15:20:13 +0000627 // Handle the following case:
628 // int a[10];
629 // int a[]; - the code below makes sure we set the correct type.
630 // int a[11]; - this is an error, size isn't 10.
631 if (OldDecl && VDIsTentative && VDIsIncompleteArray &&
632 OldDecl->getType()->isConstantArrayType())
633 VD->setType(OldDecl->getType());
634
Steve Naroffb5e78152008-08-08 17:50:35 +0000635 // Check for "tentative" definitions. We can't accomplish this in
636 // MergeVarDecl since the initializer hasn't been attached.
637 if (!OldDecl || isTentativeDefinition(OldDecl) || VDIsTentative)
638 continue;
639
640 // Handle __private_extern__ just like extern.
641 if (OldDecl->getStorageClass() != VarDecl::Extern &&
642 OldDecl->getStorageClass() != VarDecl::PrivateExtern &&
643 VD->getStorageClass() != VarDecl::Extern &&
644 VD->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000645 Diag(VD->getLocation(), diag::err_redefinition) << VD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000646 Diag(OldDecl->getLocation(), diag::note_previous_definition);
Steve Naroffb5e78152008-08-08 17:50:35 +0000647 }
648 }
649 }
650}
651
Chris Lattner4b009652007-07-25 00:24:17 +0000652/// MergeVarDecl - We just parsed a variable 'New' which has the same name
653/// and scope as a previous declaration 'Old'. Figure out how to resolve this
654/// situation, merging decls or emitting diagnostics as appropriate.
655///
Steve Naroffb5e78152008-08-08 17:50:35 +0000656/// Tentative definition rules (C99 6.9.2p2) are checked by
657/// FinalizeDeclaratorGroup. Unfortunately, we can't analyze tentative
658/// definitions here, since the initializer hasn't been attached.
Chris Lattner4b009652007-07-25 00:24:17 +0000659///
Steve Naroffe57c21a2008-04-01 23:04:06 +0000660VarDecl *Sema::MergeVarDecl(VarDecl *New, Decl *OldD) {
Chris Lattner4b009652007-07-25 00:24:17 +0000661 // Verify the old decl was also a variable.
662 VarDecl *Old = dyn_cast<VarDecl>(OldD);
663 if (!Old) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000664 Diag(New->getLocation(), diag::err_redefinition_different_kind)
Chris Lattnerb1753422008-11-23 21:45:46 +0000665 << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000666 Diag(OldD->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000667 return New;
668 }
Chris Lattner402b3372008-03-03 03:28:21 +0000669
670 MergeAttributes(New, Old);
671
Chris Lattner4b009652007-07-25 00:24:17 +0000672 // Verify the types match.
Chris Lattner42a21742008-04-06 23:10:54 +0000673 QualType OldCType = Context.getCanonicalType(Old->getType());
674 QualType NewCType = Context.getCanonicalType(New->getType());
Steve Naroff12508172008-08-09 16:04:40 +0000675 if (OldCType != NewCType && !Context.typesAreCompatible(OldCType, NewCType)) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000676 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000677 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000678 return New;
679 }
Steve Naroffb00247f2008-01-30 00:44:01 +0000680 // C99 6.2.2p4: Check if we have a static decl followed by a non-static.
681 if (New->getStorageClass() == VarDecl::Static &&
682 (Old->getStorageClass() == VarDecl::None ||
683 Old->getStorageClass() == VarDecl::Extern)) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000684 Diag(New->getLocation(), diag::err_static_non_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000685 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000686 return New;
687 }
688 // C99 6.2.2p4: Check if we have a non-static decl followed by a static.
689 if (New->getStorageClass() != VarDecl::Static &&
690 Old->getStorageClass() == VarDecl::Static) {
Chris Lattner271d4c22008-11-24 05:29:24 +0000691 Diag(New->getLocation(), diag::err_non_static_static) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000692 Diag(Old->getLocation(), diag::note_previous_definition);
Steve Naroffb00247f2008-01-30 00:44:01 +0000693 return New;
694 }
Steve Naroff2f3c4432008-09-17 14:05:40 +0000695 // Variables with external linkage are analyzed in FinalizeDeclaratorGroup.
696 if (New->getStorageClass() != VarDecl::Extern && !New->isFileVarDecl()) {
Chris Lattnerb1753422008-11-23 21:45:46 +0000697 Diag(New->getLocation(), diag::err_redefinition) << New->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +0000698 Diag(Old->getLocation(), diag::note_previous_definition);
Chris Lattner4b009652007-07-25 00:24:17 +0000699 }
700 return New;
701}
702
Chris Lattner3e254fb2008-04-08 04:40:51 +0000703/// CheckParmsForFunctionDef - Check that the parameters of the given
704/// function are appropriate for the definition of a function. This
705/// takes care of any checks that cannot be performed on the
706/// declaration itself, e.g., that the types of each of the function
707/// parameters are complete.
708bool Sema::CheckParmsForFunctionDef(FunctionDecl *FD) {
709 bool HasInvalidParm = false;
710 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
711 ParmVarDecl *Param = FD->getParamDecl(p);
712
713 // C99 6.7.5.3p4: the parameters in a parameter type list in a
714 // function declarator that is part of a function definition of
715 // that function shall not have incomplete type.
716 if (Param->getType()->isIncompleteType() &&
717 !Param->isInvalidDecl()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +0000718 Diag(Param->getLocation(), diag::err_typecheck_decl_incomplete_type)
Chris Lattner271d4c22008-11-24 05:29:24 +0000719 << Param->getType();
Chris Lattner3e254fb2008-04-08 04:40:51 +0000720 Param->setInvalidDecl();
721 HasInvalidParm = true;
722 }
Chris Lattnerb0b42f62008-12-17 07:32:46 +0000723
724 // C99 6.9.1p5: If the declarator includes a parameter type list, the
725 // declaration of each parameter shall include an identifier.
726 if (Param->getIdentifier() == 0 && !getLangOptions().CPlusPlus)
727 Diag(Param->getLocation(), diag::err_parameter_name_omitted);
Chris Lattner3e254fb2008-04-08 04:40:51 +0000728 }
729
730 return HasInvalidParm;
731}
732
Chris Lattner4b009652007-07-25 00:24:17 +0000733/// ParsedFreeStandingDeclSpec - This method is invoked when a declspec with
734/// no declarator (e.g. "struct foo;") is parsed.
735Sema::DeclTy *Sema::ParsedFreeStandingDeclSpec(Scope *S, DeclSpec &DS) {
736 // TODO: emit error on 'int;' or 'const enum foo;'.
737 // TODO: emit error on 'typedef int;'
738 // if (!DS.isMissingDeclaratorOk()) Diag(...);
739
Steve Naroffedafc0b2007-11-17 21:37:36 +0000740 return dyn_cast_or_null<TagDecl>(static_cast<Decl *>(DS.getTypeRep()));
Chris Lattner4b009652007-07-25 00:24:17 +0000741}
742
Steve Narofff0b23542008-01-10 22:15:12 +0000743bool Sema::CheckSingleInitializer(Expr *&Init, QualType DeclType) {
Steve Naroffe14e5542007-09-02 02:04:30 +0000744 // Get the type before calling CheckSingleAssignmentConstraints(), since
745 // it can promote the expression.
Chris Lattner005ed752008-01-04 18:04:52 +0000746 QualType InitType = Init->getType();
Douglas Gregor6fd35572008-12-19 17:40:08 +0000747
748 if (getLangOptions().CPlusPlus)
749 return PerformCopyInitialization(Init, DeclType, "initializing");
750
Chris Lattner005ed752008-01-04 18:04:52 +0000751 AssignConvertType ConvTy = CheckSingleAssignmentConstraints(DeclType, Init);
752 return DiagnoseAssignmentResult(ConvTy, Init->getLocStart(), DeclType,
753 InitType, Init, "initializing");
Steve Naroffe14e5542007-09-02 02:04:30 +0000754}
755
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000756bool Sema::CheckStringLiteralInit(StringLiteral *strLiteral, QualType &DeclT) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000757 const ArrayType *AT = Context.getAsArrayType(DeclT);
758
759 if (const IncompleteArrayType *IAT = dyn_cast<IncompleteArrayType>(AT)) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000760 // C99 6.7.8p14. We have an array of character type with unknown size
761 // being initialized to a string literal.
762 llvm::APSInt ConstVal(32);
763 ConstVal = strLiteral->getByteLength() + 1;
764 // Return a new array type (C99 6.7.8p22).
Eli Friedman8ff07782008-02-15 18:16:39 +0000765 DeclT = Context.getConstantArrayType(IAT->getElementType(), ConstVal,
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000766 ArrayType::Normal, 0);
Chris Lattnera1923f62008-08-04 07:31:14 +0000767 } else {
768 const ConstantArrayType *CAT = cast<ConstantArrayType>(AT);
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000769 // C99 6.7.8p14. We have an array of character type with known size.
Chris Lattnera1923f62008-08-04 07:31:14 +0000770 // FIXME: Avoid truncation for 64-bit length strings.
771 if (strLiteral->getByteLength() > (unsigned)CAT->getSize().getZExtValue())
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000772 Diag(strLiteral->getSourceRange().getBegin(),
Chris Lattner9d2cf082008-11-19 05:27:50 +0000773 diag::warn_initializer_string_for_char_array_too_long)
774 << strLiteral->getSourceRange();
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000775 }
776 // Set type from "char *" to "constant array of char".
777 strLiteral->setType(DeclT);
778 // For now, we always return false (meaning success).
779 return false;
780}
781
782StringLiteral *Sema::IsStringLiteralInit(Expr *Init, QualType DeclType) {
Chris Lattnera1923f62008-08-04 07:31:14 +0000783 const ArrayType *AT = Context.getAsArrayType(DeclType);
Steve Narofff3cb5142008-01-25 00:51:06 +0000784 if (AT && AT->getElementType()->isCharType()) {
785 return dyn_cast<StringLiteral>(Init);
786 }
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000787 return 0;
788}
789
Douglas Gregor6428e762008-11-05 15:29:30 +0000790bool Sema::CheckInitializerTypes(Expr *&Init, QualType &DeclType,
791 SourceLocation InitLoc,
Chris Lattner271d4c22008-11-24 05:29:24 +0000792 DeclarationName InitEntity) {
Douglas Gregorf1ae3e02008-12-18 21:49:58 +0000793 if (DeclType->isDependentType() || Init->isTypeDependent())
794 return false;
795
Douglas Gregor81c29152008-10-29 00:13:59 +0000796 // C++ [dcl.init.ref]p1:
Sebastian Redl51504af2008-11-24 20:06:50 +0000797 // A variable declared to be a T&, that is "reference to type T"
Douglas Gregor81c29152008-10-29 00:13:59 +0000798 // (8.3.2), shall be initialized by an object, or function, of
799 // type T or by an object that can be converted into a T.
800 if (DeclType->isReferenceType())
801 return CheckReferenceInit(Init, DeclType);
802
Steve Naroff8e9337f2008-01-21 23:53:58 +0000803 // C99 6.7.8p3: The type of the entity to be initialized shall be an array
804 // of unknown size ("[]") or an object type that is not a variable array type.
Chris Lattnera1923f62008-08-04 07:31:14 +0000805 if (const VariableArrayType *VAT = Context.getAsVariableArrayType(DeclType))
Chris Lattner9d2cf082008-11-19 05:27:50 +0000806 return Diag(InitLoc, diag::err_variable_object_no_init)
807 << VAT->getSizeExpr()->getSourceRange();
Steve Naroff8e9337f2008-01-21 23:53:58 +0000808
Steve Naroffcb69fb72007-12-10 22:44:33 +0000809 InitListExpr *InitList = dyn_cast<InitListExpr>(Init);
810 if (!InitList) {
Steve Naroff0d4e6ad2008-01-22 00:55:40 +0000811 // FIXME: Handle wide strings
812 if (StringLiteral *strLiteral = IsStringLiteralInit(Init, DeclType))
813 return CheckStringLiteralInit(strLiteral, DeclType);
Eli Friedman65280992008-02-08 00:48:24 +0000814
Douglas Gregor6428e762008-11-05 15:29:30 +0000815 // C++ [dcl.init]p14:
816 // -- If the destination type is a (possibly cv-qualified) class
817 // type:
818 if (getLangOptions().CPlusPlus && DeclType->isRecordType()) {
819 QualType DeclTypeC = Context.getCanonicalType(DeclType);
820 QualType InitTypeC = Context.getCanonicalType(Init->getType());
821
822 // -- If the initialization is direct-initialization, or if it is
823 // copy-initialization where the cv-unqualified version of the
824 // source type is the same class as, or a derived class of, the
825 // class of the destination, constructors are considered.
826 if ((DeclTypeC.getUnqualifiedType() == InitTypeC.getUnqualifiedType()) ||
827 IsDerivedFrom(InitTypeC, DeclTypeC)) {
828 CXXConstructorDecl *Constructor
829 = PerformInitializationByConstructor(DeclType, &Init, 1,
830 InitLoc, Init->getSourceRange(),
831 InitEntity, IK_Copy);
832 return Constructor == 0;
833 }
834
835 // -- Otherwise (i.e., for the remaining copy-initialization
836 // cases), user-defined conversion sequences that can
837 // convert from the source type to the destination type or
838 // (when a conversion function is used) to a derived class
839 // thereof are enumerated as described in 13.3.1.4, and the
840 // best one is chosen through overload resolution
841 // (13.3). If the conversion cannot be done or is
842 // ambiguous, the initialization is ill-formed. The
843 // function selected is called with the initializer
844 // expression as its argument; if the function is a
845 // constructor, the call initializes a temporary of the
846 // destination type.
847 // FIXME: We're pretending to do copy elision here; return to
848 // this when we have ASTs for such things.
Douglas Gregor6fd35572008-12-19 17:40:08 +0000849 if (!PerformImplicitConversion(Init, DeclType, "initializing"))
Douglas Gregor6428e762008-11-05 15:29:30 +0000850 return false;
Chris Lattner70b93d82008-11-18 22:52:51 +0000851
852 return Diag(InitLoc, diag::err_typecheck_convert_incompatible)
Chris Lattner271d4c22008-11-24 05:29:24 +0000853 << DeclType << InitEntity << "initializing"
Chris Lattner70b93d82008-11-18 22:52:51 +0000854 << Init->getSourceRange();
Douglas Gregor6428e762008-11-05 15:29:30 +0000855 }
856
Steve Naroffb2f72412008-09-29 20:07:05 +0000857 // C99 6.7.8p16.
Eli Friedman65280992008-02-08 00:48:24 +0000858 if (DeclType->isArrayType())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000859 return Diag(Init->getLocStart(), diag::err_array_init_list_required)
860 << Init->getSourceRange();
Eli Friedman65280992008-02-08 00:48:24 +0000861
Steve Narofff0b23542008-01-10 22:15:12 +0000862 return CheckSingleInitializer(Init, DeclType);
Douglas Gregor15e04622008-11-05 16:20:31 +0000863 } else if (getLangOptions().CPlusPlus) {
864 // C++ [dcl.init]p14:
865 // [...] If the class is an aggregate (8.5.1), and the initializer
866 // is a brace-enclosed list, see 8.5.1.
867 //
868 // Note: 8.5.1 is handled below; here, we diagnose the case where
869 // we have an initializer list and a destination type that is not
870 // an aggregate.
871 // FIXME: In C++0x, this is yet another form of initialization.
872 if (const RecordType *ClassRec = DeclType->getAsRecordType()) {
873 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassRec->getDecl());
874 if (!ClassDecl->isAggregate())
Chris Lattner9d2cf082008-11-19 05:27:50 +0000875 return Diag(InitLoc, diag::err_init_non_aggr_init_list)
Chris Lattner4bfd2232008-11-24 06:25:27 +0000876 << DeclType << Init->getSourceRange();
Douglas Gregor15e04622008-11-05 16:20:31 +0000877 }
Steve Naroffcb69fb72007-12-10 22:44:33 +0000878 }
Eli Friedman38b7a912008-06-06 19:40:52 +0000879
Steve Naroffc4d4a482008-05-01 22:18:59 +0000880 InitListChecker CheckInitList(this, InitList, DeclType);
881 return CheckInitList.HadError();
Steve Naroffe14e5542007-09-02 02:04:30 +0000882}
883
Douglas Gregor6704b312008-11-17 22:58:34 +0000884/// GetNameForDeclarator - Determine the full declaration name for the
885/// given Declarator.
886DeclarationName Sema::GetNameForDeclarator(Declarator &D) {
887 switch (D.getKind()) {
888 case Declarator::DK_Abstract:
889 assert(D.getIdentifier() == 0 && "abstract declarators have no name");
890 return DeclarationName();
891
892 case Declarator::DK_Normal:
893 assert (D.getIdentifier() != 0 && "normal declarators have an identifier");
894 return DeclarationName(D.getIdentifier());
895
896 case Declarator::DK_Constructor: {
897 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
898 Ty = Context.getCanonicalType(Ty);
899 return Context.DeclarationNames.getCXXConstructorName(Ty);
900 }
901
902 case Declarator::DK_Destructor: {
903 QualType Ty = Context.getTypeDeclType((TypeDecl *)D.getDeclaratorIdType());
904 Ty = Context.getCanonicalType(Ty);
905 return Context.DeclarationNames.getCXXDestructorName(Ty);
906 }
907
908 case Declarator::DK_Conversion: {
909 QualType Ty = QualType::getFromOpaquePtr(D.getDeclaratorIdType());
910 Ty = Context.getCanonicalType(Ty);
911 return Context.DeclarationNames.getCXXConversionFunctionName(Ty);
912 }
Douglas Gregor96a32dd2008-11-18 14:39:36 +0000913
914 case Declarator::DK_Operator:
915 assert(D.getIdentifier() == 0 && "operator names have no identifier");
916 return Context.DeclarationNames.getCXXOperatorName(
917 D.getOverloadedOperator());
Douglas Gregor6704b312008-11-17 22:58:34 +0000918 }
919
920 assert(false && "Unknown name kind");
921 return DeclarationName();
922}
923
Douglas Gregorc5cbc242008-12-15 23:53:10 +0000924/// isNearlyMatchingMemberFunction - Determine whether the C++ member
925/// functions Declaration and Definition are "nearly" matching. This
926/// heuristic is used to improve diagnostics in the case where an
927/// out-of-line member function definition doesn't match any
928/// declaration within the class.
929static bool isNearlyMatchingMemberFunction(ASTContext &Context,
930 FunctionDecl *Declaration,
931 FunctionDecl *Definition) {
932 if (Declaration->param_size() != Definition->param_size())
933 return false;
934 for (unsigned Idx = 0; Idx < Declaration->param_size(); ++Idx) {
935 QualType DeclParamTy = Declaration->getParamDecl(Idx)->getType();
936 QualType DefParamTy = Definition->getParamDecl(Idx)->getType();
937
938 DeclParamTy = Context.getCanonicalType(DeclParamTy.getNonReferenceType());
939 DefParamTy = Context.getCanonicalType(DefParamTy.getNonReferenceType());
940 if (DeclParamTy.getUnqualifiedType() != DefParamTy.getUnqualifiedType())
941 return false;
942 }
943
944 return true;
945}
946
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +0000947Sema::DeclTy *
Douglas Gregorc5cbc242008-12-15 23:53:10 +0000948Sema::ActOnDeclarator(Scope *S, Declarator &D, DeclTy *lastDecl,
949 bool IsFunctionDefinition) {
Steve Naroff2591e1b2007-09-13 23:52:58 +0000950 ScopedDecl *LastDeclarator = dyn_cast_or_null<ScopedDecl>((Decl *)lastDecl);
Douglas Gregor6704b312008-11-17 22:58:34 +0000951 DeclarationName Name = GetNameForDeclarator(D);
952
Chris Lattner4b009652007-07-25 00:24:17 +0000953 // All of these full declarators require an identifier. If it doesn't have
954 // one, the ParsedFreeStandingDeclSpec action should be used.
Douglas Gregor6704b312008-11-17 22:58:34 +0000955 if (!Name) {
Chris Lattnercd61d592008-11-11 06:13:16 +0000956 if (!D.getInvalidType()) // Reject this if we think it is valid.
957 Diag(D.getDeclSpec().getSourceRange().getBegin(),
Chris Lattner8ba580c2008-11-19 05:08:23 +0000958 diag::err_declarator_need_ident)
959 << D.getDeclSpec().getSourceRange() << D.getSourceRange();
Chris Lattner4b009652007-07-25 00:24:17 +0000960 return 0;
961 }
962
Chris Lattnera7549902007-08-26 06:24:45 +0000963 // The scope passed in may not be a decl scope. Zip up the scope tree until
964 // we find one that is.
Douglas Gregor8acb7272008-12-11 16:49:14 +0000965 while ((S->getFlags() & Scope::DeclScope) == 0 ||
966 (S->getFlags() & Scope::TemplateParamScope) != 0)
Chris Lattnera7549902007-08-26 06:24:45 +0000967 S = S->getParent();
968
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000969 DeclContext *DC;
970 Decl *PrevDecl;
Steve Naroffd21bc0d2007-09-13 18:10:37 +0000971 ScopedDecl *New;
Steve Naroffd1ad6ae2007-08-28 20:14:24 +0000972 bool InvalidDecl = false;
Douglas Gregor1d661552008-04-13 21:07:44 +0000973
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000974 // See if this is a redefinition of a variable in the same scope.
975 if (!D.getCXXScopeSpec().isSet()) {
976 DC = CurContext;
Douglas Gregor6704b312008-11-17 22:58:34 +0000977 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000978 } else { // Something like "int foo::x;"
979 DC = static_cast<DeclContext*>(D.getCXXScopeSpec().getScopeRep());
Douglas Gregor6704b312008-11-17 22:58:34 +0000980 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
Argiris Kirtzidis054a2632008-11-08 17:17:31 +0000981
982 // C++ 7.3.1.2p2:
983 // Members (including explicit specializations of templates) of a named
984 // namespace can also be defined outside that namespace by explicit
985 // qualification of the name being defined, provided that the entity being
986 // defined was already declared in the namespace and the definition appears
987 // after the point of declaration in a namespace that encloses the
988 // declarations namespace.
989 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +0000990 // Note that we only check the context at this point. We don't yet
991 // have enough information to make sure that PrevDecl is actually
992 // the declaration we want to match. For example, given:
993 //
Douglas Gregor98341042008-12-12 08:25:50 +0000994 // class X {
995 // void f();
Douglas Gregorc5cbc242008-12-15 23:53:10 +0000996 // void f(float);
Douglas Gregor98341042008-12-12 08:25:50 +0000997 // };
998 //
Douglas Gregorc5cbc242008-12-15 23:53:10 +0000999 // void X::f(int) { } // ill-formed
1000 //
1001 // In this case, PrevDecl will point to the overload set
1002 // containing the two f's declared in X, but neither of them
1003 // matches.
1004 if (!CurContext->Encloses(DC)) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001005 // The qualifying scope doesn't enclose the original declaration.
1006 // Emit diagnostic based on current scope.
1007 SourceLocation L = D.getIdentifierLoc();
1008 SourceRange R = D.getCXXScopeSpec().getRange();
1009 if (isa<FunctionDecl>(CurContext)) {
Chris Lattner254de7d2008-11-23 20:28:15 +00001010 Diag(L, diag::err_invalid_declarator_in_function) << Name << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001011 } else {
Chris Lattner254de7d2008-11-23 20:28:15 +00001012 Diag(L, diag::err_invalid_declarator_scope)
Chris Lattner271d4c22008-11-24 05:29:24 +00001013 << Name << cast<NamedDecl>(DC)->getDeclName() << R;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001014 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001015 InvalidDecl = true;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001016 }
1017 }
1018
Douglas Gregor2715a1f2008-12-08 18:40:42 +00001019 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00001020 // Maybe we will complain about the shadowed template parameter.
Douglas Gregor1b21c7f2008-12-05 23:32:09 +00001021 InvalidDecl = InvalidDecl
1022 || DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
Douglas Gregordd861062008-12-05 18:15:24 +00001023 // Just pretend that we didn't see the previous declaration.
1024 PrevDecl = 0;
1025 }
1026
Douglas Gregor1d661552008-04-13 21:07:44 +00001027 // In C++, the previous declaration we find might be a tag type
1028 // (class or enum). In this case, the new declaration will hide the
1029 // tag type.
1030 if (PrevDecl && PrevDecl->getIdentifierNamespace() == Decl::IDNS_Tag)
1031 PrevDecl = 0;
1032
Chris Lattner82bb4792007-11-14 06:34:38 +00001033 QualType R = GetTypeForDeclarator(D, S);
1034 assert(!R.isNull() && "GetTypeForDeclarator() returned null type");
1035
Chris Lattner4b009652007-07-25 00:24:17 +00001036 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_typedef) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001037 // Typedef declarators cannot be qualified (C++ [dcl.meaning]p1).
1038 if (D.getCXXScopeSpec().isSet()) {
1039 Diag(D.getIdentifierLoc(), diag::err_qualified_typedef_declarator)
1040 << D.getCXXScopeSpec().getRange();
1041 InvalidDecl = true;
1042 // Pretend we didn't see the scope specifier.
1043 DC = 0;
1044 }
1045
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001046 // Check that there are no default arguments (C++ only).
1047 if (getLangOptions().CPlusPlus)
1048 CheckExtraCXXDefaultArguments(D);
1049
Chris Lattner82bb4792007-11-14 06:34:38 +00001050 TypedefDecl *NewTD = ParseTypedefDecl(S, D, R, LastDeclarator);
Chris Lattner4b009652007-07-25 00:24:17 +00001051 if (!NewTD) return 0;
1052
1053 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001054 ProcessDeclAttributes(NewTD, D);
Steve Narofff8a09432008-01-09 23:34:55 +00001055 // Merge the decl with the existing one if appropriate. If the decl is
1056 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001057 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00001058 NewTD = MergeTypeDefDecl(NewTD, PrevDecl);
1059 if (NewTD == 0) return 0;
1060 }
1061 New = NewTD;
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001062 if (S->getFnParent() == 0) {
Chris Lattner4b009652007-07-25 00:24:17 +00001063 // C99 6.7.7p2: If a typedef name specifies a variably modified type
1064 // then it shall have block scope.
Eli Friedmane0079792008-02-15 12:53:51 +00001065 if (NewTD->getUnderlyingType()->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00001066 if (NewTD->getUnderlyingType()->isVariableArrayType())
1067 Diag(D.getIdentifierLoc(), diag::err_vla_decl_in_file_scope);
1068 else
1069 Diag(D.getIdentifierLoc(), diag::err_vm_decl_in_file_scope);
1070
Steve Naroff5eb879b2007-08-31 17:20:07 +00001071 InvalidDecl = true;
Chris Lattner4b009652007-07-25 00:24:17 +00001072 }
1073 }
Chris Lattner82bb4792007-11-14 06:34:38 +00001074 } else if (R.getTypePtr()->isFunctionType()) {
Chris Lattner265c8172007-09-27 15:15:46 +00001075 FunctionDecl::StorageClass SC = FunctionDecl::None;
Chris Lattner4b009652007-07-25 00:24:17 +00001076 switch (D.getDeclSpec().getStorageClassSpec()) {
1077 default: assert(0 && "Unknown storage class!");
1078 case DeclSpec::SCS_auto:
1079 case DeclSpec::SCS_register:
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001080 case DeclSpec::SCS_mutable:
Chris Lattner4bfd2232008-11-24 06:25:27 +00001081 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_func);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001082 InvalidDecl = true;
1083 break;
Chris Lattner4b009652007-07-25 00:24:17 +00001084 case DeclSpec::SCS_unspecified: SC = FunctionDecl::None; break;
1085 case DeclSpec::SCS_extern: SC = FunctionDecl::Extern; break;
1086 case DeclSpec::SCS_static: SC = FunctionDecl::Static; break;
Steve Naroffd404c352008-01-28 21:57:15 +00001087 case DeclSpec::SCS_private_extern: SC = FunctionDecl::PrivateExtern;break;
Chris Lattner4b009652007-07-25 00:24:17 +00001088 }
1089
Chris Lattner4c7802b2008-03-15 21:24:04 +00001090 bool isInline = D.getDeclSpec().isInlineSpecified();
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001091 // bool isVirtual = D.getDeclSpec().isVirtualSpecified();
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001092 bool isExplicit = D.getDeclSpec().isExplicitSpecified();
1093
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001094 FunctionDecl *NewFD;
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001095 if (D.getKind() == Declarator::DK_Constructor) {
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001096 // This is a C++ constructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001097 assert(DC->isCXXRecord() &&
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001098 "Constructors can only be declared in a member context");
1099
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001100 bool isInvalidDecl = CheckConstructorDeclarator(D, R, SC);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001101
1102 // Create the new declaration
1103 NewFD = CXXConstructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001104 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001105 D.getIdentifierLoc(), Name, R,
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001106 isExplicit, isInline,
1107 /*isImplicitlyDeclared=*/false);
1108
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001109 if (isInvalidDecl)
1110 NewFD->setInvalidDecl();
1111 } else if (D.getKind() == Declarator::DK_Destructor) {
1112 // This is a C++ destructor declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001113 if (DC->isCXXRecord()) {
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001114 bool isInvalidDecl = CheckDestructorDeclarator(D, R, SC);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001115
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001116 NewFD = CXXDestructorDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001117 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001118 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001119 isInline,
1120 /*isImplicitlyDeclared=*/false);
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001121
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001122 if (isInvalidDecl)
1123 NewFD->setInvalidDecl();
1124 } else {
1125 Diag(D.getIdentifierLoc(), diag::err_destructor_not_member);
1126 // Create a FunctionDecl to satisfy the function definition parsing
1127 // code path.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001128 NewFD = FunctionDecl::Create(Context, DC, D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001129 Name, R, SC, isInline, LastDeclarator,
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001130 // FIXME: Move to DeclGroup...
1131 D.getDeclSpec().getSourceRange().getBegin());
Douglas Gregor8210a8e2008-11-05 20:51:48 +00001132 NewFD->setInvalidDecl();
Argiris Kirtzidisc9e909c2008-11-07 22:02:30 +00001133 }
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001134 } else if (D.getKind() == Declarator::DK_Conversion) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001135 if (!DC->isCXXRecord()) {
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001136 Diag(D.getIdentifierLoc(),
1137 diag::err_conv_function_not_member);
1138 return 0;
1139 } else {
1140 bool isInvalidDecl = CheckConversionDeclarator(D, R, SC);
1141
1142 NewFD = CXXConversionDecl::Create(Context,
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001143 cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001144 D.getIdentifierLoc(), Name, R,
Douglas Gregor3ef6c972008-11-07 20:08:42 +00001145 isInline, isExplicit);
1146
1147 if (isInvalidDecl)
1148 NewFD->setInvalidDecl();
1149 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001150 } else if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001151 // This is a C++ method declaration.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001152 NewFD = CXXMethodDecl::Create(Context, cast<CXXRecordDecl>(DC),
Douglas Gregor6704b312008-11-17 22:58:34 +00001153 D.getIdentifierLoc(), Name, R,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001154 (SC == FunctionDecl::Static), isInline,
1155 LastDeclarator);
1156 } else {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001157 NewFD = FunctionDecl::Create(Context, DC,
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001158 D.getIdentifierLoc(),
Douglas Gregor6704b312008-11-17 22:58:34 +00001159 Name, R, SC, isInline, LastDeclarator,
Steve Naroff71cd7762008-10-03 00:02:03 +00001160 // FIXME: Move to DeclGroup...
1161 D.getDeclSpec().getSourceRange().getBegin());
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001162 }
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001163
Ted Kremenek117f1862008-02-27 22:18:07 +00001164 // Handle attributes.
Chris Lattner9b384ca2008-06-29 00:02:00 +00001165 ProcessDeclAttributes(NewFD, D);
Chris Lattner3e254fb2008-04-08 04:40:51 +00001166
Douglas Gregorb9213832008-12-15 21:24:18 +00001167 // Set the lexical context. If the declarator has a C++
1168 // scope specifier, the lexical context will be different
1169 // from the semantic context.
1170 NewFD->setLexicalDeclContext(CurContext);
1171
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001172 // Handle GNU asm-label extension (encoded as an attribute).
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00001173 if (Expr *E = (Expr*) D.getAsmLabel()) {
Daniel Dunbarc3540ff2008-08-05 01:35:17 +00001174 // The parser guarantees this is a string.
1175 StringLiteral *SE = cast<StringLiteral>(E);
1176 NewFD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1177 SE->getByteLength())));
1178 }
1179
Chris Lattner3e254fb2008-04-08 04:40:51 +00001180 // Copy the parameter declarations from the declarator D to
1181 // the function declaration NewFD, if they are available.
Eli Friedman769e7302008-08-25 21:31:01 +00001182 if (D.getNumTypeObjects() > 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001183 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
1184
1185 // Create Decl objects for each parameter, adding them to the
1186 // FunctionDecl.
1187 llvm::SmallVector<ParmVarDecl*, 16> Params;
1188
1189 // Check for C99 6.7.5.3p10 - foo(void) is a non-varargs
1190 // function that takes no arguments, not a function that takes a
Chris Lattner97316c02008-04-10 02:22:51 +00001191 // single void argument.
Eli Friedman910758e2008-05-22 08:54:03 +00001192 // We let through "const void" here because Sema::GetTypeForDeclarator
1193 // already checks for that case.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001194 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
1195 FTI.ArgInfo[0].Param &&
Chris Lattner3e254fb2008-04-08 04:40:51 +00001196 ((ParmVarDecl*)FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
1197 // empty arg list, don't push any params.
Chris Lattner97316c02008-04-10 02:22:51 +00001198 ParmVarDecl *Param = (ParmVarDecl*)FTI.ArgInfo[0].Param;
1199
Chris Lattnerda7b5f02008-04-10 02:26:16 +00001200 // In C++, the empty parameter-type-list must be spelled "void"; a
1201 // typedef of void is not permitted.
1202 if (getLangOptions().CPlusPlus &&
Eli Friedman910758e2008-05-22 08:54:03 +00001203 Param->getType().getUnqualifiedType() != Context.VoidTy) {
Chris Lattner97316c02008-04-10 02:22:51 +00001204 Diag(Param->getLocation(), diag::ext_param_typedef_of_void);
1205 }
Eli Friedman769e7302008-08-25 21:31:01 +00001206 } else if (FTI.NumArgs > 0 && FTI.ArgInfo[0].Param != 0) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00001207 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
1208 Params.push_back((ParmVarDecl *)FTI.ArgInfo[i].Param);
1209 }
1210
1211 NewFD->setParams(&Params[0], Params.size());
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001212 } else if (R->getAsTypedefType()) {
1213 // When we're declaring a function with a typedef, as in the
1214 // following example, we'll need to synthesize (unnamed)
1215 // parameters for use in the declaration.
1216 //
1217 // @code
1218 // typedef void fn(int);
1219 // fn f;
1220 // @endcode
1221 const FunctionTypeProto *FT = R->getAsFunctionTypeProto();
1222 if (!FT) {
1223 // This is a typedef of a function with no prototype, so we
1224 // don't need to do anything.
1225 } else if ((FT->getNumArgs() == 0) ||
1226 (FT->getNumArgs() == 1 && !FT->isVariadic() &&
1227 FT->getArgType(0)->isVoidType())) {
1228 // This is a zero-argument function. We don't need to do anything.
1229 } else {
1230 // Synthesize a parameter for each argument type.
1231 llvm::SmallVector<ParmVarDecl*, 16> Params;
1232 for (FunctionTypeProto::arg_type_iterator ArgType = FT->arg_type_begin();
1233 ArgType != FT->arg_type_end(); ++ArgType) {
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001234 Params.push_back(ParmVarDecl::Create(Context, DC,
Douglas Gregorba3e8b72008-10-24 18:09:54 +00001235 SourceLocation(), 0,
1236 *ArgType, VarDecl::None,
1237 0, 0));
1238 }
1239
1240 NewFD->setParams(&Params[0], Params.size());
1241 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00001242 }
1243
Douglas Gregor605de8d2008-12-16 21:30:33 +00001244 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(NewFD))
1245 InvalidDecl = InvalidDecl || CheckConstructor(Constructor);
Douglas Gregorb9213832008-12-15 21:24:18 +00001246 else if (isa<CXXDestructorDecl>(NewFD))
1247 cast<CXXRecordDecl>(NewFD->getParent())->setUserDeclaredDestructor(true);
1248 else if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(NewFD))
Douglas Gregorb0212bd2008-11-17 20:34:05 +00001249 ActOnConversionDeclarator(Conversion);
Douglas Gregorf15ac4b2008-10-31 09:07:45 +00001250
Douglas Gregore60e5d32008-11-06 22:13:31 +00001251 // Extra checking for C++ overloaded operators (C++ [over.oper]).
1252 if (NewFD->isOverloadedOperator() &&
1253 CheckOverloadedOperatorDeclaration(NewFD))
1254 NewFD->setInvalidDecl();
1255
Steve Narofff8a09432008-01-09 23:34:55 +00001256 // Merge the decl with the existing one if appropriate. Since C functions
1257 // are in a flat namespace, make sure we consider decls in outer scopes.
Argiris Kirtzidis59a9afb2008-05-09 23:39:43 +00001258 if (PrevDecl &&
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001259 (!getLangOptions().CPlusPlus||isDeclInScope(PrevDecl, DC, S))) {
Douglas Gregor42214c52008-04-21 02:02:58 +00001260 bool Redeclaration = false;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001261
1262 // If C++, determine whether NewFD is an overload of PrevDecl or
1263 // a declaration that requires merging. If it's an overload,
1264 // there's no more work to do here; we'll just add the new
1265 // function to the scope.
1266 OverloadedFunctionDecl::function_iterator MatchedDecl;
1267 if (!getLangOptions().CPlusPlus ||
1268 !IsOverload(NewFD, PrevDecl, MatchedDecl)) {
1269 Decl *OldDecl = PrevDecl;
1270
1271 // If PrevDecl was an overloaded function, extract the
1272 // FunctionDecl that matched.
1273 if (isa<OverloadedFunctionDecl>(PrevDecl))
1274 OldDecl = *MatchedDecl;
1275
1276 // NewFD and PrevDecl represent declarations that need to be
1277 // merged.
1278 NewFD = MergeFunctionDecl(NewFD, OldDecl, Redeclaration);
1279
1280 if (NewFD == 0) return 0;
1281 if (Redeclaration) {
1282 NewFD->setPreviousDeclaration(cast<FunctionDecl>(OldDecl));
1283
1284 if (OldDecl == PrevDecl) {
1285 // Remove the name binding for the previous
Douglas Gregor8acb7272008-12-11 16:49:14 +00001286 // declaration.
1287 if (S->isDeclScope(PrevDecl)) {
1288 IdResolver.RemoveDecl(cast<NamedDecl>(PrevDecl));
1289 S->RemoveDecl(PrevDecl);
1290 }
1291
1292 // Introduce the new binding for this declaration.
1293 IdResolver.AddDecl(NewFD);
1294 if (getLangOptions().CPlusPlus && NewFD->getParent())
1295 NewFD->getParent()->insert(Context, NewFD);
1296
1297 // Add the redeclaration to the current scope, since we'll
1298 // be skipping PushOnScopeChains.
1299 S->AddDecl(NewFD);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001300 } else {
1301 // We need to update the OverloadedFunctionDecl with the
1302 // latest declaration of this function, so that name
1303 // lookup will always refer to the latest declaration of
1304 // this function.
1305 *MatchedDecl = NewFD;
Douglas Gregor8acb7272008-12-11 16:49:14 +00001306 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001307
Douglas Gregor8acb7272008-12-11 16:49:14 +00001308 if (getLangOptions().CPlusPlus) {
1309 // Add this declaration to the current context.
1310 CurContext->addDecl(Context, NewFD, false);
Douglas Gregord2baafd2008-10-21 16:13:35 +00001311
Douglas Gregor8acb7272008-12-11 16:49:14 +00001312 // Check default arguments now that we have merged decls.
1313 CheckCXXDefaultArguments(NewFD);
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001314
1315 // An out-of-line member function declaration must also be a
1316 // definition (C++ [dcl.meaning]p1).
1317 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet() &&
1318 !InvalidDecl) {
1319 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1320 << D.getCXXScopeSpec().getRange();
1321 NewFD->setInvalidDecl();
1322 }
Douglas Gregord2baafd2008-10-21 16:13:35 +00001323 }
Douglas Gregor8acb7272008-12-11 16:49:14 +00001324
Douglas Gregor8acb7272008-12-11 16:49:14 +00001325 return NewFD;
Douglas Gregord2baafd2008-10-21 16:13:35 +00001326 }
Douglas Gregor42214c52008-04-21 02:02:58 +00001327 }
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001328
1329 if (!Redeclaration && D.getCXXScopeSpec().isSet()) {
1330 // The user tried to provide an out-of-line definition for a
1331 // member function, but there was no such member function
1332 // declared (C++ [class.mfct]p2). For example:
1333 //
1334 // class X {
1335 // void f() const;
1336 // };
1337 //
1338 // void X::f() { } // ill-formed
1339 //
1340 // Complain about this problem, and attempt to suggest close
1341 // matches (e.g., those that differ only in cv-qualifiers and
1342 // whether the parameter types are references).
1343 Diag(D.getIdentifierLoc(), diag::err_member_def_does_not_match)
1344 << cast<CXXRecordDecl>(DC)->getDeclName()
1345 << D.getCXXScopeSpec().getRange();
1346 InvalidDecl = true;
1347
1348 PrevDecl = LookupDecl(Name, Decl::IDNS_Ordinary, S, DC);
1349 if (!PrevDecl) {
1350 // Nothing to suggest.
1351 } else if (OverloadedFunctionDecl *Ovl
1352 = dyn_cast<OverloadedFunctionDecl>(PrevDecl)) {
1353 for (OverloadedFunctionDecl::function_iterator
1354 Func = Ovl->function_begin(),
1355 FuncEnd = Ovl->function_end();
1356 Func != FuncEnd; ++Func) {
1357 if (isNearlyMatchingMemberFunction(Context, *Func, NewFD))
1358 Diag((*Func)->getLocation(), diag::note_member_def_close_match);
1359
1360 }
1361 } else if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(PrevDecl)) {
1362 // Suggest this no matter how mismatched it is; it's the only
1363 // thing we have.
1364 unsigned diag;
1365 if (isNearlyMatchingMemberFunction(Context, Method, NewFD))
1366 diag = diag::note_member_def_close_match;
1367 else if (Method->getBody())
1368 diag = diag::note_previous_definition;
1369 else
1370 diag = diag::note_previous_declaration;
1371 Diag(Method->getLocation(), diag);
1372 }
1373
1374 PrevDecl = 0;
1375 }
Chris Lattner4b009652007-07-25 00:24:17 +00001376 }
1377 New = NewFD;
Chris Lattner3e254fb2008-04-08 04:40:51 +00001378
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001379 if (getLangOptions().CPlusPlus) {
1380 // In C++, check default arguments now that we have merged decls.
Chris Lattner3e254fb2008-04-08 04:40:51 +00001381 CheckCXXDefaultArguments(NewFD);
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001382
1383 // An out-of-line member function declaration must also be a
1384 // definition (C++ [dcl.meaning]p1).
1385 if (!IsFunctionDefinition && D.getCXXScopeSpec().isSet()) {
1386 Diag(NewFD->getLocation(), diag::err_out_of_line_declaration)
1387 << D.getCXXScopeSpec().getRange();
1388 InvalidDecl = true;
1389 }
1390 }
Chris Lattner4b009652007-07-25 00:24:17 +00001391 } else {
Douglas Gregor2b9422f2008-05-07 04:49:29 +00001392 // Check that there are no default arguments (C++ only).
1393 if (getLangOptions().CPlusPlus)
1394 CheckExtraCXXDefaultArguments(D);
1395
Ted Kremenek42730c52008-01-07 19:49:32 +00001396 if (R.getTypePtr()->isObjCInterfaceType()) {
Chris Lattner65cae292008-11-19 08:23:25 +00001397 Diag(D.getIdentifierLoc(), diag::err_statically_allocated_object)
1398 << D.getIdentifier();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00001399 InvalidDecl = true;
1400 }
Chris Lattner4b009652007-07-25 00:24:17 +00001401
1402 VarDecl *NewVD;
1403 VarDecl::StorageClass SC;
1404 switch (D.getDeclSpec().getStorageClassSpec()) {
Chris Lattner48d225c2008-03-15 21:10:16 +00001405 default: assert(0 && "Unknown storage class!");
1406 case DeclSpec::SCS_unspecified: SC = VarDecl::None; break;
1407 case DeclSpec::SCS_extern: SC = VarDecl::Extern; break;
1408 case DeclSpec::SCS_static: SC = VarDecl::Static; break;
1409 case DeclSpec::SCS_auto: SC = VarDecl::Auto; break;
1410 case DeclSpec::SCS_register: SC = VarDecl::Register; break;
1411 case DeclSpec::SCS_private_extern: SC = VarDecl::PrivateExtern; break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001412 case DeclSpec::SCS_mutable:
1413 // mutable can only appear on non-static class members, so it's always
1414 // an error here
1415 Diag(D.getIdentifierLoc(), diag::err_mutable_nonmember);
1416 InvalidDecl = true;
Douglas Gregor538754e2008-12-01 22:46:22 +00001417 SC = VarDecl::None;
Sebastian Redl6a2b7fd2008-11-17 23:24:37 +00001418 break;
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001419 }
Douglas Gregor6704b312008-11-17 22:58:34 +00001420
1421 IdentifierInfo *II = Name.getAsIdentifierInfo();
1422 if (!II) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00001423 Diag(D.getIdentifierLoc(), diag::err_bad_variable_name)
1424 << Name.getAsString();
Douglas Gregor6704b312008-11-17 22:58:34 +00001425 return 0;
1426 }
1427
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001428 if (DC->isCXXRecord()) {
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001429 // This is a static data member for a C++ class.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001430 NewVD = CXXClassVarDecl::Create(Context, cast<CXXRecordDecl>(DC),
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001431 D.getIdentifierLoc(), II,
1432 R, LastDeclarator);
Steve Naroffe14e5542007-09-02 02:04:30 +00001433 } else {
Daniel Dunbar5eea5622008-09-08 20:05:47 +00001434 bool ThreadSpecified = D.getDeclSpec().isThreadSpecified();
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001435 if (S->getFnParent() == 0) {
1436 // C99 6.9p2: The storage-class specifiers auto and register shall not
1437 // appear in the declaration specifiers in an external declaration.
1438 if (SC == VarDecl::Auto || SC == VarDecl::Register) {
Chris Lattner4bfd2232008-11-24 06:25:27 +00001439 Diag(D.getIdentifierLoc(), diag::err_typecheck_sclass_fscope);
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001440 InvalidDecl = true;
1441 }
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00001442 }
Sebastian Redl9f5337b2008-11-14 23:42:31 +00001443 NewVD = VarDecl::Create(Context, DC, D.getIdentifierLoc(),
1444 II, R, SC, LastDeclarator,
1445 // FIXME: Move to DeclGroup...
1446 D.getDeclSpec().getSourceRange().getBegin());
1447 NewVD->setThreadSpecified(ThreadSpecified);
Steve Naroffcae537d2007-08-28 18:45:29 +00001448 }
Chris Lattner4b009652007-07-25 00:24:17 +00001449 // Handle attributes prior to checking for duplicates in MergeVarDecl
Chris Lattner9b384ca2008-06-29 00:02:00 +00001450 ProcessDeclAttributes(NewVD, D);
Nate Begemanea583262008-03-14 18:07:10 +00001451
Daniel Dunbarced89142008-08-06 00:03:29 +00001452 // Handle GNU asm-label extension (encoded as an attribute).
1453 if (Expr *E = (Expr*) D.getAsmLabel()) {
1454 // The parser guarantees this is a string.
1455 StringLiteral *SE = cast<StringLiteral>(E);
1456 NewVD->addAttr(new AsmLabelAttr(std::string(SE->getStrData(),
1457 SE->getByteLength())));
1458 }
1459
Nate Begemanea583262008-03-14 18:07:10 +00001460 // Emit an error if an address space was applied to decl with local storage.
1461 // This includes arrays of objects with address space qualifiers, but not
1462 // automatic variables that point to other address spaces.
1463 // ISO/IEC TR 18037 S5.1.2
Nate Begemanefc11212008-03-25 18:36:32 +00001464 if (NewVD->hasLocalStorage() && (NewVD->getType().getAddressSpace() != 0)) {
1465 Diag(D.getIdentifierLoc(), diag::err_as_qualified_auto_decl);
1466 InvalidDecl = true;
Nate Begeman06068192008-03-14 00:22:18 +00001467 }
Steve Narofff8a09432008-01-09 23:34:55 +00001468 // Merge the decl with the existing one if appropriate. If the decl is
1469 // in an outer scope, it isn't the same thing.
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00001470 if (PrevDecl && isDeclInScope(PrevDecl, DC, S)) {
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001471 if (isa<FieldDecl>(PrevDecl) && D.getCXXScopeSpec().isSet()) {
1472 // The user tried to define a non-static data member
1473 // out-of-line (C++ [dcl.meaning]p1).
1474 Diag(NewVD->getLocation(), diag::err_nonstatic_member_out_of_line)
1475 << D.getCXXScopeSpec().getRange();
1476 NewVD->Destroy(Context);
1477 return 0;
1478 }
1479
Chris Lattner4b009652007-07-25 00:24:17 +00001480 NewVD = MergeVarDecl(NewVD, PrevDecl);
1481 if (NewVD == 0) return 0;
Douglas Gregorc5cbc242008-12-15 23:53:10 +00001482
1483 if (D.getCXXScopeSpec().isSet()) {
1484 // No previous declaration in the qualifying scope.
1485 Diag(D.getIdentifierLoc(), diag::err_typecheck_no_member)
1486 << Name << D.getCXXScopeSpec().getRange();
1487 InvalidDecl = true;
1488 }
Chris Lattner4b009652007-07-25 00:24:17 +00001489 }
Chris Lattner4b009652007-07-25 00:24:17 +00001490 New = NewVD;
1491 }
1492
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00001493 // Set the lexical context. If the declarator has a C++ scope specifier, the
1494 // lexical context will be different from the semantic context.
1495 New->setLexicalDeclContext(CurContext);
1496
Chris Lattner4b009652007-07-25 00:24:17 +00001497 // If this has an identifier, add it to the scope stack.
Douglas Gregor6704b312008-11-17 22:58:34 +00001498 if (Name)
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00001499 PushOnScopeChains(New, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00001500 // If any semantic error occurred, mark the decl as invalid.
1501 if (D.getInvalidType() || InvalidDecl)
1502 New->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00001503
1504 return New;
1505}
1506
Steve Narofffc08f5e2008-10-27 11:34:16 +00001507void Sema::InitializerElementNotConstant(const Expr *Init) {
Chris Lattner9d2cf082008-11-19 05:27:50 +00001508 Diag(Init->getExprLoc(), diag::err_init_element_not_constant)
1509 << Init->getSourceRange();
Steve Narofffc08f5e2008-10-27 11:34:16 +00001510}
1511
Eli Friedman02c22ce2008-05-20 13:48:25 +00001512bool Sema::CheckAddressConstantExpressionLValue(const Expr* Init) {
1513 switch (Init->getStmtClass()) {
1514 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001515 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001516 return true;
1517 case Expr::ParenExprClass: {
1518 const ParenExpr* PE = cast<ParenExpr>(Init);
1519 return CheckAddressConstantExpressionLValue(PE->getSubExpr());
1520 }
1521 case Expr::CompoundLiteralExprClass:
1522 return cast<CompoundLiteralExpr>(Init)->isFileScope();
1523 case Expr::DeclRefExprClass: {
1524 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
Eli Friedman8cb86e32008-05-21 03:39:11 +00001525 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
1526 if (VD->hasGlobalStorage())
1527 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001528 InitializerElementNotConstant(Init);
Eli Friedman8cb86e32008-05-21 03:39:11 +00001529 return true;
1530 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001531 if (isa<FunctionDecl>(D))
1532 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001533 InitializerElementNotConstant(Init);
Steve Narofff0b23542008-01-10 22:15:12 +00001534 return true;
1535 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001536 case Expr::MemberExprClass: {
1537 const MemberExpr *M = cast<MemberExpr>(Init);
1538 if (M->isArrow())
1539 return CheckAddressConstantExpression(M->getBase());
1540 return CheckAddressConstantExpressionLValue(M->getBase());
1541 }
1542 case Expr::ArraySubscriptExprClass: {
1543 // FIXME: Should we pedwarn for "x[0+0]" (where x is a pointer)?
1544 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(Init);
1545 return CheckAddressConstantExpression(ASE->getBase()) ||
1546 CheckArithmeticConstantExpression(ASE->getIdx());
1547 }
1548 case Expr::StringLiteralClass:
Chris Lattner69909292008-08-10 01:53:14 +00001549 case Expr::PredefinedExprClass:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001550 return false;
1551 case Expr::UnaryOperatorClass: {
1552 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1553
1554 // C99 6.6p9
1555 if (Exp->getOpcode() == UnaryOperator::Deref)
Eli Friedman8cb86e32008-05-21 03:39:11 +00001556 return CheckAddressConstantExpression(Exp->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001557
Steve Narofffc08f5e2008-10-27 11:34:16 +00001558 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001559 return true;
1560 }
1561 }
1562}
1563
1564bool Sema::CheckAddressConstantExpression(const Expr* Init) {
1565 switch (Init->getStmtClass()) {
1566 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001567 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001568 return true;
Chris Lattner0903cba2008-10-06 07:26:43 +00001569 case Expr::ParenExprClass:
1570 return CheckAddressConstantExpression(cast<ParenExpr>(Init)->getSubExpr());
Eli Friedman02c22ce2008-05-20 13:48:25 +00001571 case Expr::StringLiteralClass:
1572 case Expr::ObjCStringLiteralClass:
1573 return false;
Chris Lattner0903cba2008-10-06 07:26:43 +00001574 case Expr::CallExprClass:
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001575 case Expr::CXXOperatorCallExprClass:
Chris Lattner0903cba2008-10-06 07:26:43 +00001576 // __builtin___CFStringMakeConstantString is a valid constant l-value.
1577 if (cast<CallExpr>(Init)->isBuiltinCall() ==
1578 Builtin::BI__builtin___CFStringMakeConstantString)
1579 return false;
1580
Steve Narofffc08f5e2008-10-27 11:34:16 +00001581 InitializerElementNotConstant(Init);
Chris Lattner0903cba2008-10-06 07:26:43 +00001582 return true;
1583
Eli Friedman02c22ce2008-05-20 13:48:25 +00001584 case Expr::UnaryOperatorClass: {
1585 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1586
1587 // C99 6.6p9
1588 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1589 return CheckAddressConstantExpressionLValue(Exp->getSubExpr());
1590
1591 if (Exp->getOpcode() == UnaryOperator::Extension)
1592 return CheckAddressConstantExpression(Exp->getSubExpr());
1593
Steve Narofffc08f5e2008-10-27 11:34:16 +00001594 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001595 return true;
1596 }
1597 case Expr::BinaryOperatorClass: {
1598 // FIXME: Should we pedwarn for expressions like "a + 1 + 2"?
1599 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1600
1601 Expr *PExp = Exp->getLHS();
1602 Expr *IExp = Exp->getRHS();
1603 if (IExp->getType()->isPointerType())
1604 std::swap(PExp, IExp);
1605
1606 // FIXME: Should we pedwarn if IExp isn't an integer constant expression?
1607 return CheckAddressConstantExpression(PExp) ||
1608 CheckArithmeticConstantExpression(IExp);
1609 }
Eli Friedman1fad3c62008-08-25 20:46:57 +00001610 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001611 case Expr::CStyleCastExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001612 const Expr* SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedman1fad3c62008-08-25 20:46:57 +00001613 if (Init->getStmtClass() == Expr::ImplicitCastExprClass) {
1614 // Check for implicit promotion
1615 if (SubExpr->getType()->isFunctionType() ||
1616 SubExpr->getType()->isArrayType())
1617 return CheckAddressConstantExpressionLValue(SubExpr);
1618 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001619
1620 // Check for pointer->pointer cast
1621 if (SubExpr->getType()->isPointerType())
1622 return CheckAddressConstantExpression(SubExpr);
1623
Eli Friedman1fad3c62008-08-25 20:46:57 +00001624 if (SubExpr->getType()->isIntegralType()) {
1625 // Check for the special-case of a pointer->int->pointer cast;
1626 // this isn't standard, but some code requires it. See
1627 // PR2720 for an example.
1628 if (const CastExpr* SubCast = dyn_cast<CastExpr>(SubExpr)) {
1629 if (SubCast->getSubExpr()->getType()->isPointerType()) {
1630 unsigned IntWidth = Context.getIntWidth(SubCast->getType());
1631 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1632 if (IntWidth >= PointerWidth) {
1633 return CheckAddressConstantExpression(SubCast->getSubExpr());
1634 }
1635 }
1636 }
1637 }
1638 if (SubExpr->getType()->isArithmeticType()) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001639 return CheckArithmeticConstantExpression(SubExpr);
Eli Friedman1fad3c62008-08-25 20:46:57 +00001640 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001641
Steve Narofffc08f5e2008-10-27 11:34:16 +00001642 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001643 return true;
1644 }
1645 case Expr::ConditionalOperatorClass: {
1646 // FIXME: Should we pedwarn here?
1647 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
1648 if (!Exp->getCond()->getType()->isArithmeticType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001649 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001650 return true;
1651 }
1652 if (CheckArithmeticConstantExpression(Exp->getCond()))
1653 return true;
1654 if (Exp->getLHS() &&
1655 CheckAddressConstantExpression(Exp->getLHS()))
1656 return true;
1657 return CheckAddressConstantExpression(Exp->getRHS());
1658 }
1659 case Expr::AddrLabelExprClass:
1660 return false;
1661 }
1662}
1663
Eli Friedman998dffb2008-06-09 05:05:07 +00001664static const Expr* FindExpressionBaseAddress(const Expr* E);
1665
1666static const Expr* FindExpressionBaseAddressLValue(const Expr* E) {
1667 switch (E->getStmtClass()) {
1668 default:
1669 return E;
1670 case Expr::ParenExprClass: {
1671 const ParenExpr* PE = cast<ParenExpr>(E);
1672 return FindExpressionBaseAddressLValue(PE->getSubExpr());
1673 }
1674 case Expr::MemberExprClass: {
1675 const MemberExpr *M = cast<MemberExpr>(E);
1676 if (M->isArrow())
1677 return FindExpressionBaseAddress(M->getBase());
1678 return FindExpressionBaseAddressLValue(M->getBase());
1679 }
1680 case Expr::ArraySubscriptExprClass: {
1681 const ArraySubscriptExpr *ASE = cast<ArraySubscriptExpr>(E);
1682 return FindExpressionBaseAddress(ASE->getBase());
1683 }
1684 case Expr::UnaryOperatorClass: {
1685 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1686
1687 if (Exp->getOpcode() == UnaryOperator::Deref)
1688 return FindExpressionBaseAddress(Exp->getSubExpr());
1689
1690 return E;
1691 }
1692 }
1693}
1694
1695static const Expr* FindExpressionBaseAddress(const Expr* E) {
1696 switch (E->getStmtClass()) {
1697 default:
1698 return E;
1699 case Expr::ParenExprClass: {
1700 const ParenExpr* PE = cast<ParenExpr>(E);
1701 return FindExpressionBaseAddress(PE->getSubExpr());
1702 }
1703 case Expr::UnaryOperatorClass: {
1704 const UnaryOperator *Exp = cast<UnaryOperator>(E);
1705
1706 // C99 6.6p9
1707 if (Exp->getOpcode() == UnaryOperator::AddrOf)
1708 return FindExpressionBaseAddressLValue(Exp->getSubExpr());
1709
1710 if (Exp->getOpcode() == UnaryOperator::Extension)
1711 return FindExpressionBaseAddress(Exp->getSubExpr());
1712
1713 return E;
1714 }
1715 case Expr::BinaryOperatorClass: {
1716 const BinaryOperator *Exp = cast<BinaryOperator>(E);
1717
1718 Expr *PExp = Exp->getLHS();
1719 Expr *IExp = Exp->getRHS();
1720 if (IExp->getType()->isPointerType())
1721 std::swap(PExp, IExp);
1722
1723 return FindExpressionBaseAddress(PExp);
1724 }
1725 case Expr::ImplicitCastExprClass: {
1726 const Expr* SubExpr = cast<ImplicitCastExpr>(E)->getSubExpr();
1727
1728 // Check for implicit promotion
1729 if (SubExpr->getType()->isFunctionType() ||
1730 SubExpr->getType()->isArrayType())
1731 return FindExpressionBaseAddressLValue(SubExpr);
1732
1733 // Check for pointer->pointer cast
1734 if (SubExpr->getType()->isPointerType())
1735 return FindExpressionBaseAddress(SubExpr);
1736
1737 // We assume that we have an arithmetic expression here;
1738 // if we don't, we'll figure it out later
1739 return 0;
1740 }
Douglas Gregor035d0882008-10-28 15:36:24 +00001741 case Expr::CStyleCastExprClass: {
Eli Friedman998dffb2008-06-09 05:05:07 +00001742 const Expr* SubExpr = cast<CastExpr>(E)->getSubExpr();
1743
1744 // Check for pointer->pointer cast
1745 if (SubExpr->getType()->isPointerType())
1746 return FindExpressionBaseAddress(SubExpr);
1747
1748 // We assume that we have an arithmetic expression here;
1749 // if we don't, we'll figure it out later
1750 return 0;
1751 }
1752 }
1753}
1754
Anders Carlssone8bd9f22008-11-22 21:04:56 +00001755bool Sema::CheckArithmeticConstantExpression(const Expr* Init) {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001756 switch (Init->getStmtClass()) {
1757 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001758 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001759 return true;
1760 case Expr::ParenExprClass: {
1761 const ParenExpr* PE = cast<ParenExpr>(Init);
1762 return CheckArithmeticConstantExpression(PE->getSubExpr());
1763 }
1764 case Expr::FloatingLiteralClass:
1765 case Expr::IntegerLiteralClass:
1766 case Expr::CharacterLiteralClass:
1767 case Expr::ImaginaryLiteralClass:
1768 case Expr::TypesCompatibleExprClass:
1769 case Expr::CXXBoolLiteralExprClass:
1770 return false;
Douglas Gregor65fedaf2008-11-14 16:09:21 +00001771 case Expr::CallExprClass:
1772 case Expr::CXXOperatorCallExprClass: {
Eli Friedman02c22ce2008-05-20 13:48:25 +00001773 const CallExpr *CE = cast<CallExpr>(Init);
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001774
1775 // Allow any constant foldable calls to builtins.
1776 if (CE->isBuiltinCall() && CE->isEvaluatable(Context))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001777 return false;
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001778
Steve Narofffc08f5e2008-10-27 11:34:16 +00001779 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001780 return true;
1781 }
1782 case Expr::DeclRefExprClass: {
1783 const Decl *D = cast<DeclRefExpr>(Init)->getDecl();
1784 if (isa<EnumConstantDecl>(D))
1785 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001786 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001787 return true;
1788 }
1789 case Expr::CompoundLiteralExprClass:
1790 // Allow "(vector type){2,4}"; normal C constraints don't allow this,
1791 // but vectors are allowed to be magic.
1792 if (Init->getType()->isVectorType())
1793 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001794 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001795 return true;
1796 case Expr::UnaryOperatorClass: {
1797 const UnaryOperator *Exp = cast<UnaryOperator>(Init);
1798
1799 switch (Exp->getOpcode()) {
1800 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
1801 // See C99 6.6p3.
1802 default:
Steve Narofffc08f5e2008-10-27 11:34:16 +00001803 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001804 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001805 case UnaryOperator::OffsetOf:
Eli Friedman02c22ce2008-05-20 13:48:25 +00001806 if (Exp->getSubExpr()->getType()->isConstantSizeType())
1807 return false;
Steve Narofffc08f5e2008-10-27 11:34:16 +00001808 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001809 return true;
1810 case UnaryOperator::Extension:
1811 case UnaryOperator::LNot:
1812 case UnaryOperator::Plus:
1813 case UnaryOperator::Minus:
1814 case UnaryOperator::Not:
1815 return CheckArithmeticConstantExpression(Exp->getSubExpr());
1816 }
1817 }
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001818 case Expr::SizeOfAlignOfExprClass: {
1819 const SizeOfAlignOfExpr *Exp = cast<SizeOfAlignOfExpr>(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001820 // Special check for void types, which are allowed as an extension
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001821 if (Exp->getTypeOfArgument()->isVoidType())
Eli Friedman02c22ce2008-05-20 13:48:25 +00001822 return false;
1823 // alignof always evaluates to a constant.
1824 // FIXME: is sizeof(int[3.0]) a constant expression?
Sebastian Redl0cb7c872008-11-11 17:56:53 +00001825 if (Exp->isSizeOf() && !Exp->getTypeOfArgument()->isConstantSizeType()) {
Steve Narofffc08f5e2008-10-27 11:34:16 +00001826 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001827 return true;
1828 }
1829 return false;
1830 }
1831 case Expr::BinaryOperatorClass: {
1832 const BinaryOperator *Exp = cast<BinaryOperator>(Init);
1833
1834 if (Exp->getLHS()->getType()->isArithmeticType() &&
1835 Exp->getRHS()->getType()->isArithmeticType()) {
1836 return CheckArithmeticConstantExpression(Exp->getLHS()) ||
1837 CheckArithmeticConstantExpression(Exp->getRHS());
1838 }
1839
Eli Friedman998dffb2008-06-09 05:05:07 +00001840 if (Exp->getLHS()->getType()->isPointerType() &&
1841 Exp->getRHS()->getType()->isPointerType()) {
1842 const Expr* LHSBase = FindExpressionBaseAddress(Exp->getLHS());
1843 const Expr* RHSBase = FindExpressionBaseAddress(Exp->getRHS());
1844
1845 // Only allow a null (constant integer) base; we could
1846 // allow some additional cases if necessary, but this
1847 // is sufficient to cover offsetof-like constructs.
1848 if (!LHSBase && !RHSBase) {
1849 return CheckAddressConstantExpression(Exp->getLHS()) ||
1850 CheckAddressConstantExpression(Exp->getRHS());
1851 }
1852 }
1853
Steve Narofffc08f5e2008-10-27 11:34:16 +00001854 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00001855 return true;
1856 }
1857 case Expr::ImplicitCastExprClass:
Douglas Gregor035d0882008-10-28 15:36:24 +00001858 case Expr::CStyleCastExprClass: {
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001859 const Expr *SubExpr = cast<CastExpr>(Init)->getSubExpr();
Eli Friedmand662caa2008-09-01 22:08:17 +00001860 if (SubExpr->getType()->isArithmeticType())
1861 return CheckArithmeticConstantExpression(SubExpr);
1862
Eli Friedman266df142008-09-02 09:37:00 +00001863 if (SubExpr->getType()->isPointerType()) {
1864 const Expr* Base = FindExpressionBaseAddress(SubExpr);
1865 // If the pointer has a null base, this is an offsetof-like construct
1866 if (!Base)
1867 return CheckAddressConstantExpression(SubExpr);
1868 }
1869
Steve Narofffc08f5e2008-10-27 11:34:16 +00001870 InitializerElementNotConstant(Init);
Eli Friedmand662caa2008-09-01 22:08:17 +00001871 return true;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001872 }
1873 case Expr::ConditionalOperatorClass: {
1874 const ConditionalOperator *Exp = cast<ConditionalOperator>(Init);
Chris Lattner94d45412008-10-06 05:42:39 +00001875
1876 // If GNU extensions are disabled, we require all operands to be arithmetic
1877 // constant expressions.
1878 if (getLangOptions().NoExtensions) {
1879 return CheckArithmeticConstantExpression(Exp->getCond()) ||
1880 (Exp->getLHS() && CheckArithmeticConstantExpression(Exp->getLHS())) ||
1881 CheckArithmeticConstantExpression(Exp->getRHS());
1882 }
1883
1884 // Otherwise, we have to emulate some of the behavior of fold here.
1885 // Basically GCC treats things like "4 ? 1 : somefunc()" as a constant
1886 // because it can constant fold things away. To retain compatibility with
1887 // GCC code, we see if we can fold the condition to a constant (which we
1888 // should always be able to do in theory). If so, we only require the
1889 // specified arm of the conditional to be a constant. This is a horrible
1890 // hack, but is require by real world code that uses __builtin_constant_p.
Anders Carlsson8c3de802008-12-19 20:58:05 +00001891 Expr::EvalResult EvalResult;
1892 if (!Exp->getCond()->Evaluate(EvalResult, Context) ||
1893 EvalResult.HasSideEffects) {
Chris Lattneref069662008-11-16 21:24:15 +00001894 // If Evaluate couldn't fold it, CheckArithmeticConstantExpression
Chris Lattner94d45412008-10-06 05:42:39 +00001895 // won't be able to either. Use it to emit the diagnostic though.
1896 bool Res = CheckArithmeticConstantExpression(Exp->getCond());
Chris Lattneref069662008-11-16 21:24:15 +00001897 assert(Res && "Evaluate couldn't evaluate this constant?");
Chris Lattner94d45412008-10-06 05:42:39 +00001898 return Res;
1899 }
1900
1901 // Verify that the side following the condition is also a constant.
1902 const Expr *TrueSide = Exp->getLHS(), *FalseSide = Exp->getRHS();
Anders Carlsson8c3de802008-12-19 20:58:05 +00001903 if (EvalResult.Val.getInt() == 0)
Chris Lattner94d45412008-10-06 05:42:39 +00001904 std::swap(TrueSide, FalseSide);
1905
1906 if (TrueSide && CheckArithmeticConstantExpression(TrueSide))
Eli Friedman02c22ce2008-05-20 13:48:25 +00001907 return true;
Chris Lattner94d45412008-10-06 05:42:39 +00001908
1909 // Okay, the evaluated side evaluates to a constant, so we accept this.
1910 // Check to see if the other side is obviously not a constant. If so,
1911 // emit a warning that this is a GNU extension.
Chris Lattner2d9a3f62008-10-06 06:49:02 +00001912 if (FalseSide && !FalseSide->isEvaluatable(Context))
Chris Lattner94d45412008-10-06 05:42:39 +00001913 Diag(Init->getExprLoc(),
Chris Lattner9d2cf082008-11-19 05:27:50 +00001914 diag::ext_typecheck_expression_not_constant_but_accepted)
1915 << FalseSide->getSourceRange();
Chris Lattner94d45412008-10-06 05:42:39 +00001916 return false;
Eli Friedman02c22ce2008-05-20 13:48:25 +00001917 }
1918 }
1919}
1920
1921bool Sema::CheckForConstantInitializer(Expr *Init, QualType DclT) {
Anders Carlssonf6791c62008-12-05 05:09:56 +00001922 Expr::EvalResult Result;
1923
Nuno Lopese7280452008-07-07 16:46:50 +00001924 Init = Init->IgnoreParens();
1925
Anders Carlssonf6791c62008-12-05 05:09:56 +00001926 if (Init->Evaluate(Result, Context) && !Result.HasSideEffects)
1927 return false;
1928
Eli Friedman02c22ce2008-05-20 13:48:25 +00001929 // Look through CXXDefaultArgExprs; they have no meaning in this context.
1930 if (CXXDefaultArgExpr* DAE = dyn_cast<CXXDefaultArgExpr>(Init))
1931 return CheckForConstantInitializer(DAE->getExpr(), DclT);
1932
Nuno Lopese7280452008-07-07 16:46:50 +00001933 if (CompoundLiteralExpr *e = dyn_cast<CompoundLiteralExpr>(Init))
1934 return CheckForConstantInitializer(e->getInitializer(), DclT);
1935
Eli Friedman02c22ce2008-05-20 13:48:25 +00001936 if (InitListExpr *Exp = dyn_cast<InitListExpr>(Init)) {
1937 unsigned numInits = Exp->getNumInits();
1938 for (unsigned i = 0; i < numInits; i++) {
1939 // FIXME: Need to get the type of the declaration for C++,
1940 // because it could be a reference?
1941 if (CheckForConstantInitializer(Exp->getInit(i),
1942 Exp->getInit(i)->getType()))
1943 return true;
1944 }
1945 return false;
1946 }
1947
Anders Carlssonf6791c62008-12-05 05:09:56 +00001948 // FIXME: We can probably remove some of this code below, now that
1949 // Expr::Evaluate is doing the heavy lifting for scalars.
1950
Eli Friedman02c22ce2008-05-20 13:48:25 +00001951 if (Init->isNullPointerConstant(Context))
1952 return false;
1953 if (Init->getType()->isArithmeticType()) {
Chris Lattnerd5a56aa2008-07-26 22:17:49 +00001954 QualType InitTy = Context.getCanonicalType(Init->getType())
1955 .getUnqualifiedType();
Eli Friedman25086f02008-05-30 18:14:48 +00001956 if (InitTy == Context.BoolTy) {
1957 // Special handling for pointers implicitly cast to bool;
1958 // (e.g. "_Bool rr = &rr;"). This is only legal at the top level.
1959 if (ImplicitCastExpr* ICE = dyn_cast<ImplicitCastExpr>(Init)) {
1960 Expr* SubE = ICE->getSubExpr();
1961 if (SubE->getType()->isPointerType() ||
1962 SubE->getType()->isArrayType() ||
1963 SubE->getType()->isFunctionType()) {
1964 return CheckAddressConstantExpression(Init);
1965 }
1966 }
1967 } else if (InitTy->isIntegralType()) {
1968 Expr* SubE = 0;
Argiris Kirtzidisc45e2fb2008-08-18 23:01:59 +00001969 if (CastExpr* CE = dyn_cast<CastExpr>(Init))
Eli Friedman25086f02008-05-30 18:14:48 +00001970 SubE = CE->getSubExpr();
1971 // Special check for pointer cast to int; we allow as an extension
1972 // an address constant cast to an integer if the integer
1973 // is of an appropriate width (this sort of code is apparently used
1974 // in some places).
1975 // FIXME: Add pedwarn?
1976 // FIXME: Don't allow bitfields here! Need the FieldDecl for that.
1977 if (SubE && (SubE->getType()->isPointerType() ||
1978 SubE->getType()->isArrayType() ||
1979 SubE->getType()->isFunctionType())) {
1980 unsigned IntWidth = Context.getTypeSize(Init->getType());
1981 unsigned PointerWidth = Context.getTypeSize(Context.VoidPtrTy);
1982 if (IntWidth >= PointerWidth)
1983 return CheckAddressConstantExpression(Init);
1984 }
Eli Friedman02c22ce2008-05-20 13:48:25 +00001985 }
1986
1987 return CheckArithmeticConstantExpression(Init);
1988 }
1989
1990 if (Init->getType()->isPointerType())
1991 return CheckAddressConstantExpression(Init);
1992
Eli Friedman25086f02008-05-30 18:14:48 +00001993 // An array type at the top level that isn't an init-list must
1994 // be a string literal
Eli Friedman02c22ce2008-05-20 13:48:25 +00001995 if (Init->getType()->isArrayType())
1996 return false;
1997
Nuno Lopes1dc26762008-09-01 18:42:41 +00001998 if (Init->getType()->isFunctionType())
1999 return false;
2000
Steve Naroffdff3fb22008-10-02 17:12:56 +00002001 // Allow block exprs at top level.
2002 if (Init->getType()->isBlockPointerType())
2003 return false;
2004
Steve Narofffc08f5e2008-10-27 11:34:16 +00002005 InitializerElementNotConstant(Init);
Eli Friedman02c22ce2008-05-20 13:48:25 +00002006 return true;
Steve Narofff0b23542008-01-10 22:15:12 +00002007}
2008
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002009void Sema::AddInitializerToDecl(DeclTy *dcl, ExprArg init) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002010 Decl *RealDecl = static_cast<Decl *>(dcl);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002011 Expr *Init = static_cast<Expr *>(init.release());
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002012 assert(Init && "missing initializer");
Steve Naroff6a0e2092007-09-12 14:07:44 +00002013
Chris Lattnerf31a2fb2007-10-19 20:10:30 +00002014 // If there is no declaration, there was an error parsing it. Just ignore
2015 // the initializer.
2016 if (RealDecl == 0) {
2017 delete Init;
2018 return;
2019 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002020
Steve Naroff420d0f52007-09-12 20:13:48 +00002021 VarDecl *VDecl = dyn_cast<VarDecl>(RealDecl);
2022 if (!VDecl) {
Steve Naroffcb597472007-09-13 21:41:19 +00002023 Diag(dyn_cast<ScopedDecl>(RealDecl)->getLocation(),
2024 diag::err_illegal_initializer);
Steve Naroff420d0f52007-09-12 20:13:48 +00002025 RealDecl->setInvalidDecl();
2026 return;
2027 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002028 // Get the decls type and save a reference for later, since
Steve Narofff0b23542008-01-10 22:15:12 +00002029 // CheckInitializerTypes may change it.
Steve Naroff420d0f52007-09-12 20:13:48 +00002030 QualType DclT = VDecl->getType(), SavT = DclT;
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002031 if (VDecl->isBlockVarDecl()) {
2032 VarDecl::StorageClass SC = VDecl->getStorageClass();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002033 if (SC == VarDecl::Extern) { // C99 6.7.8p5
Steve Naroff420d0f52007-09-12 20:13:48 +00002034 Diag(VDecl->getLocation(), diag::err_block_extern_cant_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002035 VDecl->setInvalidDecl();
2036 } else if (!VDecl->isInvalidDecl()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002037 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002038 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002039 VDecl->setInvalidDecl();
Anders Carlssonea7140a2008-08-22 05:00:02 +00002040
2041 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2042 if (!getLangOptions().CPlusPlus) {
2043 if (SC == VarDecl::Static) // C99 6.7.8p4.
2044 CheckForConstantInitializer(Init, DclT);
2045 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002046 }
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002047 } else if (VDecl->isFileVarDecl()) {
2048 if (VDecl->getStorageClass() == VarDecl::Extern)
Steve Naroff420d0f52007-09-12 20:13:48 +00002049 Diag(VDecl->getLocation(), diag::warn_extern_init);
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002050 if (!VDecl->isInvalidDecl())
Douglas Gregor6428e762008-11-05 15:29:30 +00002051 if (CheckInitializerTypes(Init, DclT, VDecl->getLocation(),
Chris Lattner271d4c22008-11-24 05:29:24 +00002052 VDecl->getDeclName()))
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002053 VDecl->setInvalidDecl();
Steve Narofff0b23542008-01-10 22:15:12 +00002054
Anders Carlssonea7140a2008-08-22 05:00:02 +00002055 // C++ 3.6.2p2, allow dynamic initialization of static initializers.
2056 if (!getLangOptions().CPlusPlus) {
2057 // C99 6.7.8p4. All file scoped initializers need to be constant.
2058 CheckForConstantInitializer(Init, DclT);
2059 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002060 }
2061 // If the type changed, it means we had an incomplete type that was
2062 // completed by the initializer. For example:
2063 // int ary[] = { 1, 3, 5 };
2064 // "ary" transitions from a VariableArrayType to a ConstantArrayType.
Christopher Lamb62f06b62007-11-29 19:09:19 +00002065 if (!VDecl->isInvalidDecl() && (DclT != SavT)) {
Steve Naroff420d0f52007-09-12 20:13:48 +00002066 VDecl->setType(DclT);
Christopher Lamb62f06b62007-11-29 19:09:19 +00002067 Init->setType(DclT);
2068 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002069
2070 // Attach the initializer to the decl.
Steve Naroff420d0f52007-09-12 20:13:48 +00002071 VDecl->setInit(Init);
Steve Naroff6a0e2092007-09-12 14:07:44 +00002072 return;
2073}
2074
Douglas Gregor81c29152008-10-29 00:13:59 +00002075void Sema::ActOnUninitializedDecl(DeclTy *dcl) {
2076 Decl *RealDecl = static_cast<Decl *>(dcl);
2077
Argiris Kirtzidis9c0e9942008-11-07 13:01:22 +00002078 // If there is no declaration, there was an error parsing it. Just ignore it.
2079 if (RealDecl == 0)
2080 return;
2081
Douglas Gregor81c29152008-10-29 00:13:59 +00002082 if (VarDecl *Var = dyn_cast<VarDecl>(RealDecl)) {
2083 QualType Type = Var->getType();
2084 // C++ [dcl.init.ref]p3:
2085 // The initializer can be omitted for a reference only in a
2086 // parameter declaration (8.3.5), in the declaration of a
2087 // function return type, in the declaration of a class member
2088 // within its class declaration (9.2), and where the extern
2089 // specifier is explicitly used.
Douglas Gregorb9213832008-12-15 21:24:18 +00002090 if (Type->isReferenceType() &&
2091 Var->getStorageClass() != VarDecl::Extern &&
2092 Var->getStorageClass() != VarDecl::PrivateExtern) {
Chris Lattner77d52da2008-11-20 06:06:08 +00002093 Diag(Var->getLocation(), diag::err_reference_var_requires_init)
Chris Lattner271d4c22008-11-24 05:29:24 +00002094 << Var->getDeclName()
2095 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregor5870a952008-11-03 20:45:27 +00002096 Var->setInvalidDecl();
2097 return;
2098 }
2099
2100 // C++ [dcl.init]p9:
2101 //
2102 // If no initializer is specified for an object, and the object
2103 // is of (possibly cv-qualified) non-POD class type (or array
2104 // thereof), the object shall be default-initialized; if the
2105 // object is of const-qualified type, the underlying class type
2106 // shall have a user-declared default constructor.
2107 if (getLangOptions().CPlusPlus) {
2108 QualType InitType = Type;
2109 if (const ArrayType *Array = Context.getAsArrayType(Type))
2110 InitType = Array->getElementType();
Douglas Gregorb9213832008-12-15 21:24:18 +00002111 if (Var->getStorageClass() != VarDecl::Extern &&
2112 Var->getStorageClass() != VarDecl::PrivateExtern &&
2113 InitType->isRecordType()) {
Douglas Gregor6428e762008-11-05 15:29:30 +00002114 const CXXConstructorDecl *Constructor
2115 = PerformInitializationByConstructor(InitType, 0, 0,
2116 Var->getLocation(),
2117 SourceRange(Var->getLocation(),
2118 Var->getLocation()),
Chris Lattner271d4c22008-11-24 05:29:24 +00002119 Var->getDeclName(),
Douglas Gregor6428e762008-11-05 15:29:30 +00002120 IK_Default);
Douglas Gregor5870a952008-11-03 20:45:27 +00002121 if (!Constructor)
2122 Var->setInvalidDecl();
2123 }
2124 }
Douglas Gregor81c29152008-10-29 00:13:59 +00002125
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002126#if 0
2127 // FIXME: Temporarily disabled because we are not properly parsing
2128 // linkage specifications on declarations, e.g.,
2129 //
2130 // extern "C" const CGPoint CGPointerZero;
2131 //
Douglas Gregor81c29152008-10-29 00:13:59 +00002132 // C++ [dcl.init]p9:
2133 //
2134 // If no initializer is specified for an object, and the
2135 // object is of (possibly cv-qualified) non-POD class type (or
2136 // array thereof), the object shall be default-initialized; if
2137 // the object is of const-qualified type, the underlying class
2138 // type shall have a user-declared default
2139 // constructor. Otherwise, if no initializer is specified for
2140 // an object, the object and its subobjects, if any, have an
2141 // indeterminate initial value; if the object or any of its
2142 // subobjects are of const-qualified type, the program is
2143 // ill-formed.
2144 //
2145 // This isn't technically an error in C, so we don't diagnose it.
2146 //
2147 // FIXME: Actually perform the POD/user-defined default
2148 // constructor check.
2149 if (getLangOptions().CPlusPlus &&
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002150 Context.getCanonicalType(Type).isConstQualified() &&
2151 Var->getStorageClass() != VarDecl::Extern)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002152 Diag(Var->getLocation(), diag::err_const_var_requires_init)
2153 << Var->getName()
2154 << SourceRange(Var->getLocation(), Var->getLocation());
Douglas Gregorc0d11a82008-10-29 13:50:18 +00002155#endif
Douglas Gregor81c29152008-10-29 00:13:59 +00002156 }
2157}
2158
Chris Lattner4b009652007-07-25 00:24:17 +00002159/// The declarators are chained together backwards, reverse the list.
2160Sema::DeclTy *Sema::FinalizeDeclaratorGroup(Scope *S, DeclTy *group) {
2161 // Often we have single declarators, handle them quickly.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002162 Decl *GroupDecl = static_cast<Decl*>(group);
2163 if (GroupDecl == 0)
Steve Naroff6a0e2092007-09-12 14:07:44 +00002164 return 0;
Steve Naroff2591e1b2007-09-13 23:52:58 +00002165
2166 ScopedDecl *Group = dyn_cast<ScopedDecl>(GroupDecl);
2167 ScopedDecl *NewGroup = 0;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002168 if (Group->getNextDeclarator() == 0)
Chris Lattner4b009652007-07-25 00:24:17 +00002169 NewGroup = Group;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002170 else { // reverse the list.
2171 while (Group) {
Steve Naroff2591e1b2007-09-13 23:52:58 +00002172 ScopedDecl *Next = Group->getNextDeclarator();
Steve Naroff6a0e2092007-09-12 14:07:44 +00002173 Group->setNextDeclarator(NewGroup);
2174 NewGroup = Group;
2175 Group = Next;
2176 }
2177 }
2178 // Perform semantic analysis that depends on having fully processed both
2179 // the declarator and initializer.
Steve Naroff2591e1b2007-09-13 23:52:58 +00002180 for (ScopedDecl *ID = NewGroup; ID; ID = ID->getNextDeclarator()) {
Steve Naroff6a0e2092007-09-12 14:07:44 +00002181 VarDecl *IDecl = dyn_cast<VarDecl>(ID);
2182 if (!IDecl)
2183 continue;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002184 QualType T = IDecl->getType();
2185
Anders Carlsson68adbd12008-12-07 00:20:55 +00002186 if (T->isVariableArrayType()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002187 const VariableArrayType *VAT =
2188 cast<VariableArrayType>(T.getUnqualifiedType());
2189
2190 // FIXME: This won't give the correct result for
2191 // int a[10][n];
2192 SourceRange SizeRange = VAT->getSizeExpr()->getSourceRange();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002193 if (IDecl->isFileVarDecl()) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002194 Diag(IDecl->getLocation(), diag::err_vla_decl_in_file_scope) <<
2195 SizeRange;
2196
Eli Friedman8ff07782008-02-15 18:16:39 +00002197 IDecl->setInvalidDecl();
Anders Carlsson68adbd12008-12-07 00:20:55 +00002198 } else {
2199 // C99 6.7.5.2p2: If an identifier is declared to be an object with
2200 // static storage duration, it shall not have a variable length array.
2201 if (IDecl->getStorageClass() == VarDecl::Static) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002202 Diag(IDecl->getLocation(), diag::err_vla_decl_has_static_storage)
2203 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002204 IDecl->setInvalidDecl();
2205 } else if (IDecl->getStorageClass() == VarDecl::Extern) {
Anders Carlssonb32a1ba2008-12-07 00:49:48 +00002206 Diag(IDecl->getLocation(), diag::err_vla_decl_has_extern_linkage)
2207 << SizeRange;
Anders Carlsson68adbd12008-12-07 00:20:55 +00002208 IDecl->setInvalidDecl();
2209 }
2210 }
2211 } else if (T->isVariablyModifiedType()) {
2212 if (IDecl->isFileVarDecl()) {
2213 Diag(IDecl->getLocation(), diag::err_vm_decl_in_file_scope);
2214 IDecl->setInvalidDecl();
2215 } else {
2216 if (IDecl->getStorageClass() == VarDecl::Extern) {
2217 Diag(IDecl->getLocation(), diag::err_vm_decl_has_extern_linkage);
2218 IDecl->setInvalidDecl();
2219 }
Steve Naroff6a0e2092007-09-12 14:07:44 +00002220 }
2221 }
Anders Carlsson68adbd12008-12-07 00:20:55 +00002222
Steve Naroff6a0e2092007-09-12 14:07:44 +00002223 // Block scope. C99 6.7p7: If an identifier for an object is declared with
2224 // no linkage (C99 6.2.2p6), the type for the object shall be complete...
Steve Naroff72a6ebc2008-04-15 22:42:06 +00002225 if (IDecl->isBlockVarDecl() &&
2226 IDecl->getStorageClass() != VarDecl::Extern) {
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002227 if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Chris Lattner271d4c22008-11-24 05:29:24 +00002228 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002229 IDecl->setInvalidDecl();
2230 }
2231 }
2232 // File scope. C99 6.9.2p2: A declaration of an identifier for and
2233 // object that has file scope without an initializer, and without a
2234 // storage-class specifier or with the storage-class specifier "static",
2235 // constitutes a tentative definition. Note: A tentative definition with
2236 // external linkage is valid (C99 6.2.2p5).
Steve Naroffb5e78152008-08-08 17:50:35 +00002237 if (isTentativeDefinition(IDecl)) {
Eli Friedmane0079792008-02-15 12:53:51 +00002238 if (T->isIncompleteArrayType()) {
Steve Naroff60685462008-01-18 20:40:52 +00002239 // C99 6.9.2 (p2, p5): Implicit initialization causes an incomplete
2240 // array to be completed. Don't issue a diagnostic.
Chris Lattner67d3c8d2008-04-02 01:05:10 +00002241 } else if (T->isIncompleteType() && !IDecl->isInvalidDecl()) {
Steve Naroff60685462008-01-18 20:40:52 +00002242 // C99 6.9.2p3: If the declaration of an identifier for an object is
2243 // a tentative definition and has internal linkage (C99 6.2.2p3), the
2244 // declared type shall not be an incomplete type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002245 Diag(IDecl->getLocation(), diag::err_typecheck_decl_incomplete_type)<<T;
Steve Naroff6a0e2092007-09-12 14:07:44 +00002246 IDecl->setInvalidDecl();
2247 }
2248 }
Steve Naroffb5e78152008-08-08 17:50:35 +00002249 if (IDecl->isFileVarDecl())
2250 CheckForFileScopedRedefinitions(S, IDecl);
Chris Lattner4b009652007-07-25 00:24:17 +00002251 }
2252 return NewGroup;
2253}
Steve Naroff91b03f72007-08-28 03:03:08 +00002254
Chris Lattner3e254fb2008-04-08 04:40:51 +00002255/// ActOnParamDeclarator - Called from Parser::ParseFunctionDeclarator()
2256/// to introduce parameters into function prototype scope.
2257Sema::DeclTy *
2258Sema::ActOnParamDeclarator(Scope *S, Declarator &D) {
Chris Lattner5e77ade2008-06-26 06:49:43 +00002259 const DeclSpec &DS = D.getDeclSpec();
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002260
Chris Lattner3e254fb2008-04-08 04:40:51 +00002261 // Verify C99 6.7.5.3p2: The only SCS allowed is 'register'.
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002262 VarDecl::StorageClass StorageClass = VarDecl::None;
2263 if (DS.getStorageClassSpec() == DeclSpec::SCS_register) {
2264 StorageClass = VarDecl::Register;
2265 } else if (DS.getStorageClassSpec() != DeclSpec::SCS_unspecified) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002266 Diag(DS.getStorageClassSpecLoc(),
2267 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002268 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002269 }
2270 if (DS.isThreadSpecified()) {
2271 Diag(DS.getThreadSpecLoc(),
2272 diag::err_invalid_storage_class_in_func_decl);
Chris Lattner5e77ade2008-06-26 06:49:43 +00002273 D.getMutableDeclSpec().ClearStorageClassSpecs();
Chris Lattner3e254fb2008-04-08 04:40:51 +00002274 }
2275
Douglas Gregor2b9422f2008-05-07 04:49:29 +00002276 // Check that there are no default arguments inside the type of this
2277 // parameter (C++ only).
2278 if (getLangOptions().CPlusPlus)
2279 CheckExtraCXXDefaultArguments(D);
2280
Chris Lattner3e254fb2008-04-08 04:40:51 +00002281 // In this context, we *do not* check D.getInvalidType(). If the declarator
2282 // type was invalid, GetTypeForDeclarator() still returns a "valid" type,
2283 // though it will not reflect the user specified type.
2284 QualType parmDeclType = GetTypeForDeclarator(D, S);
2285
2286 assert(!parmDeclType.isNull() && "GetTypeForDeclarator() returned null type");
2287
Chris Lattner4b009652007-07-25 00:24:17 +00002288 // TODO: CHECK FOR CONFLICTS, multiple decls with same name in one scope.
2289 // Can this happen for params? We already checked that they don't conflict
2290 // among each other. Here they can only shadow globals, which is ok.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002291 IdentifierInfo *II = D.getIdentifier();
2292 if (Decl *PrevDecl = LookupDecl(II, Decl::IDNS_Ordinary, S)) {
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002293 if (PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002294 // Maybe we will complain about the shadowed template parameter.
2295 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
2296 // Just pretend that we didn't see the previous declaration.
2297 PrevDecl = 0;
2298 } else if (S->isDeclScope(PrevDecl)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002299 Diag(D.getIdentifierLoc(), diag::err_param_redefinition) << II;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002300
2301 // Recover by removing the name
2302 II = 0;
2303 D.SetIdentifier(0, D.getIdentifierLoc());
2304 }
Chris Lattner4b009652007-07-25 00:24:17 +00002305 }
Steve Naroff94cd93f2007-08-07 22:44:21 +00002306
2307 // Perform the default function/array conversion (C99 6.7.5.3p[7,8]).
2308 // Doing the promotion here has a win and a loss. The win is the type for
2309 // both Decl's and DeclRefExpr's will match (a convenient invariant for the
2310 // code generator). The loss is the orginal type isn't preserved. For example:
2311 //
2312 // void func(int parmvardecl[5]) { // convert "int [5]" to "int *"
2313 // int blockvardecl[5];
2314 // sizeof(parmvardecl); // size == 4
2315 // sizeof(blockvardecl); // size == 20
2316 // }
2317 //
2318 // For expressions, all implicit conversions are captured using the
2319 // ImplicitCastExpr AST node (we have no such mechanism for Decl's).
2320 //
2321 // FIXME: If a source translation tool needs to see the original type, then
2322 // we need to consider storing both types (in ParmVarDecl)...
2323 //
Chris Lattner19eb97e2008-04-02 05:18:44 +00002324 if (parmDeclType->isArrayType()) {
Chris Lattnerc08564a2008-01-02 22:50:48 +00002325 // int x[restrict 4] -> int *restrict
Chris Lattner19eb97e2008-04-02 05:18:44 +00002326 parmDeclType = Context.getArrayDecayedType(parmDeclType);
Chris Lattnerc08564a2008-01-02 22:50:48 +00002327 } else if (parmDeclType->isFunctionType())
Steve Naroff94cd93f2007-08-07 22:44:21 +00002328 parmDeclType = Context.getPointerType(parmDeclType);
Douglas Gregor8acb7272008-12-11 16:49:14 +00002329
Chris Lattner3e254fb2008-04-08 04:40:51 +00002330 ParmVarDecl *New = ParmVarDecl::Create(Context, CurContext,
2331 D.getIdentifierLoc(), II,
Daniel Dunbarb648e8c2008-09-03 21:54:21 +00002332 parmDeclType, StorageClass,
Chris Lattner3e254fb2008-04-08 04:40:51 +00002333 0, 0);
Anders Carlsson3f70c542008-02-15 07:04:12 +00002334
Chris Lattner3e254fb2008-04-08 04:40:51 +00002335 if (D.getInvalidType())
Steve Naroffcae537d2007-08-28 18:45:29 +00002336 New->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002337
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002338 // Parameter declarators cannot be qualified (C++ [dcl.meaning]p1).
2339 if (D.getCXXScopeSpec().isSet()) {
2340 Diag(D.getIdentifierLoc(), diag::err_qualified_param_declarator)
2341 << D.getCXXScopeSpec().getRange();
2342 New->setInvalidDecl();
2343 }
2344
Douglas Gregor8acb7272008-12-11 16:49:14 +00002345 // Add the parameter declaration into this scope.
2346 S->AddDecl(New);
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002347 if (II)
Douglas Gregor8acb7272008-12-11 16:49:14 +00002348 IdResolver.AddDecl(New);
Nate Begeman9f3c4bb2008-02-17 21:20:31 +00002349
Chris Lattner9b384ca2008-06-29 00:02:00 +00002350 ProcessDeclAttributes(New, D);
Chris Lattner4b009652007-07-25 00:24:17 +00002351 return New;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002352
Chris Lattner4b009652007-07-25 00:24:17 +00002353}
Fariborz Jahaniandfb1c372007-11-08 23:49:49 +00002354
Chris Lattnerea148702007-10-09 17:14:05 +00002355Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, Declarator &D) {
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002356 assert(getCurFunctionDecl() == 0 && "Function parsing confused");
Chris Lattner4b009652007-07-25 00:24:17 +00002357 assert(D.getTypeObject(0).Kind == DeclaratorChunk::Function &&
2358 "Not a function declarator!");
2359 DeclaratorChunk::FunctionTypeInfo &FTI = D.getTypeObject(0).Fun;
Chris Lattner3e254fb2008-04-08 04:40:51 +00002360
Chris Lattner4b009652007-07-25 00:24:17 +00002361 // Verify 6.9.1p6: 'every identifier in the identifier list shall be declared'
2362 // for a K&R function.
2363 if (!FTI.hasPrototype) {
2364 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i) {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002365 if (FTI.ArgInfo[i].Param == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002366 Diag(FTI.ArgInfo[i].IdentLoc, diag::ext_param_not_declared)
2367 << FTI.ArgInfo[i].Ident;
Chris Lattner4b009652007-07-25 00:24:17 +00002368 // Implicitly declare the argument as type 'int' for lack of a better
2369 // type.
Chris Lattner3e254fb2008-04-08 04:40:51 +00002370 DeclSpec DS;
2371 const char* PrevSpec; // unused
2372 DS.SetTypeSpecType(DeclSpec::TST_int, FTI.ArgInfo[i].IdentLoc,
2373 PrevSpec);
2374 Declarator ParamD(DS, Declarator::KNRTypeListContext);
2375 ParamD.SetIdentifier(FTI.ArgInfo[i].Ident, FTI.ArgInfo[i].IdentLoc);
2376 FTI.ArgInfo[i].Param = ActOnParamDeclarator(FnBodyScope, ParamD);
Chris Lattner4b009652007-07-25 00:24:17 +00002377 }
2378 }
Chris Lattner4b009652007-07-25 00:24:17 +00002379 } else {
Chris Lattner3e254fb2008-04-08 04:40:51 +00002380 // FIXME: Diagnose arguments without names in C.
Chris Lattner4b009652007-07-25 00:24:17 +00002381 }
2382
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002383 Scope *ParentScope = FnBodyScope->getParent();
Steve Naroff1d5bd642008-01-14 20:51:29 +00002384
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002385 return ActOnStartOfFunctionDef(FnBodyScope,
Douglas Gregorc5cbc242008-12-15 23:53:10 +00002386 ActOnDeclarator(ParentScope, D, 0,
2387 /*IsFunctionDefinition=*/true));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002388}
2389
2390Sema::DeclTy *Sema::ActOnStartOfFunctionDef(Scope *FnBodyScope, DeclTy *D) {
2391 Decl *decl = static_cast<Decl*>(D);
Chris Lattner2d2216b2008-02-16 01:20:36 +00002392 FunctionDecl *FD = cast<FunctionDecl>(decl);
Douglas Gregor56da7862008-10-29 15:10:40 +00002393
2394 // See if this is a redefinition.
2395 const FunctionDecl *Definition;
2396 if (FD->getBody(Definition)) {
Chris Lattnerb1753422008-11-23 21:45:46 +00002397 Diag(FD->getLocation(), diag::err_redefinition) << FD->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002398 Diag(Definition->getLocation(), diag::note_previous_definition);
Douglas Gregor56da7862008-10-29 15:10:40 +00002399 }
2400
Douglas Gregor8acb7272008-12-11 16:49:14 +00002401 PushDeclContext(FnBodyScope, FD);
Chris Lattner3e254fb2008-04-08 04:40:51 +00002402
2403 // Check the validity of our function parameters
2404 CheckParmsForFunctionDef(FD);
2405
2406 // Introduce our parameters into the function scope
2407 for (unsigned p = 0, NumParams = FD->getNumParams(); p < NumParams; ++p) {
2408 ParmVarDecl *Param = FD->getParamDecl(p);
2409 // If this has an identifier, add it to the scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002410 if (Param->getIdentifier())
2411 PushOnScopeChains(Param, FnBodyScope);
Chris Lattner4b009652007-07-25 00:24:17 +00002412 }
Chris Lattner3e254fb2008-04-08 04:40:51 +00002413
Chris Lattner4b009652007-07-25 00:24:17 +00002414 return FD;
2415}
2416
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002417Sema::DeclTy *Sema::ActOnFinishFunctionBody(DeclTy *D, StmtArg BodyArg) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002418 Decl *dcl = static_cast<Decl *>(D);
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002419 Stmt *Body = static_cast<Stmt*>(BodyArg.release());
Steve Naroff3ac43f92008-07-25 17:57:26 +00002420 if (FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(dcl)) {
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002421 FD->setBody(Body);
Argiris Kirtzidis95256e62008-06-28 06:07:14 +00002422 assert(FD == getCurFunctionDecl() && "Function parsing confused");
Steve Naroff3ac43f92008-07-25 17:57:26 +00002423 } else if (ObjCMethodDecl *MD = dyn_cast_or_null<ObjCMethodDecl>(dcl)) {
Steve Naroff99ee4302007-11-11 23:20:51 +00002424 MD->setBody((Stmt*)Body);
Steve Naroff3ac43f92008-07-25 17:57:26 +00002425 } else
2426 return 0;
Chris Lattnerf3874bc2008-04-06 04:47:34 +00002427 PopDeclContext();
Chris Lattner4b009652007-07-25 00:24:17 +00002428 // Verify and clean out per-function state.
2429
2430 // Check goto/label use.
2431 for (llvm::DenseMap<IdentifierInfo*, LabelStmt*>::iterator
2432 I = LabelMap.begin(), E = LabelMap.end(); I != E; ++I) {
2433 // Verify that we have no forward references left. If so, there was a goto
2434 // or address of a label taken, but no definition of it. Label fwd
2435 // definitions are indicated with a null substmt.
2436 if (I->second->getSubStmt() == 0) {
2437 LabelStmt *L = I->second;
2438 // Emit error.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002439 Diag(L->getIdentLoc(), diag::err_undeclared_label_use) << L->getName();
Chris Lattner4b009652007-07-25 00:24:17 +00002440
2441 // At this point, we have gotos that use the bogus label. Stitch it into
2442 // the function body so that they aren't leaked and that the AST is well
2443 // formed.
Chris Lattner83343342008-01-25 00:01:10 +00002444 if (Body) {
2445 L->setSubStmt(new NullStmt(L->getIdentLoc()));
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00002446 cast<CompoundStmt>(Body)->push_back(L);
Chris Lattner83343342008-01-25 00:01:10 +00002447 } else {
2448 // The whole function wasn't parsed correctly, just delete this.
2449 delete L;
2450 }
Chris Lattner4b009652007-07-25 00:24:17 +00002451 }
2452 }
2453 LabelMap.clear();
2454
Steve Naroff99ee4302007-11-11 23:20:51 +00002455 return D;
Fariborz Jahaniane6f59f12007-11-10 16:31:34 +00002456}
2457
Chris Lattner4b009652007-07-25 00:24:17 +00002458/// ImplicitlyDefineFunction - An undeclared identifier was used in a function
2459/// call, forming a call to an implicitly defined function (per C99 6.5.1p2).
Steve Narofff0c31dd2007-09-16 16:16:00 +00002460ScopedDecl *Sema::ImplicitlyDefineFunction(SourceLocation Loc,
2461 IdentifierInfo &II, Scope *S) {
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002462 // Extension in C99. Legal in C90, but warn about it.
2463 if (getLangOptions().C99)
Chris Lattner65cae292008-11-19 08:23:25 +00002464 Diag(Loc, diag::ext_implicit_function_decl) << &II;
Chris Lattnerdea31bf2008-05-05 21:18:06 +00002465 else
Chris Lattner65cae292008-11-19 08:23:25 +00002466 Diag(Loc, diag::warn_implicit_function_decl) << &II;
Chris Lattner4b009652007-07-25 00:24:17 +00002467
2468 // FIXME: handle stuff like:
2469 // void foo() { extern float X(); }
2470 // void bar() { X(); } <-- implicit decl for X in another scope.
2471
2472 // Set a Declarator for the implicit definition: int foo();
2473 const char *Dummy;
2474 DeclSpec DS;
2475 bool Error = DS.SetTypeSpecType(DeclSpec::TST_int, Loc, Dummy);
2476 Error = Error; // Silence warning.
2477 assert(!Error && "Error setting up implicit decl!");
2478 Declarator D(DS, Declarator::BlockContext);
Argiris Kirtzidis4b269b42008-10-24 21:46:40 +00002479 D.AddTypeInfo(DeclaratorChunk::getFunction(false, false, 0, 0, 0, Loc));
Chris Lattner4b009652007-07-25 00:24:17 +00002480 D.SetIdentifier(&II, Loc);
2481
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002482 // Insert this function into translation-unit scope.
2483
2484 DeclContext *PrevDC = CurContext;
2485 CurContext = Context.getTranslationUnitDecl();
2486
Steve Naroff9104f3c2008-04-04 14:32:09 +00002487 FunctionDecl *FD =
Daniel Dunbar72eaf8a2008-08-05 16:28:08 +00002488 dyn_cast<FunctionDecl>(static_cast<Decl*>(ActOnDeclarator(TUScope, D, 0)));
Steve Naroff9104f3c2008-04-04 14:32:09 +00002489 FD->setImplicit();
Argiris Kirtzidisbb4f7b42008-05-01 21:04:16 +00002490
2491 CurContext = PrevDC;
2492
Steve Naroff9104f3c2008-04-04 14:32:09 +00002493 return FD;
Chris Lattner4b009652007-07-25 00:24:17 +00002494}
2495
2496
Chris Lattner82bb4792007-11-14 06:34:38 +00002497TypedefDecl *Sema::ParseTypedefDecl(Scope *S, Declarator &D, QualType T,
Steve Naroff2591e1b2007-09-13 23:52:58 +00002498 ScopedDecl *LastDeclarator) {
Chris Lattner4b009652007-07-25 00:24:17 +00002499 assert(D.getIdentifier() && "Wrong callback for declspec without declarator");
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002500 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
Chris Lattner4b009652007-07-25 00:24:17 +00002501
2502 // Scope manipulation handled by caller.
Chris Lattnereee57c02008-04-04 06:12:32 +00002503 TypedefDecl *NewTD = TypedefDecl::Create(Context, CurContext,
2504 D.getIdentifierLoc(),
Chris Lattnere4650482008-03-15 06:12:44 +00002505 D.getIdentifier(),
Chris Lattner58114f02008-03-15 21:32:50 +00002506 T, LastDeclarator);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002507 if (D.getInvalidType())
2508 NewTD->setInvalidDecl();
2509 return NewTD;
Chris Lattner4b009652007-07-25 00:24:17 +00002510}
2511
Steve Naroff0acc9c92007-09-15 18:49:24 +00002512/// ActOnTag - This is invoked when we see 'struct foo' or 'struct {'. In the
Chris Lattner4b009652007-07-25 00:24:17 +00002513/// former case, Name will be non-null. In the later case, Name will be null.
2514/// TagType indicates what kind of tag this is. TK indicates whether this is a
2515/// reference/declaration/definition of a tag.
Steve Naroff0acc9c92007-09-15 18:49:24 +00002516Sema::DeclTy *Sema::ActOnTag(Scope *S, unsigned TagType, TagKind TK,
Argiris Kirtzidis311db8c2008-11-08 16:45:02 +00002517 SourceLocation KWLoc, const CXXScopeSpec &SS,
2518 IdentifierInfo *Name, SourceLocation NameLoc,
2519 AttributeList *Attr) {
Douglas Gregorae644892008-12-15 16:32:14 +00002520 // If this is not a definition, it must have a name.
Chris Lattner4b009652007-07-25 00:24:17 +00002521 assert((Name != 0 || TK == TK_Definition) &&
2522 "Nameless record must be a definition!");
2523
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002524 TagDecl::TagKind Kind;
Chris Lattner4b009652007-07-25 00:24:17 +00002525 switch (TagType) {
2526 default: assert(0 && "Unknown tag type!");
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002527 case DeclSpec::TST_struct: Kind = TagDecl::TK_struct; break;
2528 case DeclSpec::TST_union: Kind = TagDecl::TK_union; break;
2529 case DeclSpec::TST_class: Kind = TagDecl::TK_class; break;
2530 case DeclSpec::TST_enum: Kind = TagDecl::TK_enum; break;
Chris Lattner4b009652007-07-25 00:24:17 +00002531 }
2532
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002533 DeclContext *DC = CurContext;
2534 ScopedDecl *PrevDecl = 0;
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002535
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002536 if (Name && SS.isNotEmpty()) {
2537 // We have a nested-name tag ('struct foo::bar').
2538
2539 // Check for invalid 'foo::'.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002540 if (SS.isInvalid()) {
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002541 Name = 0;
2542 goto CreateNewDecl;
2543 }
2544
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002545 DC = static_cast<DeclContext*>(SS.getScopeRep());
2546 // Look-up name inside 'foo::'.
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002547 PrevDecl = dyn_cast_or_null<TagDecl>(LookupDecl(Name, Decl::IDNS_Tag,S,DC));
2548
2549 // A tag 'foo::bar' must already exist.
2550 if (PrevDecl == 0) {
Chris Lattner65cae292008-11-19 08:23:25 +00002551 Diag(NameLoc, diag::err_not_tag_in_scope) << Name << SS.getRange();
Argiris Kirtzidis70b54132008-11-09 22:09:58 +00002552 Name = 0;
2553 goto CreateNewDecl;
2554 }
2555 } else {
2556 // If this is a named struct, check to see if there was a previous forward
2557 // declaration or definition.
2558 // Use ScopedDecl instead of TagDecl, because a NamespaceDecl may come up.
2559 PrevDecl = dyn_cast_or_null<ScopedDecl>(LookupDecl(Name, Decl::IDNS_Tag,S));
2560 }
2561
Douglas Gregor2715a1f2008-12-08 18:40:42 +00002562 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00002563 // Maybe we will complain about the shadowed template parameter.
2564 DiagnoseTemplateParameterShadow(NameLoc, PrevDecl);
2565 // Just pretend that we didn't see the previous declaration.
2566 PrevDecl = 0;
2567 }
2568
Ted Kremenekd4434152008-09-02 21:26:19 +00002569 if (PrevDecl) {
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002570 assert((isa<TagDecl>(PrevDecl) || isa<NamespaceDecl>(PrevDecl)) &&
2571 "unexpected Decl type");
2572 if (TagDecl *PrevTagDecl = dyn_cast<TagDecl>(PrevDecl)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002573 // If this is a use of a previous tag, or if the tag is already declared
2574 // in the same scope (so that the definition/declaration completes or
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002575 // rementions the tag), reuse the decl.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002576 if (TK == TK_Reference || isDeclInScope(PrevDecl, DC, S)) {
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002577 // Make sure that this wasn't declared as an enum and now used as a
2578 // struct or something similar.
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002579 if (PrevTagDecl->getTagKind() != Kind) {
Chris Lattner65cae292008-11-19 08:23:25 +00002580 Diag(KWLoc, diag::err_use_with_wrong_tag) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002581 Diag(PrevDecl->getLocation(), diag::note_previous_use);
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002582 // Recover by making this an anonymous redefinition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002583 Name = 0;
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002584 PrevDecl = 0;
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002585 } else {
Douglas Gregorae644892008-12-15 16:32:14 +00002586 // If this is a use, just return the declaration we found.
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002587
Douglas Gregorae644892008-12-15 16:32:14 +00002588 // FIXME: In the future, return a variant or some other clue
2589 // for the consumer of this Decl to know it doesn't own it.
2590 // For our current ASTs this shouldn't be a problem, but will
2591 // need to be changed with DeclGroups.
2592 if (TK == TK_Reference)
Chris Lattner5bf0ad52008-07-03 03:30:58 +00002593 return PrevDecl;
Douglas Gregorae644892008-12-15 16:32:14 +00002594
2595 // Diagnose attempts to redefine a tag.
2596 if (TK == TK_Definition) {
2597 if (TagDecl *Def = PrevTagDecl->getDefinition(Context)) {
2598 Diag(NameLoc, diag::err_redefinition) << Name;
2599 Diag(Def->getLocation(), diag::note_previous_definition);
2600 // If this is a redefinition, recover by making this struct be
2601 // anonymous, which will make any later references get the previous
2602 // definition.
2603 Name = 0;
2604 PrevDecl = 0;
2605 }
2606 // Okay, this is definition of a previously declared or referenced
2607 // tag PrevDecl. We're going to create a new Decl for it.
2608 }
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002609 }
Douglas Gregorae644892008-12-15 16:32:14 +00002610 // If we get here we have (another) forward declaration or we
2611 // have a definition. Just create a new decl.
2612 } else {
2613 // If we get here, this is a definition of a new tag type in a nested
2614 // scope, e.g. "struct foo; void bar() { struct foo; }", just create a
2615 // new decl/type. We set PrevDecl to NULL so that the entities
2616 // have distinct types.
2617 PrevDecl = 0;
Chris Lattner4b009652007-07-25 00:24:17 +00002618 }
Douglas Gregorae644892008-12-15 16:32:14 +00002619 // If we get here, we're going to create a new Decl. If PrevDecl
2620 // is non-NULL, it's a definition of the tag declared by
2621 // PrevDecl. If it's NULL, we have a new definition.
Argiris Kirtzidis03e6aaf2008-04-27 13:50:30 +00002622 } else {
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002623 // PrevDecl is a namespace.
Argiris Kirtzidis5ce4db82008-11-09 22:53:32 +00002624 if (isDeclInScope(PrevDecl, DC, S)) {
Ted Kremenek40e70e72008-09-03 18:03:35 +00002625 // The tag name clashes with a namespace name, issue an error and
2626 // recover by making this tag be anonymous.
Chris Lattner65cae292008-11-19 08:23:25 +00002627 Diag(NameLoc, diag::err_redefinition_different_kind) << Name;
Chris Lattner1336cab2008-11-23 23:12:31 +00002628 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002629 Name = 0;
Douglas Gregorae644892008-12-15 16:32:14 +00002630 PrevDecl = 0;
2631 } else {
2632 // The existing declaration isn't relevant to us; we're in a
2633 // new scope, so clear out the previous declaration.
2634 PrevDecl = 0;
Argiris Kirtzidis5beb45f2008-07-16 07:45:46 +00002635 }
Chris Lattner4b009652007-07-25 00:24:17 +00002636 }
Chris Lattner4b009652007-07-25 00:24:17 +00002637 }
Argiris Kirtzidis054a2632008-11-08 17:17:31 +00002638
Chris Lattner9bb9abf2008-12-17 07:13:27 +00002639CreateNewDecl:
Chris Lattner4b009652007-07-25 00:24:17 +00002640
2641 // If there is an identifier, use the location of the identifier as the
2642 // location of the decl, otherwise use the location of the struct/union
2643 // keyword.
2644 SourceLocation Loc = NameLoc.isValid() ? NameLoc : KWLoc;
2645
Douglas Gregorae644892008-12-15 16:32:14 +00002646 // Otherwise, create a new declaration. If there is a previous
2647 // declaration of the same entity, the two will be linked via
2648 // PrevDecl.
Chris Lattner4b009652007-07-25 00:24:17 +00002649 TagDecl *New;
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002650 if (Kind == TagDecl::TK_enum) {
Chris Lattner4b009652007-07-25 00:24:17 +00002651 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2652 // enum X { A, B, C } D; D should chain to X.
Douglas Gregorae644892008-12-15 16:32:14 +00002653 New = EnumDecl::Create(Context, DC, Loc, Name,
2654 cast_or_null<EnumDecl>(PrevDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00002655 // If this is an undefined enum, warn.
2656 if (TK != TK_Definition) Diag(Loc, diag::ext_forward_ref_enum);
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002657 } else {
2658 // struct/union/class
2659
Chris Lattner4b009652007-07-25 00:24:17 +00002660 // FIXME: Tag decls should be chained to any simultaneous vardecls, e.g.:
2661 // struct X { int A; } D; D should chain to X.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002662 if (getLangOptions().CPlusPlus)
Ted Kremenek770b11d2008-09-05 17:39:33 +00002663 // FIXME: Look for a way to use RecordDecl for simple structs.
Douglas Gregorae644892008-12-15 16:32:14 +00002664 New = CXXRecordDecl::Create(Context, Kind, DC, Loc, Name,
2665 cast_or_null<CXXRecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002666 else
Douglas Gregorae644892008-12-15 16:32:14 +00002667 New = RecordDecl::Create(Context, Kind, DC, Loc, Name,
2668 cast_or_null<RecordDecl>(PrevDecl));
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002669 }
Douglas Gregorae644892008-12-15 16:32:14 +00002670
2671 if (Kind != TagDecl::TK_enum) {
2672 // Handle #pragma pack: if the #pragma pack stack has non-default
2673 // alignment, make up a packed attribute for this decl. These
2674 // attributes are checked when the ASTContext lays out the
2675 // structure.
2676 //
2677 // It is important for implementing the correct semantics that this
2678 // happen here (in act on tag decl). The #pragma pack stack is
2679 // maintained as a result of parser callbacks which can occur at
2680 // many points during the parsing of a struct declaration (because
2681 // the #pragma tokens are effectively skipped over during the
2682 // parsing of the struct).
2683 if (unsigned Alignment = PackContext.getAlignment())
2684 New->addAttr(new PackedAttr(Alignment * 8));
2685 }
2686
2687 if (Attr)
2688 ProcessDeclAttributeList(New, Attr);
2689
2690 // Set the lexical context. If the tag has a C++ scope specifier, the
2691 // lexical context will be different from the semantic context.
2692 New->setLexicalDeclContext(CurContext);
Chris Lattner4b009652007-07-25 00:24:17 +00002693
2694 // If this has an identifier, add it to the scope stack.
2695 if (Name) {
Chris Lattnera7549902007-08-26 06:24:45 +00002696 // The scope passed in may not be a decl scope. Zip up the scope tree until
2697 // we find one that is.
2698 while ((S->getFlags() & Scope::DeclScope) == 0)
2699 S = S->getParent();
2700
2701 // Add it to the decl chain.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00002702 PushOnScopeChains(New, S);
Chris Lattner4b009652007-07-25 00:24:17 +00002703 }
Argiris Kirtzidis881964b2008-11-09 23:41:00 +00002704
Chris Lattner4b009652007-07-25 00:24:17 +00002705 return New;
2706}
2707
Chris Lattner1bf58f62008-06-21 19:39:06 +00002708
Chris Lattnera73e2202008-11-12 21:17:48 +00002709/// TryToFixInvalidVariablyModifiedType - Helper method to turn variable array
2710/// types into constant array types in certain situations which would otherwise
2711/// be errors (for GCC compatibility).
2712static QualType TryToFixInvalidVariablyModifiedType(QualType T,
2713 ASTContext &Context) {
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002714 // This method tries to turn a variable array into a constant
2715 // array even when the size isn't an ICE. This is necessary
2716 // for compatibility with code that depends on gcc's buggy
2717 // constant expression folding, like struct {char x[(int)(char*)2];}
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002718 const VariableArrayType* VLATy = dyn_cast<VariableArrayType>(T);
2719 if (!VLATy) return QualType();
2720
Anders Carlsson8c3de802008-12-19 20:58:05 +00002721 Expr::EvalResult EvalResult;
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002722 if (!VLATy->getSizeExpr() ||
Anders Carlsson8c3de802008-12-19 20:58:05 +00002723 !VLATy->getSizeExpr()->Evaluate(EvalResult, Context))
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002724 return QualType();
2725
Anders Carlsson8c3de802008-12-19 20:58:05 +00002726 assert(EvalResult.Val.isInt() && "Size expressions must be integers!");
2727 llvm::APSInt &Res = EvalResult.Val.getInt();
Chris Lattnerd03be6e2008-11-12 19:48:13 +00002728 if (Res > llvm::APSInt(Res.getBitWidth(), Res.isUnsigned()))
2729 return Context.getConstantArrayType(VLATy->getElementType(),
2730 Res, ArrayType::Normal, 0);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002731 return QualType();
2732}
2733
Anders Carlsson108229a2008-12-06 20:33:04 +00002734bool Sema::VerifyBitField(SourceLocation FieldLoc, IdentifierInfo *FieldName,
Chris Lattner8464c372008-12-12 04:56:04 +00002735 QualType FieldTy, const Expr *BitWidth) {
Anders Carlsson108229a2008-12-06 20:33:04 +00002736 // FIXME: 6.7.2.1p4 - verify the field type.
2737
2738 llvm::APSInt Value;
2739 if (VerifyIntegerConstantExpression(BitWidth, &Value))
2740 return true;
2741
Chris Lattner8464c372008-12-12 04:56:04 +00002742 // Zero-width bitfield is ok for anonymous field.
2743 if (Value == 0 && FieldName)
2744 return Diag(FieldLoc, diag::err_bitfield_has_zero_width) << FieldName;
2745
2746 if (Value.isNegative())
2747 return Diag(FieldLoc, diag::err_bitfield_has_negative_width) << FieldName;
Anders Carlsson108229a2008-12-06 20:33:04 +00002748
2749 uint64_t TypeSize = Context.getTypeSize(FieldTy);
2750 // FIXME: We won't need the 0 size once we check that the field type is valid.
Chris Lattner8464c372008-12-12 04:56:04 +00002751 if (TypeSize && Value.getZExtValue() > TypeSize)
2752 return Diag(FieldLoc, diag::err_bitfield_width_exceeds_type_size)
2753 << FieldName << (unsigned)TypeSize;
Anders Carlsson108229a2008-12-06 20:33:04 +00002754
2755 return false;
2756}
2757
Steve Naroff0acc9c92007-09-15 18:49:24 +00002758/// ActOnField - Each field of a struct/union/class is passed into this in order
Chris Lattner4b009652007-07-25 00:24:17 +00002759/// to create a FieldDecl object for it.
Douglas Gregor8acb7272008-12-11 16:49:14 +00002760Sema::DeclTy *Sema::ActOnField(Scope *S, DeclTy *TagD,
Chris Lattner4b009652007-07-25 00:24:17 +00002761 SourceLocation DeclStart,
2762 Declarator &D, ExprTy *BitfieldWidth) {
2763 IdentifierInfo *II = D.getIdentifier();
2764 Expr *BitWidth = (Expr*)BitfieldWidth;
Chris Lattner4b009652007-07-25 00:24:17 +00002765 SourceLocation Loc = DeclStart;
Douglas Gregor8acb7272008-12-11 16:49:14 +00002766 RecordDecl *Record = (RecordDecl *)TagD;
Chris Lattner4b009652007-07-25 00:24:17 +00002767 if (II) Loc = D.getIdentifierLoc();
2768
2769 // FIXME: Unnamed fields can be handled in various different ways, for
2770 // example, unnamed unions inject all members into the struct namespace!
Chris Lattner4b009652007-07-25 00:24:17 +00002771
Chris Lattner4b009652007-07-25 00:24:17 +00002772 QualType T = GetTypeForDeclarator(D, S);
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002773 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2774 bool InvalidDecl = false;
Anders Carlsson108229a2008-12-06 20:33:04 +00002775
Chris Lattner4b009652007-07-25 00:24:17 +00002776 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2777 // than a variably modified type.
Eli Friedmane0079792008-02-15 12:53:51 +00002778 if (T->isVariablyModifiedType()) {
Chris Lattnera73e2202008-11-12 21:17:48 +00002779 QualType FixedTy = TryToFixInvalidVariablyModifiedType(T, Context);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002780 if (!FixedTy.isNull()) {
Chris Lattner86be8572008-11-13 18:49:38 +00002781 Diag(Loc, diag::warn_illegal_constant_array_size);
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002782 T = FixedTy;
2783 } else {
Chris Lattner86be8572008-11-13 18:49:38 +00002784 Diag(Loc, diag::err_typecheck_field_variable_size);
Chris Lattner2a884752008-11-12 19:45:49 +00002785 T = Context.IntTy;
Eli Friedman48fb3ee2008-06-03 21:01:11 +00002786 InvalidDecl = true;
2787 }
Chris Lattner4b009652007-07-25 00:24:17 +00002788 }
Anders Carlsson108229a2008-12-06 20:33:04 +00002789
2790 if (BitWidth) {
2791 if (VerifyBitField(Loc, II, T, BitWidth))
2792 InvalidDecl = true;
2793 } else {
2794 // Not a bitfield.
2795
2796 // validate II.
2797
2798 }
2799
Chris Lattner4b009652007-07-25 00:24:17 +00002800 // FIXME: Chain fielddecls together.
Argiris Kirtzidis38f16712008-07-01 10:37:29 +00002801 FieldDecl *NewFD;
2802
Douglas Gregor8acb7272008-12-11 16:49:14 +00002803 // FIXME: We don't want CurContext for C, do we? No, we'll need some
2804 // other way to determine the current RecordDecl.
2805 NewFD = FieldDecl::Create(Context, Record,
2806 Loc, II, T, BitWidth,
2807 D.getDeclSpec().getStorageClassSpec() ==
2808 DeclSpec::SCS_mutable,
2809 /*PrevDecl=*/0);
2810
Douglas Gregor605de8d2008-12-16 21:30:33 +00002811 if (getLangOptions().CPlusPlus)
2812 CheckExtraCXXDefaultArguments(D);
2813
Chris Lattner9b384ca2008-06-29 00:02:00 +00002814 ProcessDeclAttributes(NewFD, D);
Anders Carlsson136cdc32008-02-16 00:29:18 +00002815
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002816 if (D.getInvalidType() || InvalidDecl)
2817 NewFD->setInvalidDecl();
Douglas Gregor8acb7272008-12-11 16:49:14 +00002818
2819 if (II && getLangOptions().CPlusPlus)
2820 PushOnScopeChains(NewFD, S);
2821 else
2822 Record->addDecl(Context, NewFD);
2823
Steve Naroffd1ad6ae2007-08-28 20:14:24 +00002824 return NewFD;
Chris Lattner4b009652007-07-25 00:24:17 +00002825}
2826
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002827/// TranslateIvarVisibility - Translate visibility from a token ID to an
2828/// AST enum value.
Ted Kremenek42730c52008-01-07 19:49:32 +00002829static ObjCIvarDecl::AccessControl
Fariborz Jahanianbec0d562007-10-01 16:53:59 +00002830TranslateIvarVisibility(tok::ObjCKeywordKind ivarVisibility) {
Steve Naroffffeaa552007-09-14 23:09:53 +00002831 switch (ivarVisibility) {
Chris Lattner504c5432008-10-12 00:28:42 +00002832 default: assert(0 && "Unknown visitibility kind");
2833 case tok::objc_private: return ObjCIvarDecl::Private;
2834 case tok::objc_public: return ObjCIvarDecl::Public;
2835 case tok::objc_protected: return ObjCIvarDecl::Protected;
2836 case tok::objc_package: return ObjCIvarDecl::Package;
Steve Naroffffeaa552007-09-14 23:09:53 +00002837 }
2838}
2839
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002840/// ActOnIvar - Each ivar field of an objective-c class is passed into this
2841/// in order to create an IvarDecl object for it.
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002842Sema::DeclTy *Sema::ActOnIvar(Scope *S,
Fariborz Jahanian4e0bb982008-04-11 16:55:42 +00002843 SourceLocation DeclStart,
2844 Declarator &D, ExprTy *BitfieldWidth,
2845 tok::ObjCKeywordKind Visibility) {
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002846 IdentifierInfo *II = D.getIdentifier();
2847 Expr *BitWidth = (Expr*)BitfieldWidth;
2848 SourceLocation Loc = DeclStart;
2849 if (II) Loc = D.getIdentifierLoc();
2850
2851 // FIXME: Unnamed fields can be handled in various different ways, for
2852 // example, unnamed unions inject all members into the struct namespace!
2853
Anders Carlsson108229a2008-12-06 20:33:04 +00002854 QualType T = GetTypeForDeclarator(D, S);
2855 assert(!T.isNull() && "GetTypeForDeclarator() returned null type");
2856 bool InvalidDecl = false;
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002857
2858 if (BitWidth) {
2859 // TODO: Validate.
2860 //printf("WARNING: BITFIELDS IGNORED!\n");
2861
2862 // 6.7.2.1p3
2863 // 6.7.2.1p4
2864
2865 } else {
2866 // Not a bitfield.
2867
2868 // validate II.
2869
2870 }
2871
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002872 // C99 6.7.2.1p8: A member of a structure or union may have any type other
2873 // than a variably modified type.
2874 if (T->isVariablyModifiedType()) {
Anders Carlsson68adbd12008-12-07 00:20:55 +00002875 Diag(Loc, diag::err_typecheck_ivar_variable_size);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002876 InvalidDecl = true;
2877 }
2878
Ted Kremenek173dd312008-07-23 18:04:17 +00002879 // Get the visibility (access control) for this ivar.
2880 ObjCIvarDecl::AccessControl ac =
2881 Visibility != tok::objc_not_keyword ? TranslateIvarVisibility(Visibility)
2882 : ObjCIvarDecl::None;
2883
2884 // Construct the decl.
2885 ObjCIvarDecl *NewID = ObjCIvarDecl::Create(Context, Loc, II, T, ac,
Steve Naroffd3354222008-07-16 18:22:22 +00002886 (Expr *)BitfieldWidth);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002887
Ted Kremenek173dd312008-07-23 18:04:17 +00002888 // Process attributes attached to the ivar.
Chris Lattner9b384ca2008-06-29 00:02:00 +00002889 ProcessDeclAttributes(NewID, D);
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002890
2891 if (D.getInvalidType() || InvalidDecl)
2892 NewID->setInvalidDecl();
Ted Kremenek173dd312008-07-23 18:04:17 +00002893
Fariborz Jahanian751c6172008-04-10 23:32:45 +00002894 return NewID;
2895}
2896
Fariborz Jahanian0c5affb2007-09-29 00:54:24 +00002897void Sema::ActOnFields(Scope* S,
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002898 SourceLocation RecLoc, DeclTy *RecDecl,
Steve Naroff0acc9c92007-09-15 18:49:24 +00002899 DeclTy **Fields, unsigned NumFields,
Daniel Dunbarf3944442008-10-03 02:03:53 +00002900 SourceLocation LBrac, SourceLocation RBrac,
Daniel Dunbar175e6392008-10-03 17:33:35 +00002901 AttributeList *Attr) {
Steve Naroff9bb759f2007-09-14 22:20:54 +00002902 Decl *EnclosingDecl = static_cast<Decl*>(RecDecl);
2903 assert(EnclosingDecl && "missing record or interface decl");
2904 RecordDecl *Record = dyn_cast<RecordDecl>(EnclosingDecl);
2905
Ted Kremenek46a837c2008-09-05 17:16:31 +00002906 if (Record)
2907 if (RecordDecl* DefRecord = Record->getDefinition(Context)) {
2908 // Diagnose code like:
2909 // struct S { struct S {} X; };
2910 // We discover this when we complete the outer S. Reject and ignore the
2911 // outer S.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002912 Diag(DefRecord->getLocation(), diag::err_nested_redefinition)
Chris Lattner271d4c22008-11-24 05:29:24 +00002913 << DefRecord->getDeclName();
Chris Lattner1336cab2008-11-23 23:12:31 +00002914 Diag(RecLoc, diag::note_previous_definition);
Ted Kremenek46a837c2008-09-05 17:16:31 +00002915 Record->setInvalidDecl();
2916 return;
2917 }
2918
Chris Lattner4b009652007-07-25 00:24:17 +00002919 // Verify that all the fields are okay.
2920 unsigned NumNamedMembers = 0;
2921 llvm::SmallVector<FieldDecl*, 32> RecFields;
2922 llvm::SmallSet<const IdentifierInfo*, 32> FieldIDs;
Steve Naroff9bb759f2007-09-14 22:20:54 +00002923
Chris Lattner4b009652007-07-25 00:24:17 +00002924 for (unsigned i = 0; i != NumFields; ++i) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002925
Steve Naroff9bb759f2007-09-14 22:20:54 +00002926 FieldDecl *FD = cast_or_null<FieldDecl>(static_cast<Decl*>(Fields[i]));
2927 assert(FD && "missing field decl");
2928
2929 // Remember all fields.
2930 RecFields.push_back(FD);
Chris Lattner4b009652007-07-25 00:24:17 +00002931
2932 // Get the type for the field.
Chris Lattner36be3d82007-07-31 21:33:24 +00002933 Type *FDTy = FD->getType().getTypePtr();
Steve Naroffffeaa552007-09-14 23:09:53 +00002934
Chris Lattner4b009652007-07-25 00:24:17 +00002935 // C99 6.7.2.1p2 - A field may not be a function type.
Chris Lattner36be3d82007-07-31 21:33:24 +00002936 if (FDTy->isFunctionType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002937 Diag(FD->getLocation(), diag::err_field_declared_as_function)
Chris Lattner271d4c22008-11-24 05:29:24 +00002938 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002939 FD->setInvalidDecl();
2940 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002941 continue;
2942 }
Chris Lattner4b009652007-07-25 00:24:17 +00002943 // C99 6.7.2.1p2 - A field may not be an incomplete type except...
2944 if (FDTy->isIncompleteType()) {
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002945 if (!Record) { // Incomplete ivar type is always an error.
Chris Lattner271d4c22008-11-24 05:29:24 +00002946 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002947 FD->setInvalidDecl();
2948 EnclosingDecl->setInvalidDecl();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002949 continue;
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002950 }
Chris Lattner4b009652007-07-25 00:24:17 +00002951 if (i != NumFields-1 || // ... that the last member ...
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002952 !Record->isStruct() || // ... of a structure ...
Chris Lattner36be3d82007-07-31 21:33:24 +00002953 !FDTy->isArrayType()) { //... may have incomplete array type.
Chris Lattner271d4c22008-11-24 05:29:24 +00002954 Diag(FD->getLocation(), diag::err_field_incomplete) <<FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002955 FD->setInvalidDecl();
2956 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002957 continue;
2958 }
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002959 if (NumNamedMembers < 1) { //... must have more than named member ...
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002960 Diag(FD->getLocation(), diag::err_flexible_array_empty_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00002961 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002962 FD->setInvalidDecl();
2963 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002964 continue;
2965 }
Chris Lattner4b009652007-07-25 00:24:17 +00002966 // Okay, we have a legal flexible array member at the end of the struct.
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002967 if (Record)
2968 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002969 }
Chris Lattner4b009652007-07-25 00:24:17 +00002970 /// C99 6.7.2.1p2 - a struct ending in a flexible array member cannot be the
2971 /// field of another structure or the element of an array.
Chris Lattner36be3d82007-07-31 21:33:24 +00002972 if (const RecordType *FDTTy = FDTy->getAsRecordType()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002973 if (FDTTy->getDecl()->hasFlexibleArrayMember()) {
2974 // If this is a member of a union, then entire union becomes "flexible".
Argiris Kirtzidisc6cc7d52008-06-09 23:19:58 +00002975 if (Record && Record->isUnion()) {
Chris Lattner4b009652007-07-25 00:24:17 +00002976 Record->setHasFlexibleArrayMember(true);
2977 } else {
2978 // If this is a struct/class and this is not the last element, reject
2979 // it. Note that GCC supports variable sized arrays in the middle of
2980 // structures.
2981 if (i != NumFields-1) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002982 Diag(FD->getLocation(), diag::err_variable_sized_type_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00002983 << FD->getDeclName();
Steve Naroff9bb759f2007-09-14 22:20:54 +00002984 FD->setInvalidDecl();
2985 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00002986 continue;
2987 }
Chris Lattner4b009652007-07-25 00:24:17 +00002988 // We support flexible arrays at the end of structs in other structs
2989 // as an extension.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002990 Diag(FD->getLocation(), diag::ext_flexible_array_in_struct)
Chris Lattner271d4c22008-11-24 05:29:24 +00002991 << FD->getDeclName();
Fariborz Jahaniancbc36d42007-10-04 00:45:27 +00002992 if (Record)
Fariborz Jahanian023a4392007-09-14 16:27:55 +00002993 Record->setHasFlexibleArrayMember(true);
Chris Lattner4b009652007-07-25 00:24:17 +00002994 }
2995 }
2996 }
Fariborz Jahanian550e0502007-10-12 22:10:42 +00002997 /// A field cannot be an Objective-c object
Ted Kremenek42730c52008-01-07 19:49:32 +00002998 if (FDTy->isObjCInterfaceType()) {
Chris Lattner10f2c2e2008-11-20 06:38:18 +00002999 Diag(FD->getLocation(), diag::err_statically_allocated_object)
Chris Lattnerb1753422008-11-23 21:45:46 +00003000 << FD->getDeclName();
Fariborz Jahanian550e0502007-10-12 22:10:42 +00003001 FD->setInvalidDecl();
3002 EnclosingDecl->setInvalidDecl();
3003 continue;
3004 }
Chris Lattner4b009652007-07-25 00:24:17 +00003005 // Keep track of the number of named members.
3006 if (IdentifierInfo *II = FD->getIdentifier()) {
3007 // Detect duplicate member names.
3008 if (!FieldIDs.insert(II)) {
Chris Lattner65cae292008-11-19 08:23:25 +00003009 Diag(FD->getLocation(), diag::err_duplicate_member) << II;
Chris Lattner4b009652007-07-25 00:24:17 +00003010 // Find the previous decl.
3011 SourceLocation PrevLoc;
Chris Lattner504c5432008-10-12 00:28:42 +00003012 for (unsigned i = 0; ; ++i) {
3013 assert(i != RecFields.size() && "Didn't find previous def!");
Chris Lattner4b009652007-07-25 00:24:17 +00003014 if (RecFields[i]->getIdentifier() == II) {
3015 PrevLoc = RecFields[i]->getLocation();
3016 break;
3017 }
3018 }
Chris Lattner1336cab2008-11-23 23:12:31 +00003019 Diag(PrevLoc, diag::note_previous_definition);
Steve Naroff9bb759f2007-09-14 22:20:54 +00003020 FD->setInvalidDecl();
3021 EnclosingDecl->setInvalidDecl();
Chris Lattner4b009652007-07-25 00:24:17 +00003022 continue;
3023 }
3024 ++NumNamedMembers;
3025 }
Chris Lattner4b009652007-07-25 00:24:17 +00003026 }
3027
Chris Lattner4b009652007-07-25 00:24:17 +00003028 // Okay, we successfully defined 'Record'.
Chris Lattner33aad6e2008-02-06 00:51:33 +00003029 if (Record) {
Douglas Gregor8acb7272008-12-11 16:49:14 +00003030 Record->completeDefinition(Context);
Argiris Kirtzidis7c210ea2008-08-09 00:58:37 +00003031 // If this is a C++ record, HandleTagDeclDefinition will be invoked in
3032 // Sema::ActOnFinishCXXClassDef.
3033 if (!isa<CXXRecordDecl>(Record))
3034 Consumer.HandleTagDeclDefinition(Record);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003035 } else {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003036 ObjCIvarDecl **ClsFields = reinterpret_cast<ObjCIvarDecl**>(&RecFields[0]);
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003037 if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(EnclosingDecl)) {
Chris Lattner1100cfb2008-02-05 22:40:55 +00003038 ID->addInstanceVariablesToClass(ClsFields, RecFields.size(), RBrac);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003039 // Must enforce the rule that ivars in the base classes may not be
3040 // duplicates.
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003041 if (ID->getSuperClass()) {
3042 for (ObjCInterfaceDecl::ivar_iterator IVI = ID->ivar_begin(),
3043 IVE = ID->ivar_end(); IVI != IVE; ++IVI) {
3044 ObjCIvarDecl* Ivar = (*IVI);
3045 IdentifierInfo *II = Ivar->getIdentifier();
3046 ObjCIvarDecl* prevIvar = ID->getSuperClass()->FindIvarDeclaration(II);
3047 if (prevIvar) {
3048 Diag(Ivar->getLocation(), diag::err_duplicate_member) << II;
3049 Diag(prevIvar->getLocation(), diag::note_previous_definition);
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003050 }
Fariborz Jahanian2004fb62008-12-17 22:21:44 +00003051 }
Fariborz Jahanian0c067092008-12-16 01:08:35 +00003052 }
Fariborz Jahanian624921a2008-12-13 20:28:25 +00003053 }
Chris Lattner1100cfb2008-02-05 22:40:55 +00003054 else if (ObjCImplementationDecl *IMPDecl =
3055 dyn_cast<ObjCImplementationDecl>(EnclosingDecl)) {
Ted Kremenek42730c52008-01-07 19:49:32 +00003056 assert(IMPDecl && "ActOnFields - missing ObjCImplementationDecl");
3057 IMPDecl->ObjCAddInstanceVariablesToClassImpl(ClsFields, RecFields.size());
Fariborz Jahanian87093732007-10-31 18:48:14 +00003058 CheckImplementationIvars(IMPDecl, ClsFields, RecFields.size(), RBrac);
Fariborz Jahaniand34caf92007-09-26 18:27:25 +00003059 }
Fariborz Jahanianebcc9b62007-09-14 21:08:27 +00003060 }
Daniel Dunbar175e6392008-10-03 17:33:35 +00003061
3062 if (Attr)
3063 ProcessDeclAttributeList(Record, Attr);
Chris Lattner4b009652007-07-25 00:24:17 +00003064}
3065
Steve Naroff0acc9c92007-09-15 18:49:24 +00003066Sema::DeclTy *Sema::ActOnEnumConstant(Scope *S, DeclTy *theEnumDecl,
Chris Lattner4b009652007-07-25 00:24:17 +00003067 DeclTy *lastEnumConst,
3068 SourceLocation IdLoc, IdentifierInfo *Id,
3069 SourceLocation EqualLoc, ExprTy *val) {
Chris Lattnereee57c02008-04-04 06:12:32 +00003070 EnumDecl *TheEnumDecl = cast<EnumDecl>(static_cast<Decl*>(theEnumDecl));
Chris Lattner4b009652007-07-25 00:24:17 +00003071 EnumConstantDecl *LastEnumConst =
3072 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(lastEnumConst));
3073 Expr *Val = static_cast<Expr*>(val);
3074
Chris Lattnera7549902007-08-26 06:24:45 +00003075 // The scope passed in may not be a decl scope. Zip up the scope tree until
3076 // we find one that is.
3077 while ((S->getFlags() & Scope::DeclScope) == 0)
3078 S = S->getParent();
3079
Chris Lattner4b009652007-07-25 00:24:17 +00003080 // Verify that there isn't already something declared with this name in this
3081 // scope.
Douglas Gregordd861062008-12-05 18:15:24 +00003082 Decl *PrevDecl = LookupDecl(Id, Decl::IDNS_Ordinary, S);
Douglas Gregor2715a1f2008-12-08 18:40:42 +00003083 if (PrevDecl && PrevDecl->isTemplateParameter()) {
Douglas Gregordd861062008-12-05 18:15:24 +00003084 // Maybe we will complain about the shadowed template parameter.
3085 DiagnoseTemplateParameterShadow(IdLoc, PrevDecl);
3086 // Just pretend that we didn't see the previous declaration.
3087 PrevDecl = 0;
3088 }
3089
3090 if (PrevDecl) {
Argiris Kirtzidis4f071ec2008-07-16 21:01:53 +00003091 // When in C++, we may get a TagDecl with the same name; in this case the
3092 // enum constant will 'hide' the tag.
3093 assert((getLangOptions().CPlusPlus || !isa<TagDecl>(PrevDecl)) &&
3094 "Received TagDecl when not in C++!");
Argiris Kirtzidis90842b62008-09-09 21:18:04 +00003095 if (!isa<TagDecl>(PrevDecl) && isDeclInScope(PrevDecl, CurContext, S)) {
Chris Lattner4b009652007-07-25 00:24:17 +00003096 if (isa<EnumConstantDecl>(PrevDecl))
Chris Lattner65cae292008-11-19 08:23:25 +00003097 Diag(IdLoc, diag::err_redefinition_of_enumerator) << Id;
Chris Lattner4b009652007-07-25 00:24:17 +00003098 else
Chris Lattner65cae292008-11-19 08:23:25 +00003099 Diag(IdLoc, diag::err_redefinition) << Id;
Chris Lattner1336cab2008-11-23 23:12:31 +00003100 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003101 delete Val;
Chris Lattner4b009652007-07-25 00:24:17 +00003102 return 0;
3103 }
3104 }
3105
3106 llvm::APSInt EnumVal(32);
3107 QualType EltTy;
3108 if (Val) {
Chris Lattner2cda8792007-08-27 21:16:18 +00003109 // Make sure to promote the operand type to int.
3110 UsualUnaryConversions(Val);
3111
Chris Lattner4b009652007-07-25 00:24:17 +00003112 // C99 6.7.2.2p2: Make sure we have an integer constant expression.
3113 SourceLocation ExpLoc;
Anders Carlsson5374c6b2008-12-05 16:33:57 +00003114 if (VerifyIntegerConstantExpression(Val, &EnumVal)) {
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003115 delete Val;
Chris Lattnere7f53a42007-08-27 17:37:24 +00003116 Val = 0; // Just forget about it.
Chris Lattner7cea0552007-08-29 16:03:41 +00003117 } else {
3118 EltTy = Val->getType();
Chris Lattner4b009652007-07-25 00:24:17 +00003119 }
Chris Lattnere7f53a42007-08-27 17:37:24 +00003120 }
3121
3122 if (!Val) {
3123 if (LastEnumConst) {
3124 // Assign the last value + 1.
3125 EnumVal = LastEnumConst->getInitVal();
3126 ++EnumVal;
Chris Lattner2cda8792007-08-27 21:16:18 +00003127
3128 // Check for overflow on increment.
3129 if (EnumVal < LastEnumConst->getInitVal())
3130 Diag(IdLoc, diag::warn_enum_value_overflow);
3131
Chris Lattnere7f53a42007-08-27 17:37:24 +00003132 EltTy = LastEnumConst->getType();
3133 } else {
3134 // First value, set to zero.
3135 EltTy = Context.IntTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003136 EnumVal.zextOrTrunc(static_cast<uint32_t>(Context.getTypeSize(EltTy)));
Chris Lattnere7f53a42007-08-27 17:37:24 +00003137 }
Chris Lattner4b009652007-07-25 00:24:17 +00003138 }
3139
Chris Lattnere4650482008-03-15 06:12:44 +00003140 EnumConstantDecl *New =
Chris Lattnereee57c02008-04-04 06:12:32 +00003141 EnumConstantDecl::Create(Context, TheEnumDecl, IdLoc, Id, EltTy,
3142 Val, EnumVal,
Chris Lattner58114f02008-03-15 21:32:50 +00003143 LastEnumConst);
Chris Lattner4b009652007-07-25 00:24:17 +00003144
3145 // Register this decl in the current scope stack.
Argiris Kirtzidis951f25b2008-04-12 00:47:19 +00003146 PushOnScopeChains(New, S);
Douglas Gregor0c3ab042008-12-17 02:04:30 +00003147
3148 // Add this enumerator into the enum itself.
3149 // FIXME: This means that the enumerator is stored in two
3150 // DeclContexts. This is not a long-term solution.
3151 New->setLexicalDeclContext(TheEnumDecl);
3152 TheEnumDecl->addDecl(Context, New, true);
Chris Lattner4b009652007-07-25 00:24:17 +00003153 return New;
3154}
3155
Steve Naroffb0726b82008-08-07 14:08:16 +00003156// FIXME: For consistency with ActOnFields(), we should have the parser
3157// pass in the source location for the left/right braces.
Steve Naroff0acc9c92007-09-15 18:49:24 +00003158void Sema::ActOnEnumBody(SourceLocation EnumLoc, DeclTy *EnumDeclX,
Chris Lattner4b009652007-07-25 00:24:17 +00003159 DeclTy **Elements, unsigned NumElements) {
3160 EnumDecl *Enum = cast<EnumDecl>(static_cast<Decl*>(EnumDeclX));
Chris Lattner4b009652007-07-25 00:24:17 +00003161
Douglas Gregorae644892008-12-15 16:32:14 +00003162 if (Enum) {
3163 if (EnumDecl *Def = cast_or_null<EnumDecl>(Enum->getDefinition(Context))) {
3164 // Diagnose code like:
3165 // enum e0 {
3166 // E0 = sizeof(enum e0 { E1 })
3167 // };
3168 Diag(Def->getLocation(), diag::err_nested_redefinition)
3169 << Enum->getDeclName();
3170 Diag(Enum->getLocation(), diag::note_previous_definition);
3171 Enum->setInvalidDecl();
3172 return;
3173 }
Steve Naroffb0726b82008-08-07 14:08:16 +00003174 }
Chris Lattner435c3fd2007-08-28 05:10:31 +00003175 // TODO: If the result value doesn't fit in an int, it must be a long or long
3176 // long value. ISO C does not support this, but GCC does as an extension,
3177 // emit a warning.
Chris Lattner8cd0e932008-03-05 18:54:05 +00003178 unsigned IntWidth = Context.Target.getIntWidth();
Chris Lattner435c3fd2007-08-28 05:10:31 +00003179
Chris Lattner206754a2007-08-28 06:15:15 +00003180 // Verify that all the values are okay, compute the size of the values, and
3181 // reverse the list.
3182 unsigned NumNegativeBits = 0;
3183 unsigned NumPositiveBits = 0;
3184
3185 // Keep track of whether all elements have type int.
3186 bool AllElementsInt = true;
3187
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003188 QualType EnumType = Context.getTypeDeclType(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003189 EnumConstantDecl *EltList = 0;
3190 for (unsigned i = 0; i != NumElements; ++i) {
3191 EnumConstantDecl *ECD =
3192 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3193 if (!ECD) continue; // Already issued a diagnostic.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003194
3195 // If the enum value doesn't fit in an int, emit an extension warning.
Chris Lattnercb33ae12007-08-28 05:27:00 +00003196 const llvm::APSInt &InitVal = ECD->getInitVal();
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003197 assert(InitVal.getBitWidth() >= IntWidth &&
3198 "Should have promoted value to int");
Chris Lattnercb33ae12007-08-28 05:27:00 +00003199 if (InitVal.getBitWidth() > IntWidth) {
3200 llvm::APSInt V(InitVal);
3201 V.trunc(IntWidth);
3202 V.extend(InitVal.getBitWidth());
3203 if (V != InitVal)
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003204 Diag(ECD->getLocation(), diag::ext_enum_value_not_int)
3205 << InitVal.toString(10);
Chris Lattnercb33ae12007-08-28 05:27:00 +00003206 }
Chris Lattner206754a2007-08-28 06:15:15 +00003207
3208 // Keep track of the size of positive and negative values.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003209 if (InitVal.isUnsigned() || InitVal.isNonNegative())
Chris Lattneraff63f02008-01-14 21:47:29 +00003210 NumPositiveBits = std::max(NumPositiveBits,
3211 (unsigned)InitVal.getActiveBits());
Chris Lattner206754a2007-08-28 06:15:15 +00003212 else
Chris Lattneraff63f02008-01-14 21:47:29 +00003213 NumNegativeBits = std::max(NumNegativeBits,
3214 (unsigned)InitVal.getMinSignedBits());
Chris Lattner4b009652007-07-25 00:24:17 +00003215
Chris Lattner206754a2007-08-28 06:15:15 +00003216 // Keep track of whether every enum element has type int (very commmon).
3217 if (AllElementsInt)
3218 AllElementsInt = ECD->getType() == Context.IntTy;
3219
Chris Lattner4b009652007-07-25 00:24:17 +00003220 ECD->setNextDeclarator(EltList);
3221 EltList = ECD;
3222 }
3223
Chris Lattner206754a2007-08-28 06:15:15 +00003224 // Figure out the type that should be used for this enum.
3225 // FIXME: Support attribute(packed) on enums and -fshort-enums.
3226 QualType BestType;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003227 unsigned BestWidth;
Chris Lattner206754a2007-08-28 06:15:15 +00003228
3229 if (NumNegativeBits) {
3230 // If there is a negative value, figure out the smallest integer type (of
3231 // int/long/longlong) that fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003232 if (NumNegativeBits <= IntWidth && NumPositiveBits < IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003233 BestType = Context.IntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003234 BestWidth = IntWidth;
3235 } else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003236 BestWidth = Context.Target.getLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003237
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003238 if (NumNegativeBits <= BestWidth && NumPositiveBits < BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003239 BestType = Context.LongTy;
3240 else {
Chris Lattner8cd0e932008-03-05 18:54:05 +00003241 BestWidth = Context.Target.getLongLongWidth();
Ted Kremenekd7f64cd2007-12-12 22:39:36 +00003242
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003243 if (NumNegativeBits > BestWidth || NumPositiveBits >= BestWidth)
Chris Lattner206754a2007-08-28 06:15:15 +00003244 Diag(Enum->getLocation(), diag::warn_enum_too_large);
3245 BestType = Context.LongLongTy;
3246 }
3247 }
3248 } else {
3249 // If there is no negative value, figure out which of uint, ulong, ulonglong
3250 // fits.
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003251 if (NumPositiveBits <= IntWidth) {
Chris Lattner206754a2007-08-28 06:15:15 +00003252 BestType = Context.UnsignedIntTy;
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003253 BestWidth = IntWidth;
3254 } else if (NumPositiveBits <=
Chris Lattner8cd0e932008-03-05 18:54:05 +00003255 (BestWidth = Context.Target.getLongWidth())) {
Chris Lattner206754a2007-08-28 06:15:15 +00003256 BestType = Context.UnsignedLongTy;
Chris Lattner8cd0e932008-03-05 18:54:05 +00003257 } else {
3258 BestWidth = Context.Target.getLongLongWidth();
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003259 assert(NumPositiveBits <= BestWidth &&
Chris Lattner206754a2007-08-28 06:15:15 +00003260 "How could an initializer get larger than ULL?");
3261 BestType = Context.UnsignedLongLongTy;
3262 }
3263 }
3264
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003265 // Loop over all of the enumerator constants, changing their types to match
3266 // the type of the enum if needed.
3267 for (unsigned i = 0; i != NumElements; ++i) {
3268 EnumConstantDecl *ECD =
3269 cast_or_null<EnumConstantDecl>(static_cast<Decl*>(Elements[i]));
3270 if (!ECD) continue; // Already issued a diagnostic.
3271
3272 // Standard C says the enumerators have int type, but we allow, as an
3273 // extension, the enumerators to be larger than int size. If each
3274 // enumerator value fits in an int, type it as an int, otherwise type it the
3275 // same as the enumerator decl itself. This means that in "enum { X = 1U }"
3276 // that X has type 'int', not 'unsigned'.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003277 if (ECD->getType() == Context.IntTy) {
3278 // Make sure the init value is signed.
3279 llvm::APSInt IV = ECD->getInitVal();
3280 IV.setIsSigned(true);
3281 ECD->setInitVal(IV);
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003282
3283 if (getLangOptions().CPlusPlus)
3284 // C++ [dcl.enum]p4: Following the closing brace of an
3285 // enum-specifier, each enumerator has the type of its
3286 // enumeration.
3287 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003288 continue; // Already int type.
Chris Lattner6ea9bd42008-02-26 00:33:57 +00003289 }
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003290
3291 // Determine whether the value fits into an int.
3292 llvm::APSInt InitVal = ECD->getInitVal();
3293 bool FitsInInt;
3294 if (InitVal.isUnsigned() || !InitVal.isNegative())
3295 FitsInInt = InitVal.getActiveBits() < IntWidth;
3296 else
3297 FitsInInt = InitVal.getMinSignedBits() <= IntWidth;
3298
3299 // If it fits into an integer type, force it. Otherwise force it to match
3300 // the enum decl type.
3301 QualType NewTy;
3302 unsigned NewWidth;
3303 bool NewSign;
3304 if (FitsInInt) {
3305 NewTy = Context.IntTy;
3306 NewWidth = IntWidth;
3307 NewSign = true;
3308 } else if (ECD->getType() == BestType) {
3309 // Already the right type!
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003310 if (getLangOptions().CPlusPlus)
3311 // C++ [dcl.enum]p4: Following the closing brace of an
3312 // enum-specifier, each enumerator has the type of its
3313 // enumeration.
3314 ECD->setType(EnumType);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003315 continue;
3316 } else {
3317 NewTy = BestType;
3318 NewWidth = BestWidth;
3319 NewSign = BestType->isSignedIntegerType();
3320 }
3321
3322 // Adjust the APSInt value.
3323 InitVal.extOrTrunc(NewWidth);
3324 InitVal.setIsSigned(NewSign);
3325 ECD->setInitVal(InitVal);
3326
3327 // Adjust the Expr initializer and type.
Douglas Gregor70d26122008-11-12 17:17:38 +00003328 ECD->setInitExpr(new ImplicitCastExpr(NewTy, ECD->getInitExpr(),
3329 /*isLvalue=*/false));
Douglas Gregor6b5e34f2008-12-12 02:00:36 +00003330 if (getLangOptions().CPlusPlus)
3331 // C++ [dcl.enum]p4: Following the closing brace of an
3332 // enum-specifier, each enumerator has the type of its
3333 // enumeration.
3334 ECD->setType(EnumType);
3335 else
3336 ECD->setType(NewTy);
Chris Lattnerca01d0a2007-08-29 17:31:48 +00003337 }
Chris Lattner206754a2007-08-28 06:15:15 +00003338
Douglas Gregor8acb7272008-12-11 16:49:14 +00003339 Enum->completeDefinition(Context, BestType);
Chris Lattner33aad6e2008-02-06 00:51:33 +00003340 Consumer.HandleTagDeclDefinition(Enum);
Chris Lattner4b009652007-07-25 00:24:17 +00003341}
3342
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003343Sema::DeclTy *Sema::ActOnFileScopeAsmDecl(SourceLocation Loc,
Sebastian Redl91f9b0a2008-12-13 16:23:55 +00003344 ExprArg expr) {
3345 StringLiteral *AsmString = cast<StringLiteral>((Expr*)expr.release());
3346
Chris Lattner81db64a2008-03-16 00:16:02 +00003347 return FileScopeAsmDecl::Create(Context, Loc, AsmString);
Anders Carlsson4f7f4412008-02-08 00:33:21 +00003348}
3349
Douglas Gregorad17e372008-12-16 22:23:02 +00003350
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003351void Sema::ActOnPragmaPack(PragmaPackKind Kind, IdentifierInfo *Name,
3352 ExprTy *alignment, SourceLocation PragmaLoc,
3353 SourceLocation LParenLoc, SourceLocation RParenLoc) {
3354 Expr *Alignment = static_cast<Expr *>(alignment);
3355
3356 // If specified then alignment must be a "small" power of two.
3357 unsigned AlignmentVal = 0;
3358 if (Alignment) {
3359 llvm::APSInt Val;
3360 if (!Alignment->isIntegerConstantExpr(Val, Context) ||
3361 !Val.isPowerOf2() ||
3362 Val.getZExtValue() > 16) {
3363 Diag(PragmaLoc, diag::warn_pragma_pack_invalid_alignment);
3364 delete Alignment;
3365 return; // Ignore
3366 }
3367
3368 AlignmentVal = (unsigned) Val.getZExtValue();
3369 }
3370
3371 switch (Kind) {
3372 case Action::PPK_Default: // pack([n])
3373 PackContext.setAlignment(AlignmentVal);
3374 break;
3375
3376 case Action::PPK_Show: // pack(show)
3377 // Show the current alignment, making sure to show the right value
3378 // for the default.
3379 AlignmentVal = PackContext.getAlignment();
3380 // FIXME: This should come from the target.
3381 if (AlignmentVal == 0)
3382 AlignmentVal = 8;
Chris Lattnera5cc1882008-11-19 07:25:44 +00003383 Diag(PragmaLoc, diag::warn_pragma_pack_show) << AlignmentVal;
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003384 break;
3385
3386 case Action::PPK_Push: // pack(push [, id] [, [n])
3387 PackContext.push(Name);
3388 // Set the new alignment if specified.
3389 if (Alignment)
3390 PackContext.setAlignment(AlignmentVal);
3391 break;
3392
3393 case Action::PPK_Pop: // pack(pop [, id] [, n])
3394 // MSDN, C/C++ Preprocessor Reference > Pragma Directives > pack:
3395 // "#pragma pack(pop, identifier, n) is undefined"
3396 if (Alignment && Name)
3397 Diag(PragmaLoc, diag::warn_pragma_pack_pop_identifer_and_alignment);
3398
3399 // Do the pop.
3400 if (!PackContext.pop(Name)) {
3401 // If a name was specified then failure indicates the name
3402 // wasn't found. Otherwise failure indicates the stack was
3403 // empty.
Chris Lattner10f2c2e2008-11-20 06:38:18 +00003404 Diag(PragmaLoc, diag::warn_pragma_pack_pop_failed)
3405 << (Name ? "no record matching name" : "stack empty");
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003406
3407 // FIXME: Warn about popping named records as MSVC does.
3408 } else {
3409 // Pop succeeded, set the new alignment if specified.
3410 if (Alignment)
3411 PackContext.setAlignment(AlignmentVal);
3412 }
3413 break;
3414
3415 default:
3416 assert(0 && "Invalid #pragma pack kind.");
3417 }
3418}
3419
3420bool PragmaPackStack::pop(IdentifierInfo *Name) {
3421 if (Stack.empty())
3422 return false;
3423
3424 // If name is empty just pop top.
3425 if (!Name) {
3426 Alignment = Stack.back().first;
3427 Stack.pop_back();
3428 return true;
3429 }
3430
3431 // Otherwise, find the named record.
3432 for (unsigned i = Stack.size(); i != 0; ) {
3433 --i;
Daniel Dunbarc13c54c2008-11-19 10:32:38 +00003434 if (Stack[i].second == Name) {
Daniel Dunbar81c7d472008-10-14 05:35:18 +00003435 // Found it, pop up to and including this record.
3436 Alignment = Stack[i].first;
3437 Stack.erase(Stack.begin() + i, Stack.end());
3438 return true;
3439 }
3440 }
3441
3442 return false;
3443}